-
# frozen_string_literal: true
-
-
25
require "httpx/version"
-
-
# Top-Level Namespace
-
#
-
25
module HTTPX
-
25
EMPTY = [].freeze
-
25
EMPTY_HASH = {}.freeze
-
-
# All plugins should be stored under this module/namespace. Can register and load
-
# plugins.
-
#
-
25
module Plugins
-
25
@plugins = {}
-
25
@plugins_mutex = Thread::Mutex.new
-
-
# Loads a plugin based on a name. If the plugin hasn't been loaded, tries to load
-
# it from the load path under "httpx/plugins/" directory.
-
#
-
25
def self.load_plugin(name)
-
4482
h = @plugins
-
4482
m = @plugins_mutex
-
8964
unless (plugin = m.synchronize { h[name] })
-
214
require "httpx/plugins/#{name}"
-
428
raise "Plugin #{name} hasn't been registered" unless (plugin = m.synchronize { h[name] })
-
end
-
4482
plugin
-
end
-
-
# Registers a plugin (+mod+) in the central store indexed by +name+.
-
#
-
25
def self.register_plugin(name, mod)
-
272
h = @plugins
-
272
m = @plugins_mutex
-
544
m.synchronize { h[name] = mod }
-
end
-
end
-
end
-
-
25
require "httpx/extensions"
-
-
25
require "httpx/errors"
-
25
require "httpx/utils"
-
25
require "httpx/punycode"
-
25
require "httpx/domain_name"
-
25
require "httpx/altsvc"
-
25
require "httpx/callbacks"
-
25
require "httpx/loggable"
-
25
require "httpx/transcoder"
-
25
require "httpx/timers"
-
25
require "httpx/pool"
-
25
require "httpx/headers"
-
25
require "httpx/request"
-
25
require "httpx/response"
-
25
require "httpx/options"
-
25
require "httpx/chainable"
-
-
25
require "httpx/session"
-
25
require "httpx/session_extensions"
-
-
# load integrations when possible
-
-
25
require "httpx/adapters/datadog" if defined?(DDTrace) || defined?(Datadog::Tracing)
-
25
require "httpx/adapters/sentry" if defined?(Sentry)
-
25
require "httpx/adapters/webmock" if defined?(WebMock)
-
# frozen_string_literal: true
-
-
6
require "datadog/tracing/contrib/integration"
-
6
require "datadog/tracing/contrib/configuration/settings"
-
6
require "datadog/tracing/contrib/patcher"
-
-
6
module Datadog::Tracing
-
6
module Contrib
-
6
module HTTPX
-
6
DATADOG_VERSION = defined?(::DDTrace) ? ::DDTrace::VERSION : ::Datadog::VERSION
-
-
6
METADATA_MODULE = Datadog::Tracing::Metadata
-
-
6
TYPE_OUTBOUND = Datadog::Tracing::Metadata::Ext::HTTP::TYPE_OUTBOUND
-
-
6
TAG_BASE_SERVICE = Datadog::Tracing::Contrib::Ext::Metadata::TAG_BASE_SERVICE
-
6
TAG_PEER_HOSTNAME = Datadog::Tracing::Metadata::Ext::TAG_PEER_HOSTNAME
-
-
6
TAG_KIND = Datadog::Tracing::Metadata::Ext::TAG_KIND
-
6
TAG_CLIENT = Datadog::Tracing::Metadata::Ext::SpanKind::TAG_CLIENT
-
6
TAG_COMPONENT = Datadog::Tracing::Metadata::Ext::TAG_COMPONENT
-
6
TAG_OPERATION = Datadog::Tracing::Metadata::Ext::TAG_OPERATION
-
6
TAG_URL = Datadog::Tracing::Metadata::Ext::HTTP::TAG_URL
-
6
TAG_METHOD = Datadog::Tracing::Metadata::Ext::HTTP::TAG_METHOD
-
6
TAG_TARGET_HOST = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_HOST
-
6
TAG_TARGET_PORT = Datadog::Tracing::Metadata::Ext::NET::TAG_TARGET_PORT
-
-
6
TAG_STATUS_CODE = Datadog::Tracing::Metadata::Ext::HTTP::TAG_STATUS_CODE
-
-
# HTTPX Datadog Plugin
-
#
-
# Enables tracing for httpx requests.
-
#
-
# A span will be created for each request transaction; the span is created lazily only when
-
# buffering a request, and it is fed the start time stored inside the tracer object.
-
#
-
6
module Plugin
-
6
module RequestTracer
-
6
extend Contrib::HttpAnnotationHelper
-
-
6
module_function
-
-
6
SPAN_REQUEST = "httpx.request"
-
-
# initializes tracing on the +request+.
-
6
def call(request)
-
165
return unless configuration(request).enabled
-
-
84
span = nil
-
-
# request objects are reused, when already buffered requests get rerouted to a different
-
# connection due to connection issues, or when they already got a response, but need to
-
# be retried. In such situations, the original span needs to be extended for the former,
-
# while a new is required for the latter.
-
84
request.on(:idle) do
-
18
span = nil
-
end
-
# the span is initialized when the request is buffered in the parser, which is the closest
-
# one gets to actually sending the request.
-
84
request.on(:headers) do
-
96
next if span
-
-
96
span = initialize_span(request, now)
-
end
-
-
84
request.on(:response) do |response|
-
96
unless span
-
6
next unless response.is_a?(::HTTPX::ErrorResponse) && response.error.respond_to?(:connection)
-
-
# handles the case when the +error+ happened during name resolution, which means
-
# that the tracing start point hasn't been triggered yet; in such cases, the approximate
-
# initial resolving time is collected from the connection, and used as span start time,
-
# and the tracing object in inserted before the on response callback is called.
-
6
span = initialize_span(request, response.error.connection.init_time)
-
-
end
-
-
96
finish(response, span)
-
end
-
end
-
-
6
def finish(response, span)
-
96
if response.is_a?(::HTTPX::ErrorResponse)
-
6
span.set_error(response.error)
-
else
-
90
span.set_tag(TAG_STATUS_CODE, response.status.to_s)
-
-
90
span.set_error(::HTTPX::HTTPError.new(response)) if response.status >= 400 && response.status <= 599
-
-
90
span.set_tags(
-
Datadog.configuration.tracing.header_tags.response_tags(response.headers.to_h)
-
)
-
end
-
-
96
span.finish
-
end
-
-
# return a span initialized with the +@request+ state.
-
6
def initialize_span(request, start_time)
-
102
verb = request.verb
-
102
uri = request.uri
-
-
102
config = configuration(request)
-
-
102
span = create_span(request, config, start_time)
-
-
102
span.resource = verb
-
-
# Tag original global service name if not used
-
102
span.set_tag(TAG_BASE_SERVICE, Datadog.configuration.service) if span.service != Datadog.configuration.service
-
-
102
span.set_tag(TAG_KIND, TAG_CLIENT)
-
-
102
span.set_tag(TAG_COMPONENT, "httpx")
-
102
span.set_tag(TAG_OPERATION, "request")
-
-
102
span.set_tag(TAG_URL, request.path)
-
102
span.set_tag(TAG_METHOD, verb)
-
-
102
span.set_tag(TAG_TARGET_HOST, uri.host)
-
102
span.set_tag(TAG_TARGET_PORT, uri.port)
-
-
102
span.set_tag(TAG_PEER_HOSTNAME, uri.host)
-
-
# Tag as an external peer service
-
# span.set_tag(TAG_PEER_SERVICE, span.service)
-
-
102
if config[:distributed_tracing]
-
96
propagate_trace_http(
-
Datadog::Tracing.active_trace,
-
request.headers
-
)
-
end
-
-
# Set analytics sample rate
-
102
if Contrib::Analytics.enabled?(config[:analytics_enabled])
-
12
Contrib::Analytics.set_sample_rate(span, config[:analytics_sample_rate])
-
end
-
-
102
span.set_tags(
-
Datadog.configuration.tracing.header_tags.request_tags(request.headers.to_h)
-
)
-
-
102
span
-
rescue StandardError => e
-
Datadog.logger.error("error preparing span for http request: #{e}")
-
Datadog.logger.error(e.backtrace)
-
end
-
-
6
def now
-
96
::Datadog::Core::Utils::Time.now.utc
-
end
-
-
6
def configuration(request)
-
267
Datadog.configuration.tracing[:httpx, request.uri.host]
-
end
-
-
6
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("2.0.0")
-
3
def propagate_trace_http(trace, headers)
-
48
Datadog::Tracing::Contrib::HTTP.inject(trace, headers)
-
end
-
-
3
def create_span(request, configuration, start_time)
-
51
Datadog::Tracing.trace(
-
SPAN_REQUEST,
-
service: service_name(request.uri.host, configuration),
-
type: TYPE_OUTBOUND,
-
start_time: start_time
-
)
-
end
-
else
-
3
def propagate_trace_http(trace, headers)
-
48
Datadog::Tracing::Propagation::HTTP.inject!(trace.to_digest, headers)
-
end
-
-
3
def create_span(request, configuration, start_time)
-
51
Datadog::Tracing.trace(
-
SPAN_REQUEST,
-
service: service_name(request.uri.host, configuration),
-
span_type: TYPE_OUTBOUND,
-
start_time: start_time
-
)
-
end
-
end
-
end
-
-
6
module RequestMethods
-
# intercepts request initialization to inject the tracing logic.
-
6
def initialize(*)
-
165
super
-
-
165
return unless Datadog::Tracing.enabled?
-
-
165
RequestTracer.call(self)
-
end
-
end
-
-
6
module ConnectionMethods
-
6
attr_reader :init_time
-
-
6
def initialize(*)
-
155
super
-
-
155
@init_time = ::Datadog::Core::Utils::Time.now.utc
-
end
-
end
-
end
-
-
6
module Configuration
-
# Default settings for httpx
-
#
-
6
class Settings < Datadog::Tracing::Contrib::Configuration::Settings
-
6
DEFAULT_ERROR_HANDLER = lambda do |response|
-
Datadog::Ext::HTTP::ERROR_RANGE.cover?(response.status)
-
end
-
-
6
option :service_name, default: "httpx"
-
6
option :distributed_tracing, default: true
-
6
option :split_by_domain, default: false
-
-
6
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
6
option :enabled do |o|
-
6
o.type :bool
-
6
o.env "DD_TRACE_HTTPX_ENABLED"
-
6
o.default true
-
end
-
-
6
option :analytics_enabled do |o|
-
6
o.type :bool
-
6
o.env "DD_TRACE_HTTPX_ANALYTICS_ENABLED"
-
6
o.default false
-
end
-
-
6
option :analytics_sample_rate do |o|
-
6
o.type :float
-
6
o.env "DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE"
-
6
o.default 1.0
-
end
-
else
-
option :enabled do |o|
-
o.default { env_to_bool("DD_TRACE_HTTPX_ENABLED", true) }
-
o.lazy
-
end
-
-
option :analytics_enabled do |o|
-
o.default { env_to_bool(%w[DD_TRACE_HTTPX_ANALYTICS_ENABLED DD_HTTPX_ANALYTICS_ENABLED], false) }
-
o.lazy
-
end
-
-
option :analytics_sample_rate do |o|
-
o.default { env_to_float(%w[DD_TRACE_HTTPX_ANALYTICS_SAMPLE_RATE DD_HTTPX_ANALYTICS_SAMPLE_RATE], 1.0) }
-
o.lazy
-
end
-
end
-
-
6
if defined?(Datadog::Tracing::Contrib::SpanAttributeSchema)
-
6
option :service_name do |o|
-
6
o.default do
-
66
Datadog::Tracing::Contrib::SpanAttributeSchema.fetch_service_name(
-
"DD_TRACE_HTTPX_SERVICE_NAME",
-
"httpx"
-
)
-
end
-
6
o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
end
-
else
-
option :service_name do |o|
-
o.default do
-
ENV.fetch("DD_TRACE_HTTPX_SERVICE_NAME", "httpx")
-
end
-
o.lazy unless Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
end
-
end
-
-
6
option :distributed_tracing, default: true
-
-
6
if Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.15.0")
-
6
option :error_handler do |o|
-
6
o.type :proc
-
6
o.default_proc(&DEFAULT_ERROR_HANDLER)
-
end
-
elsif Gem::Version.new(DATADOG_VERSION::STRING) >= Gem::Version.new("1.13.0")
-
option :error_handler do |o|
-
o.type :proc
-
o.experimental_default_proc(&DEFAULT_ERROR_HANDLER)
-
end
-
else
-
option :error_handler, default: DEFAULT_ERROR_HANDLER
-
end
-
end
-
end
-
-
# Patcher enables patching of 'httpx' with datadog components.
-
#
-
6
module Patcher
-
6
include Datadog::Tracing::Contrib::Patcher
-
-
6
module_function
-
-
6
def target_version
-
12
Integration.version
-
end
-
-
# loads a session instannce with the datadog plugin, and replaces the
-
# base HTTPX::Session with the patched session class.
-
6
def patch
-
6
datadog_session = ::HTTPX.plugin(Plugin)
-
-
6
::HTTPX.send(:remove_const, :Session)
-
6
::HTTPX.send(:const_set, :Session, datadog_session.class)
-
end
-
end
-
-
# Datadog Integration for HTTPX.
-
#
-
6
class Integration
-
6
include Contrib::Integration
-
-
6
MINIMUM_VERSION = Gem::Version.new("0.10.2")
-
-
6
register_as :httpx
-
-
6
def self.version
-
246
Gem.loaded_specs["httpx"] && Gem.loaded_specs["httpx"].version
-
end
-
-
6
def self.loaded?
-
78
defined?(::HTTPX::Request)
-
end
-
-
6
def self.compatible?
-
78
super && version >= MINIMUM_VERSION
-
end
-
-
6
def new_configuration
-
156
Configuration::Settings.new
-
end
-
-
6
def patcher
-
156
Patcher
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
13
require "delegate"
-
13
require "httpx"
-
13
require "faraday"
-
-
13
module Faraday
-
13
class Adapter
-
13
class HTTPX < Faraday::Adapter
-
13
module RequestMixin
-
13
def build_connection(env)
-
229
return @connection if defined?(@connection)
-
-
229
@connection = ::HTTPX.plugin(:persistent).plugin(ReasonPlugin)
-
229
@connection = @connection.with(@connection_options) unless @connection_options.empty?
-
229
connection_opts = options_from_env(env)
-
-
229
if (bind = env.request.bind)
-
6
@bind = TCPSocket.new(bind[:host], bind[:port])
-
6
connection_opts[:io] = @bind
-
end
-
229
@connection = @connection.with(connection_opts)
-
-
229
if (proxy = env.request.proxy)
-
6
proxy_options = { uri: proxy.uri }
-
6
proxy_options[:username] = proxy.user if proxy.user
-
6
proxy_options[:password] = proxy.password if proxy.password
-
-
6
@connection = @connection.plugin(:proxy).with(proxy: proxy_options)
-
end
-
229
@connection = @connection.plugin(OnDataPlugin) if env.request.stream_response?
-
-
229
@connection = @config_block.call(@connection) || @connection if @config_block
-
229
@connection
-
end
-
-
13
def close
-
234
@connection.close if @connection
-
234
@bind.close if @bind
-
end
-
-
13
private
-
-
13
def connect(env, &blk)
-
229
connection(env, &blk)
-
rescue ::HTTPX::TLSError => e
-
6
raise Faraday::SSLError, e
-
rescue Errno::ECONNABORTED,
-
Errno::ECONNREFUSED,
-
Errno::ECONNRESET,
-
Errno::EHOSTUNREACH,
-
Errno::EINVAL,
-
Errno::ENETUNREACH,
-
Errno::EPIPE,
-
::HTTPX::ConnectionError => e
-
6
raise Faraday::ConnectionFailed, e
-
end
-
-
13
def build_request(env)
-
235
meth = env[:method]
-
-
request_options = {
-
235
headers: env.request_headers,
-
body: env.body,
-
**options_from_env(env),
-
}
-
235
[meth.to_s.upcase, env.url, request_options]
-
end
-
-
13
def options_from_env(env)
-
464
timeout_options = {}
-
464
req_opts = env.request
-
464
if (sec = request_timeout(:read, req_opts))
-
24
timeout_options[:read_timeout] = sec
-
end
-
-
464
if (sec = request_timeout(:write, req_opts))
-
12
timeout_options[:write_timeout] = sec
-
end
-
-
464
if (sec = request_timeout(:open, req_opts))
-
12
timeout_options[:connect_timeout] = sec
-
end
-
-
{
-
464
ssl: ssl_options_from_env(env),
-
timeout: timeout_options,
-
}
-
end
-
-
13
if defined?(::OpenSSL)
-
13
def ssl_options_from_env(env)
-
464
ssl_options = {}
-
-
464
unless env.ssl.verify.nil?
-
24
ssl_options[:verify_mode] = env.ssl.verify ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
-
end
-
-
464
ssl_options[:ca_file] = env.ssl.ca_file if env.ssl.ca_file
-
464
ssl_options[:ca_path] = env.ssl.ca_path if env.ssl.ca_path
-
464
ssl_options[:cert_store] = env.ssl.cert_store if env.ssl.cert_store
-
464
ssl_options[:cert] = env.ssl.client_cert if env.ssl.client_cert
-
464
ssl_options[:key] = env.ssl.client_key if env.ssl.client_key
-
464
ssl_options[:ssl_version] = env.ssl.version if env.ssl.version
-
464
ssl_options[:verify_depth] = env.ssl.verify_depth if env.ssl.verify_depth
-
464
ssl_options[:min_version] = env.ssl.min_version if env.ssl.min_version
-
464
ssl_options[:max_version] = env.ssl.max_version if env.ssl.max_version
-
464
ssl_options
-
end
-
else
-
skipped
# :nocov:
-
skipped
def ssl_options_from_env(*)
-
skipped
{}
-
skipped
end
-
skipped
# :nocov:
-
end
-
end
-
-
13
include RequestMixin
-
-
13
module OnDataPlugin
-
13
module RequestMethods
-
13
attr_writer :response_on_data
-
-
13
def response=(response)
-
12
super
-
-
12
return if response.is_a?(::HTTPX::ErrorResponse)
-
-
12
response.body.on_data = @response_on_data
-
end
-
end
-
-
13
module ResponseBodyMethods
-
13
attr_writer :on_data
-
-
13
def write(chunk)
-
39
return super unless @on_data
-
-
39
@on_data.call(chunk, chunk.bytesize)
-
end
-
end
-
end
-
-
13
module ReasonPlugin
-
13
def self.load_dependencies(*)
-
229
require "net/http/status"
-
end
-
-
13
module ResponseMethods
-
13
def reason
-
193
Net::HTTP::STATUS_CODES.fetch(@status, "Non-Standard status code")
-
end
-
end
-
end
-
-
13
class ParallelManager
-
13
class ResponseHandler < SimpleDelegator
-
13
attr_reader :env
-
-
13
def initialize(env)
-
24
@env = env
-
24
super
-
end
-
-
13
def on_response(&blk)
-
48
if blk
-
24
@on_response = ->(response) do
-
24
blk.call(response)
-
end
-
24
self
-
else
-
24
@on_response
-
end
-
end
-
-
13
def on_complete(&blk)
-
24
if blk
-
@on_complete = blk
-
self
-
else
-
24
@on_complete
-
end
-
end
-
end
-
-
13
include RequestMixin
-
-
13
def initialize(options)
-
24
@handlers = []
-
24
@connection_options = options
-
end
-
-
13
def enqueue(request)
-
24
handler = ResponseHandler.new(request)
-
24
@handlers << handler
-
24
handler
-
end
-
-
13
def run
-
24
return unless @handlers.last
-
-
18
env = @handlers.last.env
-
-
18
connect(env) do |session|
-
42
requests = @handlers.map { |handler| session.build_request(*build_request(handler.env)) }
-
-
18
if env.request.stream_response?
-
6
requests.each do |request|
-
6
request.response_on_data = env.request.on_data
-
end
-
end
-
-
18
responses = session.request(*requests)
-
18
Array(responses).each_with_index do |response, index|
-
24
handler = @handlers[index]
-
24
handler.on_response.call(response)
-
24
handler.on_complete.call(handler.env) if handler.on_complete
-
end
-
end
-
rescue ::HTTPX::TimeoutError => e
-
raise Faraday::TimeoutError, e
-
end
-
-
# from Faraday::Adapter#connection
-
13
def connection(env)
-
18
conn = build_connection(env)
-
18
return conn unless block_given?
-
-
18
yield conn
-
end
-
-
13
private
-
-
# from Faraday::Adapter#request_timeout
-
13
def request_timeout(type, options)
-
126
key = Faraday::Adapter::TIMEOUT_KEYS[type]
-
126
options[key] || options[:timeout]
-
end
-
end
-
-
13
self.supports_parallel = true
-
-
13
class << self
-
13
def setup_parallel_manager(options = {})
-
24
ParallelManager.new(options)
-
end
-
end
-
-
13
def call(env)
-
235
super
-
235
if parallel?(env)
-
24
handler = env[:parallel_manager].enqueue(env)
-
24
handler.on_response do |response|
-
24
if response.is_a?(::HTTPX::Response)
-
18
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
18
response_headers.merge!(response.headers)
-
end
-
else
-
6
env[:error] = response.error
-
6
save_response(env, 0, "", {}, nil)
-
end
-
end
-
24
return handler
-
end
-
-
211
response = connect_and_request(env)
-
175
save_response(env, response.status, response.body.to_s, response.headers, response.reason) do |response_headers|
-
175
response_headers.merge!(response.headers)
-
end
-
175
@app.call(env)
-
end
-
-
13
private
-
-
13
def connect_and_request(env)
-
211
connect(env) do |session|
-
211
request = session.build_request(*build_request(env))
-
-
211
request.response_on_data = env.request.on_data if env.request.stream_response?
-
-
211
response = session.request(request)
-
# do not call #raise_for_status for HTTP 4xx or 5xx, as faraday has a middleware for that.
-
211
response.raise_for_status unless response.is_a?(::HTTPX::Response)
-
175
response
-
end
-
rescue ::HTTPX::TimeoutError => e
-
18
raise Faraday::TimeoutError, e
-
end
-
-
13
def parallel?(env)
-
235
env[:parallel_manager]
-
end
-
end
-
-
13
register_middleware httpx: HTTPX
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "sentry-ruby"
-
-
6
module HTTPX::Plugins
-
6
module Sentry
-
6
module Tracer
-
6
module_function
-
-
6
def call(request)
-
129
sentry_span = start_sentry_span
-
-
129
return unless sentry_span
-
-
129
set_sentry_trace_header(request, sentry_span)
-
-
129
request.on(:response, &method(:finish_sentry_span).curry(3)[sentry_span, request])
-
end
-
-
6
def start_sentry_span
-
129
return unless ::Sentry.initialized? && (span = ::Sentry.get_current_scope.get_span)
-
129
return if span.sampled == false
-
-
129
span.start_child(op: "httpx.client", start_timestamp: ::Sentry.utc_now.to_f)
-
end
-
-
6
def set_sentry_trace_header(request, sentry_span)
-
129
return unless sentry_span
-
-
129
config = ::Sentry.configuration
-
129
url = request.uri.to_s
-
-
258
return unless config.propagate_traces && config.trace_propagation_targets.any? { |target| url.match?(target) }
-
-
129
trace = ::Sentry.get_current_client.generate_sentry_trace(sentry_span)
-
129
request.headers[::Sentry::SENTRY_TRACE_HEADER_NAME] = trace if trace
-
end
-
-
6
def finish_sentry_span(span, request, response)
-
137
return unless ::Sentry.initialized?
-
-
137
record_sentry_breadcrumb(request, response)
-
137
record_sentry_span(request, response, span)
-
end
-
-
6
def record_sentry_breadcrumb(req, res)
-
137
return unless ::Sentry.configuration.breadcrumbs_logger.include?(:http_logger)
-
-
137
request_info = extract_request_info(req)
-
-
137
data = if res.is_a?(HTTPX::ErrorResponse)
-
13
{ error: res.error.message, **request_info }
-
else
-
124
{ status: res.status, **request_info }
-
end
-
-
137
crumb = ::Sentry::Breadcrumb.new(
-
level: :info,
-
category: "httpx",
-
type: :info,
-
data: data
-
)
-
137
::Sentry.add_breadcrumb(crumb)
-
end
-
-
6
def record_sentry_span(req, res, sentry_span)
-
137
return unless sentry_span
-
-
137
request_info = extract_request_info(req)
-
137
sentry_span.set_description("#{request_info[:method]} #{request_info[:url]}")
-
137
if res.is_a?(HTTPX::ErrorResponse)
-
13
sentry_span.set_data(:error, res.error.message)
-
else
-
124
sentry_span.set_data(:status, res.status)
-
end
-
137
sentry_span.set_timestamp(::Sentry.utc_now.to_f)
-
end
-
-
6
def extract_request_info(req)
-
274
uri = req.uri
-
-
result = {
-
274
method: req.verb,
-
}
-
-
274
if ::Sentry.configuration.send_default_pii
-
24
uri += "?#{req.query}" unless req.query.empty?
-
24
result[:body] = req.body.to_s unless req.body.empty? || req.body.unbounded_body?
-
end
-
-
274
result[:url] = uri.to_s
-
-
274
result
-
end
-
end
-
-
6
module RequestMethods
-
6
def __sentry_enable_trace!
-
137
return if @__sentry_enable_trace
-
-
129
Tracer.call(self)
-
129
@__sentry_enable_trace = true
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def send(request)
-
137
request.__sentry_enable_trace!
-
-
137
super
-
end
-
end
-
end
-
end
-
-
6
Sentry.register_patch(:httpx) do
-
30
sentry_session = HTTPX.plugin(HTTPX::Plugins::Sentry)
-
-
30
HTTPX.send(:remove_const, :Session)
-
30
HTTPX.send(:const_set, :Session, sentry_session.class)
-
end
-
# frozen_string_literal: true
-
-
8
module WebMock
-
8
module HttpLibAdapters
-
8
require "net/http/status"
-
8
HTTP_REASONS = Net::HTTP::STATUS_CODES
-
-
#
-
# HTTPX plugin for webmock.
-
#
-
# Requests are "hijacked" at the session, before they're distributed to a connection.
-
#
-
8
module Plugin
-
8
class << self
-
8
def build_webmock_request_signature(request)
-
188
uri = WebMock::Util::URI.heuristic_parse(request.uri)
-
188
uri.query = request.query
-
188
uri.path = uri.normalized_path.gsub("[^:]//", "/")
-
-
188
WebMock::RequestSignature.new(
-
request.verb.downcase.to_sym,
-
uri.to_s,
-
body: request.body.to_s,
-
headers: request.headers.to_h
-
)
-
end
-
-
8
def build_webmock_response(_request, response)
-
6
webmock_response = WebMock::Response.new
-
6
webmock_response.status = [response.status, HTTP_REASONS[response.status]]
-
6
webmock_response.body = response.body.to_s
-
6
webmock_response.headers = response.headers.to_h
-
6
webmock_response
-
end
-
-
8
def build_from_webmock_response(request, webmock_response)
-
158
return build_error_response(request, HTTPX::TimeoutError.new(1, "Timed out")) if webmock_response.should_timeout
-
-
140
return build_error_response(request, webmock_response.exception) if webmock_response.exception
-
-
133
request.options.response_class.new(request,
-
webmock_response.status[0],
-
"2.0",
-
webmock_response.headers).tap do |res|
-
133
res.mocked = true
-
end
-
end
-
-
8
def build_error_response(request, exception)
-
25
HTTPX::ErrorResponse.new(request, exception)
-
end
-
end
-
-
8
module InstanceMethods
-
8
private
-
-
8
def do_init_connection(connection, selector)
-
170
super
-
-
170
connection.once(:unmock_connection) do
-
24
next unless connection.current_session == self
-
-
24
unless connection.addresses
-
# reset Happy Eyeballs, fail early
-
24
connection.sibling = nil
-
-
24
deselect_connection(connection, selector)
-
end
-
24
resolve_connection(connection, selector)
-
end
-
end
-
end
-
-
8
module ResponseMethods
-
8
attr_accessor :mocked
-
-
8
def initialize(*)
-
157
super
-
157
@mocked = false
-
end
-
end
-
-
8
module ResponseBodyMethods
-
8
def decode_chunk(chunk)
-
96
return chunk if @response.mocked
-
-
42
super
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def initialize(*)
-
170
super
-
170
@mocked = true
-
end
-
-
8
def open?
-
194
return true if @mocked
-
-
24
super
-
end
-
-
8
def interests
-
278
return if @mocked
-
-
246
super
-
end
-
-
8
def terminate
-
145
force_reset
-
end
-
-
8
def send(request)
-
188
request_signature = Plugin.build_webmock_request_signature(request)
-
188
WebMock::RequestRegistry.instance.requested_signatures.put(request_signature)
-
-
188
if (mock_response = WebMock::StubRegistry.instance.response_for_request(request_signature))
-
158
response = Plugin.build_from_webmock_response(request, mock_response)
-
158
WebMock::CallbackRegistry.invoke_callbacks({ lib: :httpx }, request_signature, mock_response)
-
158
log { "mocking #{request.uri} with #{mock_response.inspect}" }
-
158
request.transition(:headers)
-
158
request.transition(:body)
-
158
request.transition(:trailers)
-
158
request.transition(:done)
-
158
response.finish!
-
158
request.response = response
-
158
request.emit(:response, response)
-
158
request_signature.headers = request.headers.to_h
-
-
158
response << mock_response.body.dup unless response.is_a?(HTTPX::ErrorResponse)
-
30
elsif WebMock.net_connect_allowed?(request_signature.uri)
-
24
if WebMock::CallbackRegistry.any_callbacks?
-
6
request.on(:response) do |resp|
-
6
unless resp.is_a?(HTTPX::ErrorResponse)
-
6
webmock_response = Plugin.build_webmock_response(request, resp)
-
6
WebMock::CallbackRegistry.invoke_callbacks(
-
{ lib: :httpx, real_request: true }, request_signature,
-
webmock_response
-
)
-
end
-
end
-
end
-
24
@mocked = false
-
24
emit(:unmock_connection, self)
-
24
super
-
else
-
6
raise WebMock::NetConnectNotAllowedError, request_signature
-
end
-
end
-
end
-
end
-
-
8
class HttpxAdapter < HttpLibAdapter
-
8
adapter_for :httpx
-
-
8
class << self
-
8
def enable!
-
370
@original_session ||= HTTPX::Session
-
-
370
webmock_session = HTTPX.plugin(Plugin)
-
-
370
HTTPX.send(:remove_const, :Session)
-
370
HTTPX.send(:const_set, :Session, webmock_session.class)
-
end
-
-
8
def disable!
-
370
return unless @original_session
-
-
362
HTTPX.send(:remove_const, :Session)
-
362
HTTPX.send(:const_set, :Session, @original_session)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "strscan"
-
-
25
module HTTPX
-
25
module AltSvc
-
# makes connections able to accept requests destined to primary service.
-
25
module ConnectionMixin
-
25
using URIExtensions
-
-
25
def send(request)
-
6
request.headers["alt-used"] = @origin.authority if @parser && !@write_buffer.full? && match_altsvcs?(request.uri)
-
-
6
super
-
end
-
-
25
def match?(uri, options)
-
6
return false if !used? && (@state == :closing || @state == :closed)
-
-
6
match_altsvcs?(uri) && match_altsvc_options?(uri, options)
-
end
-
-
25
private
-
-
# checks if this is connection is an alternative service of
-
# +uri+
-
25
def match_altsvcs?(uri)
-
18
@origins.any? { |origin| altsvc_match?(uri, origin) } ||
-
AltSvc.cached_altsvc(@origin).any? do |altsvc|
-
origin = altsvc["origin"]
-
altsvc_match?(origin, uri.origin)
-
end
-
end
-
-
25
def match_altsvc_options?(uri, options)
-
6
return @options == options unless @options.ssl.all? do |k, v|
-
6
v == (k == :hostname ? uri.host : options.ssl[k])
-
end
-
-
6
@options.options_equals?(options, Options::REQUEST_BODY_IVARS + %i[@ssl])
-
end
-
-
25
def altsvc_match?(uri, other_uri)
-
12
other_uri = URI(other_uri)
-
-
12
uri.origin == other_uri.origin || begin
-
6
case uri.scheme
-
when "h2"
-
(other_uri.scheme == "https" || other_uri.scheme == "h2") &&
-
uri.host == other_uri.host &&
-
uri.port == other_uri.port
-
else
-
6
false
-
end
-
end
-
end
-
end
-
-
25
@altsvc_mutex = Thread::Mutex.new
-
43
@altsvcs = Hash.new { |h, k| h[k] = [] }
-
-
25
module_function
-
-
25
def cached_altsvc(origin)
-
30
now = Utils.now
-
30
@altsvc_mutex.synchronize do
-
30
lookup(origin, now)
-
end
-
end
-
-
25
def cached_altsvc_set(origin, entry)
-
18
now = Utils.now
-
18
@altsvc_mutex.synchronize do
-
18
return if @altsvcs[origin].any? { |altsvc| altsvc["origin"] == entry["origin"] }
-
-
18
entry["TTL"] = Integer(entry["ma"]) + now if entry.key?("ma")
-
18
@altsvcs[origin] << entry
-
18
entry
-
end
-
end
-
-
25
def lookup(origin, ttl)
-
30
return [] unless @altsvcs.key?(origin)
-
-
24
@altsvcs[origin] = @altsvcs[origin].select do |entry|
-
18
!entry.key?("TTL") || entry["TTL"] > ttl
-
end
-
36
@altsvcs[origin].reject { |entry| entry["noop"] }
-
end
-
-
25
def emit(request, response)
-
6314
return unless response.respond_to?(:headers)
-
# Alt-Svc
-
6278
return unless response.headers.key?("alt-svc")
-
-
64
origin = request.origin
-
64
host = request.uri.host
-
-
64
altsvc = response.headers["alt-svc"]
-
-
# https://datatracker.ietf.org/doc/html/rfc7838#section-3
-
# A field value containing the special value "clear" indicates that the
-
# origin requests all alternatives for that origin to be invalidated
-
# (including those specified in the same response, in case of an
-
# invalid reply containing both "clear" and alternative services).
-
64
if altsvc == "clear"
-
6
@altsvc_mutex.synchronize do
-
6
@altsvcs[origin].clear
-
end
-
-
6
return
-
end
-
-
58
parse(altsvc) do |alt_origin, alt_params|
-
6
alt_origin.host ||= host
-
6
yield(alt_origin, origin, alt_params)
-
end
-
end
-
-
25
def parse(altsvc)
-
142
return enum_for(__method__, altsvc) unless block_given?
-
-
100
scanner = StringScanner.new(altsvc)
-
100
until scanner.eos?
-
100
alt_service = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
-
100
alt_params = []
-
100
loop do
-
118
alt_param = scanner.scan(/[^=]+=("[^"]+"|[^;,]+)/)
-
118
alt_params << alt_param.strip if alt_param
-
118
scanner.skip(/;/)
-
118
break if scanner.eos? || scanner.scan(/ *, */)
-
end
-
200
alt_params = Hash[alt_params.map { |field| field.split("=", 2) }]
-
-
100
alt_proto, alt_authority = alt_service.split("=", 2)
-
100
alt_origin = parse_altsvc_origin(alt_proto, alt_authority)
-
100
return unless alt_origin
-
-
36
yield(alt_origin, alt_params.merge("proto" => alt_proto))
-
end
-
end
-
-
25
def parse_altsvc_scheme(alt_proto)
-
118
case alt_proto
-
when "h2c"
-
6
"http"
-
when "h2"
-
42
"https"
-
end
-
end
-
-
25
def parse_altsvc_origin(alt_proto, alt_origin)
-
100
alt_scheme = parse_altsvc_scheme(alt_proto)
-
-
100
return unless alt_scheme
-
-
36
alt_origin = alt_origin[1..-2] if alt_origin.start_with?("\"") && alt_origin.end_with?("\"")
-
-
36
URI.parse("#{alt_scheme}://#{alt_origin}")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "forwardable"
-
-
25
module HTTPX
-
# Internal class to abstract a string buffer, by wrapping a string and providing the
-
# minimum possible API and functionality required.
-
#
-
# buffer = Buffer.new(640)
-
# buffer.full? #=> false
-
# buffer << "aa"
-
# buffer.capacity #=> 638
-
#
-
25
class Buffer
-
25
extend Forwardable
-
-
25
def_delegator :@buffer, :to_s
-
-
25
def_delegator :@buffer, :to_str
-
-
25
def_delegator :@buffer, :empty?
-
-
25
def_delegator :@buffer, :bytesize
-
-
25
def_delegator :@buffer, :clear
-
-
25
def_delegator :@buffer, :replace
-
-
25
attr_reader :limit
-
-
25
if RUBY_VERSION >= "3.4.0"
-
15
def initialize(limit)
-
2914
@buffer = String.new("", encoding: Encoding::BINARY, capacity: limit)
-
2914
@limit = limit
-
end
-
-
15
def <<(chunk)
-
12193
@buffer.append_as_bytes(chunk)
-
end
-
else
-
10
def initialize(limit)
-
14102
@buffer = "".b
-
14102
@limit = limit
-
end
-
-
10
def_delegator :@buffer, :<<
-
end
-
-
25
def full?
-
9763810
@buffer.bytesize >= @limit
-
end
-
-
25
def capacity
-
12
@limit - @buffer.bytesize
-
end
-
-
25
def shift!(fin)
-
17432
@buffer = @buffer.byteslice(fin..-1) || "".b
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Callbacks
-
25
def on(type, &action)
-
299444
callbacks(type) << action
-
299444
action
-
end
-
-
25
def once(type, &block)
-
173688
on(type) do |*args, &callback|
-
89018
block.call(*args, &callback)
-
88970
:delete
-
end
-
end
-
-
25
def emit(type, *args)
-
101254
log { "emit #{type.inspect} callbacks" } if respond_to?(:log)
-
223463
callbacks(type).delete_if { |pr| :delete == pr.call(*args) } # rubocop:disable Style/YodaCondition
-
end
-
-
25
def callbacks_for?(type)
-
2528
@callbacks.key?(type) && @callbacks[type].any?
-
end
-
-
25
protected
-
-
25
def callbacks(type = nil)
-
403247
return @callbacks unless type
-
-
592204
@callbacks ||= Hash.new { |h, k| h[k] = [] }
-
403180
@callbacks[type]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
# Session mixin, implements most of the APIs that the users call.
-
# delegates to a default session when extended.
-
25
module Chainable
-
25
%w[head get post put delete trace options connect patch].each do |meth|
-
225
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
def #{meth}(*uri, **options) # def get(*uri, **options)
-
request("#{meth.upcase}", uri, **options) # request("GET", uri, **options)
-
end # end
-
MOD
-
end
-
-
# delegates to the default session (see HTTPX::Session#request).
-
25
def request(*args, **options)
-
2081
branch(default_options).request(*args, **options)
-
end
-
-
25
def accept(type)
-
12
with(headers: { "accept" => String(type) })
-
end
-
-
# delegates to the default session (see HTTPX::Session#wrap).
-
25
def wrap(&blk)
-
67
branch(default_options).wrap(&blk)
-
end
-
-
# returns a new instance loaded with the +pl+ plugin and +options+.
-
25
def plugin(pl, options = nil, &blk)
-
4203
klass = is_a?(S) ? self.class : Session
-
4203
klass = Class.new(klass)
-
4203
klass.instance_variable_set(:@default_options, klass.default_options.merge(default_options))
-
4203
klass.plugin(pl, options, &blk).new
-
end
-
-
# returns a new instance loaded with +options+.
-
25
def with(options, &blk)
-
2156
branch(default_options.merge(options), &blk)
-
end
-
-
25
private
-
-
# returns default instance of HTTPX::Options.
-
25
def default_options
-
8549
@options || Session.default_options
-
end
-
-
# returns a default instance of HTTPX::Session.
-
25
def branch(options, &blk)
-
4292
return self.class.new(options, &blk) if is_a?(S)
-
-
2490
Session.new(options, &blk)
-
end
-
-
25
def method_missing(meth, *args, **options, &blk)
-
566
case meth
-
when /\Awith_(.+)/
-
-
559
option = Regexp.last_match(1)
-
-
559
return super unless option
-
-
559
with(option.to_sym => args.first || options)
-
when /\Aon_(.+)/
-
7
callback = Regexp.last_match(1)
-
-
5
return super unless %w[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
2
].include?(callback)
-
-
7
warn "DEPRECATION WARNING: calling `.#{meth}` on plain HTTPX sessions is deprecated. " \
-
"Use `HTTPX.plugin(:callbacks).#{meth}` instead."
-
-
7
plugin(:callbacks).__send__(meth, *args, **options, &blk)
-
else
-
super
-
end
-
end
-
-
25
def respond_to_missing?(meth, *)
-
42
case meth
-
when /\Awith_(.+)/
-
30
option = Regexp.last_match(1)
-
-
30
default_options.respond_to?(option) || super
-
when /\Aon_(.+)/
-
12
callback = Regexp.last_match(1)
-
-
10
%w[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
2
].include?(callback) || super
-
else
-
super
-
end
-
end
-
end
-
-
25
extend Chainable
-
end
-
# frozen_string_literal: true
-
-
25
require "resolv"
-
25
require "forwardable"
-
25
require "httpx/io"
-
25
require "httpx/buffer"
-
-
25
module HTTPX
-
# The Connection can be watched for IO events.
-
#
-
# It contains the +io+ object to read/write from, and knows what to do when it can.
-
#
-
# It defers connecting until absolutely necessary. Connection should be triggered from
-
# the IO selector (until then, any request will be queued).
-
#
-
# A connection boots up its parser after connection is established. All pending requests
-
# will be redirected there after connection.
-
#
-
# A connection can be prevented from closing by the parser, that is, if there are pending
-
# requests. This will signal that the connection was prematurely closed, due to a possible
-
# number of conditions:
-
#
-
# * Remote peer closed the connection ("Connection: close");
-
# * Remote peer doesn't support pipelining;
-
#
-
# A connection may also route requests for a different host for which the +io+ was connected
-
# to, provided that the IP is the same and the port and scheme as well. This will allow to
-
# share the same socket to send HTTP/2 requests to different hosts.
-
#
-
25
class Connection
-
25
extend Forwardable
-
25
include Loggable
-
25
include Callbacks
-
-
25
using URIExtensions
-
-
25
require "httpx/connection/http2"
-
25
require "httpx/connection/http1"
-
-
25
def_delegator :@io, :closed?
-
-
25
def_delegator :@write_buffer, :empty?
-
-
25
attr_reader :type, :io, :origin, :origins, :state, :pending, :options, :ssl_session, :sibling
-
-
25
attr_writer :current_selector
-
-
25
attr_accessor :current_session, :family
-
-
25
protected :sibling
-
-
25
def initialize(uri, options)
-
5787
@current_session = @current_selector = @sibling = @coalesced_connection = nil
-
5787
@exhausted = @cloned = @main_sibling = false
-
-
5787
@options = Options.new(options)
-
5787
@type = initialize_type(uri, @options)
-
5787
@origins = [uri.origin]
-
5787
@origin = Utils.to_uri(uri.origin)
-
5787
@window_size = @options.window_size
-
5787
@read_buffer = Buffer.new(@options.buffer_size)
-
5787
@write_buffer = Buffer.new(@options.buffer_size)
-
5787
@pending = []
-
-
5787
on(:error, &method(:on_error))
-
5787
if @options.io
-
# if there's an already open IO, get its
-
# peer address, and force-initiate the parser
-
54
transition(:already_open)
-
54
@io = build_socket
-
54
parser
-
else
-
5733
transition(:idle)
-
end
-
5787
on(:close) do
-
5846
next if @exhausted # it'll reset
-
-
# may be called after ":close" above, so after the connection has been checked back in.
-
# next unless @current_session
-
-
5840
next unless @current_session
-
-
5840
@current_session.deselect_connection(self, @current_selector, @cloned)
-
end
-
5787
on(:terminate) do
-
2157
next if @exhausted # it'll reset
-
-
2151
current_session = @current_session
-
2151
current_selector = @current_selector
-
-
# may be called after ":close" above, so after the connection has been checked back in.
-
2151
next unless current_session && current_selector
-
-
12
current_session.deselect_connection(self, current_selector)
-
end
-
-
5787
on(:altsvc) do |alt_origin, origin, alt_params|
-
6
build_altsvc_connection(alt_origin, origin, alt_params)
-
end
-
-
5787
@inflight = 0
-
5787
@keep_alive_timeout = @options.timeout[:keep_alive_timeout]
-
-
5787
self.addresses = @options.addresses if @options.addresses
-
end
-
-
25
def peer
-
11810
@origin
-
end
-
-
# this is a semi-private method, to be used by the resolver
-
# to initiate the io object.
-
25
def addresses=(addrs)
-
5590
if @io
-
226
@io.add_addresses(addrs)
-
else
-
5364
@io = build_socket(addrs)
-
end
-
end
-
-
25
def addresses
-
11539
@io && @io.addresses
-
end
-
-
25
def match?(uri, options)
-
1752
return false if !used? && (@state == :closing || @state == :closed)
-
-
(
-
1662
@origins.include?(uri.origin) &&
-
# if there is more than one origin to match, it means that this connection
-
# was the result of coalescing. To prevent blind trust in the case where the
-
# origin came from an ORIGIN frame, we're going to verify the hostname with the
-
# SSL certificate
-
1588
(@origins.size == 1 || @origin == uri.origin || (@io.is_a?(SSL) && @io.verify_hostname(uri.host)))
-
) && @options == options
-
end
-
-
25
def expired?
-
return false unless @io
-
-
@io.expired?
-
end
-
-
25
def mergeable?(connection)
-
255
return false if @state == :closing || @state == :closed || !@io
-
-
60
return false unless connection.addresses
-
-
(
-
60
(open? && @origin == connection.origin) ||
-
60
!(@io.addresses & (connection.addresses || [])).empty?
-
) && @options == connection.options
-
end
-
-
# coalesces +self+ into +connection+.
-
25
def coalesce!(connection)
-
13
@coalesced_connection = connection
-
-
13
close_sibling
-
13
connection.merge(self)
-
end
-
-
# coalescable connections need to be mergeable!
-
# but internally, #mergeable? is called before #coalescable?
-
25
def coalescable?(connection)
-
27
if @io.protocol == "h2" &&
-
@origin.scheme == "https" &&
-
connection.origin.scheme == "https" &&
-
@io.can_verify_peer?
-
13
@io.verify_hostname(connection.origin.host)
-
else
-
14
@origin == connection.origin
-
end
-
end
-
-
25
def create_idle(options = {})
-
self.class.new(@origin, @options.merge(options))
-
end
-
-
25
def merge(connection)
-
31
@origins |= connection.instance_variable_get(:@origins)
-
31
if connection.ssl_session
-
12
@ssl_session = connection.ssl_session
-
@io.session_new_cb do |sess|
-
18
@ssl_session = sess
-
12
end if @io
-
end
-
31
connection.purge_pending do |req|
-
7
send(req)
-
end
-
end
-
-
25
def purge_pending(&block)
-
31
pendings = []
-
31
if @parser
-
18
@inflight -= @parser.pending.size
-
18
pendings << @parser.pending
-
end
-
31
pendings << @pending
-
31
pendings.each do |pending|
-
49
pending.reject!(&block)
-
end
-
end
-
-
25
def io_connected?
-
return @coalesced_connection.io_connected? if @coalesced_connection
-
-
@io && @io.state == :connected
-
end
-
-
25
def connecting?
-
9791216
@state == :idle
-
end
-
-
25
def inflight?
-
2276
@parser && (
-
# parser may be dealing with other requests (possibly started from a different fiber)
-
2131
!@parser.empty? ||
-
# connection may be doing connection termination handshake
-
!@write_buffer.empty?
-
)
-
end
-
-
25
def interests
-
# connecting
-
9781833
if connecting?
-
9114
connect
-
-
9113
return @io.interests if connecting?
-
end
-
-
# if the write buffer is full, we drain it
-
9773185
return :w unless @write_buffer.empty?
-
-
9740224
return @parser.interests if @parser
-
-
12
nil
-
rescue StandardError => e
-
emit(:error, e)
-
nil
-
end
-
-
25
def to_io
-
18908
@io.to_io
-
end
-
-
25
def call
-
18121
case @state
-
when :idle
-
8519
connect
-
8508
consume
-
when :closed
-
return
-
when :closing
-
consume
-
transition(:closed)
-
when :open
-
9353
consume
-
end
-
4546
nil
-
rescue StandardError => e
-
18
@write_buffer.clear
-
18
emit(:error, e)
-
18
raise e
-
end
-
-
25
def close
-
2119
transition(:active) if @state == :inactive
-
-
2119
@parser.close if @parser
-
end
-
-
25
def terminate
-
2119
case @state
-
when :idle
-
purge_after_closed
-
emit(:terminate)
-
when :closed
-
6
@connected_at = nil
-
end
-
-
2119
close
-
end
-
-
# bypasses the state machine to force closing of connections still connecting.
-
# **only** used for Happy Eyeballs v2.
-
25
def force_reset(cloned = false)
-
259
@state = :closing
-
259
@cloned = cloned
-
259
transition(:closed)
-
end
-
-
25
def reset
-
5762
return if @state == :closing || @state == :closed
-
-
5719
transition(:closing)
-
-
5719
transition(:closed)
-
end
-
-
25
def send(request)
-
7110
return @coalesced_connection.send(request) if @coalesced_connection
-
-
7104
if @parser && !@write_buffer.full?
-
350
if @response_received_at && @keep_alive_timeout &&
-
Utils.elapsed_time(@response_received_at) > @keep_alive_timeout
-
# when pushing a request into an existing connection, we have to check whether there
-
# is the possibility that the connection might have extended the keep alive timeout.
-
# for such cases, we want to ping for availability before deciding to shovel requests.
-
16
log(level: 3) { "keep alive timeout expired, pinging connection..." }
-
16
@pending << request
-
16
transition(:active) if @state == :inactive
-
16
parser.ping
-
16
request.ping!
-
16
return
-
end
-
-
334
send_request_to_parser(request)
-
else
-
6754
@pending << request
-
end
-
end
-
-
25
def timeout
-
9682293
return if @state == :closed || @state == :inactive
-
-
9682293
return @timeout if @timeout
-
-
9672117
return @options.timeout[:connect_timeout] if @state == :idle
-
-
9672117
@options.timeout[:operation_timeout]
-
end
-
-
25
def idling
-
640
purge_after_closed
-
640
@write_buffer.clear
-
640
transition(:idle)
-
640
@parser = nil if @parser
-
end
-
-
25
def used?
-
1917
@connected_at
-
end
-
-
25
def deactivate
-
310
transition(:inactive)
-
end
-
-
25
def open?
-
5617
@state == :open || @state == :inactive
-
end
-
-
25
def handle_socket_timeout(interval)
-
24
error = OperationTimeoutError.new(interval, "timed out while waiting on select")
-
24
error.set_backtrace(caller)
-
24
on_error(error)
-
end
-
-
25
def sibling=(connection)
-
24
@sibling = connection
-
-
24
return unless connection
-
-
@main_sibling = connection.sibling.nil?
-
-
return unless @main_sibling
-
-
connection.sibling = self
-
end
-
-
25
def handle_connect_error(error)
-
246
@connect_error = error
-
-
246
return handle_error(error) unless @sibling && @sibling.connecting?
-
-
@sibling.merge(self)
-
-
force_reset(true)
-
end
-
-
25
def disconnect
-
5955
return unless @current_session && @current_selector
-
-
5846
emit(:close)
-
5834
@current_session = nil
-
5834
@current_selector = nil
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"@origin=#{@origin} " \
-
skipped
"@state=#{@state} " \
-
skipped
"@pending=#{@pending.size} " \
-
skipped
"@io=#{@io}>"
-
skipped
end
-
skipped
# :nocov:
-
-
25
private
-
-
25
def connect
-
16856
transition(:open)
-
end
-
-
25
def consume
-
20415
return unless @io
-
-
20415
catch(:called) do
-
20415
epiped = false
-
20415
loop do
-
# connection may have
-
36533
return if @state == :idle
-
-
33687
parser.consume
-
-
# we exit if there's no more requests to process
-
#
-
# this condition takes into account:
-
#
-
# * the number of inflight requests
-
# * the number of pending requests
-
# * whether the write buffer has bytes (i.e. for close handshake)
-
33675
if @pending.empty? && @inflight.zero? && @write_buffer.empty?
-
2228
log(level: 3) { "NO MORE REQUESTS..." }
-
2216
return
-
end
-
-
31459
@timeout = @current_timeout
-
-
31459
read_drained = false
-
31459
write_drained = nil
-
-
#
-
# tight read loop.
-
#
-
# read as much of the socket as possible.
-
#
-
# this tight loop reads all the data it can from the socket and pipes it to
-
# its parser.
-
#
-
5026
loop do
-
40154
siz = @io.read(@window_size, @read_buffer)
-
40258
log(level: 3, color: :cyan) { "IO READ: #{siz} bytes... (wsize: #{@window_size}, rbuffer: #{@read_buffer.bytesize})" }
-
40154
unless siz
-
16
@write_buffer.clear
-
-
16
ex = EOFError.new("descriptor closed")
-
16
ex.set_backtrace(caller)
-
16
on_error(ex)
-
16
return
-
end
-
-
# socket has been drained. mark and exit the read loop.
-
40138
if siz.zero?
-
8871
read_drained = @read_buffer.empty?
-
8871
epiped = false
-
8871
break
-
end
-
-
31267
parser << @read_buffer.to_s
-
-
# continue reading if possible.
-
27852
break if interests == :w && !epiped
-
-
# exit the read loop if connection is preparing to be closed
-
21697
break if @state == :closing || @state == :closed
-
-
# exit #consume altogether if all outstanding requests have been dealt with
-
21685
return if @pending.empty? && @inflight.zero?
-
31459
end unless ((ints = interests).nil? || ints == :w || @state == :closing) && !epiped
-
-
#
-
# tight write loop.
-
#
-
# flush as many bytes as the sockets allow.
-
#
-
3811
loop do
-
# buffer has been drainned, mark and exit the write loop.
-
19073
if @write_buffer.empty?
-
# we only mark as drained on the first loop
-
2278
write_drained = write_drained.nil? && @inflight.positive?
-
-
2278
break
-
end
-
-
begin
-
16795
siz = @io.write(@write_buffer)
-
rescue Errno::EPIPE
-
# this can happen if we still have bytes in the buffer to send to the server, but
-
# the server wants to respond immediately with some message, or an error. An example is
-
# when one's uploading a big file to an unintended endpoint, and the server stops the
-
# consumption, and responds immediately with an authorization of even method not allowed error.
-
# at this point, we have to let the connection switch to read-mode.
-
12
log(level: 2) { "pipe broken, could not flush buffer..." }
-
12
epiped = true
-
12
read_drained = false
-
12
break
-
end
-
16849
log(level: 3, color: :cyan) { "IO WRITE: #{siz} bytes..." }
-
16777
unless siz
-
@write_buffer.clear
-
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
on_error(ex)
-
return
-
end
-
-
# socket closed for writing. mark and exit the write loop.
-
16777
if siz.zero?
-
12
write_drained = !@write_buffer.empty?
-
12
break
-
end
-
-
# exit write loop if marked to consume from peer, or is closing.
-
16765
break if interests == :r || @state == :closing || @state == :closed
-
-
2331
write_drained = false
-
25612
end unless (ints = interests) == :r
-
-
25606
send_pending if @state == :open
-
-
# return if socket is drained
-
25606
next unless (ints != :r || read_drained) && (ints != :w || write_drained)
-
-
# gotta go back to the event loop. It happens when:
-
#
-
# * the socket is drained of bytes or it's not the interest of the conn to read;
-
# * theres nothing more to write, or it's not in the interest of the conn to write;
-
9524
log(level: 3) { "(#{ints}): WAITING FOR EVENTS..." }
-
9488
return
-
end
-
end
-
end
-
-
25
def send_pending
-
74129
while !@write_buffer.full? && (request = @pending.shift)
-
16963
send_request_to_parser(request)
-
end
-
end
-
-
25
def parser
-
88926
@parser ||= build_parser
-
end
-
-
25
def send_request_to_parser(request)
-
17297
@inflight += 1
-
17297
request.peer_address = @io.ip
-
17297
set_request_timeouts(request)
-
-
17297
parser.send(request)
-
-
17297
return unless @state == :inactive
-
-
6
transition(:active)
-
end
-
-
25
def build_parser(protocol = @io.protocol)
-
5785
parser = parser_type(protocol).new(@write_buffer, @options)
-
5785
set_parser_callbacks(parser)
-
5785
parser
-
end
-
-
25
def set_parser_callbacks(parser)
-
5870
parser.on(:response) do |request, response|
-
6308
AltSvc.emit(request, response) do |alt_origin, origin, alt_params|
-
6
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
6308
@response_received_at = Utils.now
-
6308
@inflight -= 1
-
6308
response.finish!
-
6308
request.emit(:response, response)
-
end
-
5870
parser.on(:altsvc) do |alt_origin, origin, alt_params|
-
emit(:altsvc, alt_origin, origin, alt_params)
-
end
-
-
5870
parser.on(:pong, &method(:send_pending))
-
-
5870
parser.on(:promise) do |request, stream|
-
18
request.emit(:promise, parser, stream)
-
end
-
5870
parser.on(:exhausted) do
-
6
@exhausted = true
-
6
current_session = @current_session
-
6
current_selector = @current_selector
-
begin
-
6
parser.close
-
6
@pending.concat(parser.pending)
-
ensure
-
6
@current_session = current_session
-
6
@current_selector = current_selector
-
end
-
-
6
case @state
-
when :closed
-
6
idling
-
6
@exhausted = false
-
when :closing
-
once(:closed) do
-
idling
-
@exhausted = false
-
end
-
end
-
end
-
5870
parser.on(:origin) do |origin|
-
@origins |= [origin]
-
end
-
5870
parser.on(:close) do |force|
-
2157
if force
-
2157
reset
-
2151
emit(:terminate)
-
end
-
end
-
5870
parser.on(:close_handshake) do
-
6
consume
-
end
-
5870
parser.on(:reset) do
-
3124
@pending.concat(parser.pending) unless parser.empty?
-
3124
current_session = @current_session
-
3124
current_selector = @current_selector
-
3124
reset
-
3118
unless @pending.empty?
-
162
idling
-
162
@current_session = current_session
-
162
@current_selector = current_selector
-
end
-
end
-
5870
parser.on(:current_timeout) do
-
2486
@current_timeout = @timeout = parser.timeout
-
end
-
5870
parser.on(:timeout) do |tout|
-
2107
@timeout = tout
-
end
-
5870
parser.on(:error) do |request, error|
-
53
case error
-
when :http_1_1_required
-
12
current_session = @current_session
-
12
current_selector = @current_selector
-
12
parser.close
-
-
12
other_connection = current_session.find_connection(@origin, current_selector,
-
@options.merge(ssl: { alpn_protocols: %w[http/1.1] }))
-
12
other_connection.merge(self)
-
12
request.transition(:idle)
-
12
other_connection.send(request)
-
12
next
-
when OperationTimeoutError
-
# request level timeouts should take precedence
-
next unless request.active_timeouts.empty?
-
end
-
-
41
@inflight -= 1
-
41
response = ErrorResponse.new(request, error)
-
41
request.response = response
-
41
request.emit(:response, response)
-
end
-
end
-
-
25
def transition(nextstate)
-
36527
handle_transition(nextstate)
-
rescue Errno::ECONNABORTED,
-
Errno::ECONNREFUSED,
-
Errno::ECONNRESET,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
Errno::EINVAL,
-
Errno::ENETUNREACH,
-
Errno::EPIPE,
-
Errno::ENOENT,
-
SocketError,
-
IOError => e
-
# connect errors, exit gracefully
-
72
error = ConnectionError.new(e.message)
-
72
error.set_backtrace(e.backtrace)
-
72
handle_connect_error(error) if connecting?
-
72
@state = :closed
-
72
purge_after_closed
-
72
disconnect
-
rescue TLSError, ::HTTP2::Error::ProtocolError, ::HTTP2::Error::HandshakeError => e
-
# connect errors, exit gracefully
-
18
handle_error(e)
-
18
handle_connect_error(e) if connecting?
-
18
@state = :closed
-
18
purge_after_closed
-
18
disconnect
-
end
-
-
25
def handle_transition(nextstate)
-
36145
case nextstate
-
when :idle
-
6385
@timeout = @current_timeout = @options.timeout[:connect_timeout]
-
-
6385
@connected_at = @response_received_at = nil
-
when :open
-
17091
return if @state == :closed
-
-
17091
@io.connect
-
17001
close_sibling if @io.state == :connected
-
-
17001
return unless @io.connected?
-
-
5787
@connected_at = Utils.now
-
-
5787
send_pending
-
-
5787
@timeout = @current_timeout = parser.timeout
-
5787
emit(:open)
-
when :inactive
-
310
return unless @state == :open
-
-
# do not deactivate connection in use
-
309
return if @inflight.positive?
-
when :closing
-
5725
return unless @state == :idle || @state == :open
-
-
5725
unless @write_buffer.empty?
-
# preset state before handshake, as error callbacks
-
# may take it back here.
-
2114
@state = nextstate
-
# handshakes, try sending
-
2114
consume
-
2114
@write_buffer.clear
-
2114
return
-
end
-
when :closed
-
5984
return unless @state == :closing
-
5984
return unless @write_buffer.empty?
-
-
5966
purge_after_closed
-
5966
disconnect if @pending.empty?
-
-
when :already_open
-
54
nextstate = :open
-
# the first check for given io readiness must still use a timeout.
-
# connect is the reasonable choice in such a case.
-
54
@timeout = @options.timeout[:connect_timeout]
-
54
send_pending
-
when :active
-
151
return unless @state == :inactive
-
-
151
nextstate = :open
-
-
# activate
-
151
@current_session.select_connection(self, @current_selector)
-
end
-
22684
@state = nextstate
-
end
-
-
25
def close_sibling
-
8047
return unless @sibling
-
-
if @sibling.io_connected?
-
reset
-
# TODO: transition connection to closed
-
end
-
-
unless @sibling.state == :closed
-
merge(@sibling) unless @main_sibling
-
@sibling.force_reset(true)
-
end
-
-
@sibling = nil
-
end
-
-
25
def purge_after_closed
-
6702
@io.close if @io
-
6702
@read_buffer.clear
-
6702
@timeout = nil
-
end
-
-
25
def initialize_type(uri, options)
-
5507
options.transport || begin
-
5483
case uri.scheme
-
when "http"
-
3139
"tcp"
-
when "https"
-
2344
"ssl"
-
else
-
raise UnsupportedSchemeError, "#{uri}: #{uri.scheme}: unsupported URI scheme"
-
end
-
end
-
end
-
-
# returns an HTTPX::Connection for the negotiated Alternative Service (or none).
-
25
def build_altsvc_connection(alt_origin, origin, alt_params)
-
# do not allow security downgrades on altsvc negotiation
-
6
return if @origin.scheme == "https" && alt_origin.scheme != "https"
-
-
6
altsvc = AltSvc.cached_altsvc_set(origin, alt_params.merge("origin" => alt_origin))
-
-
# altsvc already exists, somehow it wasn't advertised, probably noop
-
6
return unless altsvc
-
-
6
alt_options = @options.merge(ssl: @options.ssl.merge(hostname: URI(origin).host))
-
-
6
connection = @current_session.find_connection(alt_origin, @current_selector, alt_options)
-
-
# advertised altsvc is the same origin being used, ignore
-
6
return if connection == self
-
-
6
connection.extend(AltSvc::ConnectionMixin) unless connection.is_a?(AltSvc::ConnectionMixin)
-
-
6
log(level: 1) { "#{origin} alt-svc: #{alt_origin}" }
-
-
6
connection.merge(self)
-
6
terminate
-
rescue UnsupportedSchemeError
-
altsvc["noop"] = true
-
nil
-
end
-
-
25
def build_socket(addrs = nil)
-
5418
case @type
-
when "tcp"
-
3137
TCP.new(peer, addrs, @options)
-
when "ssl"
-
2257
SSL.new(peer, addrs, @options) do |sock|
-
2239
sock.ssl_session = @ssl_session
-
2239
sock.session_new_cb do |sess|
-
4369
@ssl_session = sess
-
-
4369
sock.ssl_session = sess
-
end
-
end
-
when "unix"
-
24
path = Array(addrs).first
-
-
24
path = String(path) if path
-
-
24
UNIX.new(peer, path, @options)
-
else
-
raise Error, "unsupported transport (#{@type})"
-
end
-
end
-
-
25
def on_error(error, request = nil)
-
463
if error.is_a?(OperationTimeoutError)
-
-
# inactive connections do not contribute to the select loop, therefore
-
# they should not fail due to such errors.
-
24
return if @state == :inactive
-
-
24
if @timeout
-
24
@timeout -= error.timeout
-
24
return unless @timeout <= 0
-
end
-
-
24
error = error.to_connection_error if connecting?
-
end
-
463
handle_error(error, request)
-
463
reset
-
end
-
-
25
def handle_error(error, request = nil)
-
727
parser.handle_error(error, request) if @parser && parser.respond_to?(:handle_error)
-
1802
while (req = @pending.shift)
-
360
next if request && req == request
-
-
360
response = ErrorResponse.new(req, error)
-
360
req.response = response
-
348
req.emit(:response, response)
-
end
-
-
715
return unless request
-
-
309
@inflight -= 1
-
309
response = ErrorResponse.new(request, error)
-
309
request.response = response
-
309
request.emit(:response, response)
-
end
-
-
25
def set_request_timeouts(request)
-
17297
set_request_write_timeout(request)
-
17297
set_request_read_timeout(request)
-
17297
set_request_request_timeout(request)
-
end
-
-
25
def set_request_read_timeout(request)
-
17297
read_timeout = request.read_timeout
-
-
17297
return if read_timeout.nil? || read_timeout.infinite?
-
-
17027
set_request_timeout(:read_timeout, request, read_timeout, :done, :response) do
-
12
read_timeout_callback(request, read_timeout)
-
end
-
end
-
-
25
def set_request_write_timeout(request)
-
17297
write_timeout = request.write_timeout
-
-
17297
return if write_timeout.nil? || write_timeout.infinite?
-
-
17297
set_request_timeout(:write_timeout, request, write_timeout, :headers, %i[done response]) do
-
12
write_timeout_callback(request, write_timeout)
-
end
-
end
-
-
25
def set_request_request_timeout(request)
-
17083
request_timeout = request.request_timeout
-
-
17083
return if request_timeout.nil? || request_timeout.infinite?
-
-
413
set_request_timeout(:request_timeout, request, request_timeout, :headers, :complete) do
-
314
read_timeout_callback(request, request_timeout, RequestTimeoutError)
-
end
-
end
-
-
25
def write_timeout_callback(request, write_timeout)
-
12
return if request.state == :done
-
-
12
@write_buffer.clear
-
12
error = WriteTimeoutError.new(request, nil, write_timeout)
-
-
12
on_error(error, request)
-
end
-
-
25
def read_timeout_callback(request, read_timeout, error_type = ReadTimeoutError)
-
326
response = request.response
-
-
326
return if response && response.finished?
-
-
297
@write_buffer.clear
-
297
error = error_type.new(request, request.response, read_timeout)
-
-
297
on_error(error, request)
-
end
-
-
25
def set_request_timeout(label, request, timeout, start_event, finish_events, &callback)
-
34797
request.set_timeout_callback(start_event) do
-
34645
timer = @current_selector.after(timeout, callback)
-
34645
request.active_timeouts << label
-
-
34645
Array(finish_events).each do |event|
-
# clean up request timeouts if the connection errors out
-
51935
request.set_timeout_callback(event) do
-
51585
timer.cancel
-
51585
request.active_timeouts.delete(label)
-
end
-
end
-
end
-
end
-
-
25
def parser_type(protocol)
-
5885
case protocol
-
2486
when "h2" then HTTP2
-
3399
when "http/1.1" then HTTP1
-
else
-
raise Error, "unsupported protocol (##{protocol})"
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "httpx/parser/http1"
-
-
25
module HTTPX
-
25
class Connection::HTTP1
-
25
include Callbacks
-
25
include Loggable
-
-
25
MAX_REQUESTS = 200
-
25
CRLF = "\r\n"
-
-
25
attr_reader :pending, :requests
-
-
25
attr_accessor :max_concurrent_requests
-
-
25
def initialize(buffer, options)
-
3399
@options = options
-
3399
@max_concurrent_requests = @options.max_concurrent_requests || MAX_REQUESTS
-
3399
@max_requests = @options.max_requests
-
3399
@parser = Parser::HTTP1.new(self)
-
3399
@buffer = buffer
-
3399
@version = [1, 1]
-
3399
@pending = []
-
3399
@requests = []
-
3399
@handshake_completed = false
-
end
-
-
25
def timeout
-
3306
@options.timeout[:operation_timeout]
-
end
-
-
25
def interests
-
# this means we're processing incoming response already
-
25665
return :r if @request
-
-
21357
return if @requests.empty?
-
-
21340
request = @requests.first
-
-
21340
return unless request
-
-
21340
return :w if request.interests == :w || !@buffer.empty?
-
-
18758
:r
-
end
-
-
25
def reset
-
3223
@max_requests = @options.max_requests || MAX_REQUESTS
-
3223
@parser.reset!
-
3223
@handshake_completed = false
-
3223
@pending.concat(@requests) unless @requests.empty?
-
end
-
-
25
def close
-
63
reset
-
63
emit(:close, true)
-
end
-
-
25
def exhausted?
-
520
!@max_requests.positive?
-
end
-
-
25
def empty?
-
# this means that for every request there's an available
-
# partial response, so there are no in-flight requests waiting.
-
3160
@requests.empty? || (
-
# checking all responses can be time-consuming. Alas, as in HTTP/1, responses
-
# do not come out of order, we can get away with checking first and last.
-
174
!@requests.first.response.nil? &&
-
(@requests.size == 1 || !@requests.last.response.nil?)
-
)
-
end
-
-
25
def <<(data)
-
5703
@parser << data
-
end
-
-
25
def send(request)
-
14473
unless @max_requests.positive?
-
@pending << request
-
return
-
end
-
-
14473
return if @requests.include?(request)
-
-
14473
@requests << request
-
14473
@pipelining = true if @requests.size > 1
-
end
-
-
25
def consume
-
13164
requests_limit = [@max_requests, @requests.size].min
-
13164
concurrent_requests_limit = [@max_concurrent_requests, requests_limit].min
-
13164
@requests.each_with_index do |request, idx|
-
15702
break if idx >= concurrent_requests_limit
-
13149
next unless request.can_buffer?
-
-
4837
handle(request)
-
end
-
end
-
-
# HTTP Parser callbacks
-
#
-
# must be public methods, or else they won't be reachable
-
-
25
def on_start
-
3821
log(level: 2) { "parsing begins" }
-
end
-
-
25
def on_headers(h)
-
3797
@request = @requests.first
-
-
3797
return if @request.response
-
-
3821
log(level: 2) { "headers received" }
-
3797
headers = @request.options.headers_class.new(h)
-
3797
response = @request.options.response_class.new(@request,
-
@parser.status_code,
-
@parser.http_version.join("."),
-
headers)
-
3821
log(color: :yellow) { "-> HEADLINE: #{response.status} HTTP/#{@parser.http_version.join(".")}" }
-
4013
log(color: :yellow) { response.headers.each.map { |f, v| "-> HEADER: #{f}: #{log_redact(v)}" }.join("\n") }
-
-
3797
@request.response = response
-
3791
on_complete if response.finished?
-
end
-
-
25
def on_trailers(h)
-
6
return unless @request
-
-
6
response = @request.response
-
6
log(level: 2) { "trailer headers received" }
-
-
6
log(color: :yellow) { h.each.map { |f, v| "-> HEADER: #{f}: #{log_redact(v.join(", "))}" }.join("\n") }
-
6
response.merge_headers(h)
-
end
-
-
25
def on_data(chunk)
-
4377
request = @request
-
-
4377
return unless request
-
-
4401
log(color: :green) { "-> DATA: #{chunk.bytesize} bytes..." }
-
4401
log(level: 2, color: :green) { "-> #{log_redact(chunk.inspect)}" }
-
4377
response = request.response
-
-
4377
response << chunk
-
rescue StandardError => e
-
12
error_response = ErrorResponse.new(request, e)
-
12
request.response = error_response
-
12
dispatch
-
end
-
-
25
def on_complete
-
3767
request = @request
-
-
3767
return unless request
-
-
3791
log(level: 2) { "parsing complete" }
-
3767
dispatch
-
end
-
-
25
def dispatch
-
3779
request = @request
-
-
3779
if request.expects?
-
54
@parser.reset!
-
54
return handle(request)
-
end
-
-
3725
@request = nil
-
3725
@requests.shift
-
3725
response = request.response
-
3725
emit(:response, request, response)
-
-
3680
if @parser.upgrade?
-
24
response << @parser.upgrade_data
-
24
throw(:called)
-
end
-
-
3656
@parser.reset!
-
3656
@max_requests -= 1
-
3656
if response.is_a?(ErrorResponse)
-
12
disable
-
else
-
3644
manage_connection(request, response)
-
end
-
-
520
if exhausted?
-
@pending.concat(@requests)
-
@requests.clear
-
-
emit(:exhausted)
-
else
-
520
send(@pending.shift) unless @pending.empty?
-
end
-
end
-
-
25
def handle_error(ex, request = nil)
-
160
if (ex.is_a?(EOFError) || ex.is_a?(TimeoutError)) && @request && @request.response &&
-
!@request.response.headers.key?("content-length") &&
-
!@request.response.headers.key?("transfer-encoding")
-
# if the response does not contain a content-length header, the server closing the
-
# connnection is the indicator of response consumed.
-
# https://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.4
-
24
catch(:called) { on_complete }
-
12
return
-
end
-
-
148
if @pipelining
-
catch(:called) { disable }
-
else
-
148
@requests.each do |req|
-
140
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
148
@pending.each do |req|
-
next if request && request == req
-
-
emit(:error, req, ex)
-
end
-
end
-
end
-
-
25
def ping
-
reset
-
emit(:reset)
-
emit(:exhausted)
-
end
-
-
25
private
-
-
25
def manage_connection(request, response)
-
3644
connection = response.headers["connection"]
-
3644
case connection
-
when /keep-alive/i
-
520
if @handshake_completed
-
if @max_requests.zero?
-
@pending.concat(@requests)
-
@requests.clear
-
emit(:exhausted)
-
end
-
return
-
end
-
-
520
keep_alive = response.headers["keep-alive"]
-
520
return unless keep_alive
-
-
106
parameters = Hash[keep_alive.split(/ *, */).map do |pair|
-
106
pair.split(/ *= */, 2)
-
end]
-
106
@max_requests = parameters["max"].to_i - 1 if parameters.key?("max")
-
-
106
if parameters.key?("timeout")
-
keep_alive_timeout = parameters["timeout"].to_i
-
emit(:timeout, keep_alive_timeout)
-
end
-
106
@handshake_completed = true
-
when /close/i
-
3124
disable
-
when nil
-
# In HTTP/1.1, it's keep alive by default
-
return if response.version == "1.1" && request.headers["connection"] != "close"
-
-
disable
-
end
-
end
-
-
25
def disable
-
3136
disable_pipelining
-
3136
reset
-
3136
emit(:reset)
-
3130
throw(:called)
-
end
-
-
25
def disable_pipelining
-
3136
return if @requests.empty?
-
# do not disable pipelining if already set to 1 request at a time
-
168
return if @max_concurrent_requests == 1
-
-
24
@requests.each do |r|
-
24
r.transition(:idle)
-
-
# when we disable pipelining, we still want to try keep-alive.
-
# only when keep-alive with one request fails, do we fallback to
-
# connection: close.
-
24
r.headers["connection"] = "close" if @max_concurrent_requests == 1
-
end
-
# server doesn't handle pipelining, and probably
-
# doesn't support keep-alive. Fallback to send only
-
# 1 keep alive request.
-
24
@max_concurrent_requests = 1
-
24
@pipelining = false
-
end
-
-
25
def set_protocol_headers(request)
-
3907
if !request.headers.key?("content-length") &&
-
request.body.bytesize == Float::INFINITY
-
24
request.body.chunk!
-
end
-
-
3907
extra_headers = {}
-
-
3907
unless request.headers.key?("connection")
-
3889
connection_value = if request.persistent?
-
# when in a persistent connection, the request can't be at
-
# the edge of a renegotiation
-
85
if @requests.index(request) + 1 < @max_requests
-
85
"keep-alive"
-
else
-
"close"
-
end
-
else
-
# when it's not a persistent connection, it sets "Connection: close" always
-
# on the last request of the possible batch (either allowed max requests,
-
# or if smaller, the size of the batch itself)
-
3804
requests_limit = [@max_requests, @requests.size].min
-
3804
if request == @requests[requests_limit - 1]
-
3254
"close"
-
else
-
550
"keep-alive"
-
end
-
end
-
-
3889
extra_headers["connection"] = connection_value
-
end
-
3907
extra_headers["host"] = request.authority unless request.headers.key?("host")
-
3907
extra_headers
-
end
-
-
25
def handle(request)
-
4891
catch(:buffer_full) do
-
4891
request.transition(:headers)
-
4885
join_headers(request) if request.state == :headers
-
4885
request.transition(:body)
-
4885
join_body(request) if request.state == :body
-
4063
request.transition(:trailers)
-
# HTTP/1.1 trailers should only work for chunked encoding
-
4063
join_trailers(request) if request.body.chunked? && request.state == :trailers
-
4063
request.transition(:done)
-
end
-
end
-
-
25
def join_headline(request)
-
3846
"#{request.verb} #{request.path} HTTP/#{@version.join(".")}"
-
end
-
-
25
def join_headers(request)
-
3907
headline = join_headline(request)
-
3907
@buffer << headline << CRLF
-
3931
log(color: :yellow) { "<- HEADLINE: #{headline.chomp.inspect}" }
-
3907
extra_headers = set_protocol_headers(request)
-
3907
join_headers2(request.headers.each(extra_headers))
-
3931
log { "<- " }
-
3907
@buffer << CRLF
-
end
-
-
25
def join_body(request)
-
4717
return if request.body.empty?
-
-
5646
while (chunk = request.drain_body)
-
2472
log(color: :green) { "<- DATA: #{chunk.bytesize} bytes..." }
-
2472
log(level: 2, color: :green) { "<- #{log_redact(chunk.inspect)}" }
-
2472
@buffer << chunk
-
2472
throw(:buffer_full, request) if @buffer.full?
-
end
-
-
1176
return unless (error = request.drain_error)
-
-
raise error
-
end
-
-
25
def join_trailers(request)
-
72
return unless request.trailers? && request.callbacks_for?(:trailers)
-
-
24
join_headers2(request.trailers)
-
24
log { "<- " }
-
24
@buffer << CRLF
-
end
-
-
25
def join_headers2(headers)
-
3931
headers.each do |field, value|
-
24139
field = capitalized(field)
-
24259
log(color: :yellow) { "<- HEADER: #{[field, log_redact(value)].join(": ")}" }
-
24139
@buffer << "#{field}: #{value}#{CRLF}"
-
end
-
end
-
-
25
UPCASED = {
-
"www-authenticate" => "WWW-Authenticate",
-
"http2-settings" => "HTTP2-Settings",
-
"content-md5" => "Content-MD5",
-
}.freeze
-
-
25
def capitalized(field)
-
24139
UPCASED[field] || field.split("-").map(&:capitalize).join("-")
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "securerandom"
-
25
require "http/2"
-
-
25
module HTTPX
-
25
class Connection::HTTP2
-
25
include Callbacks
-
25
include Loggable
-
-
25
MAX_CONCURRENT_REQUESTS = ::HTTP2::DEFAULT_MAX_CONCURRENT_STREAMS
-
-
25
class Error < Error
-
25
def initialize(id, error)
-
44
super("stream #{id} closed with error: #{error}")
-
end
-
end
-
-
25
class PingError < Error
-
25
def initialize
-
super(0, :ping_error)
-
end
-
end
-
-
25
class GoawayError < Error
-
25
def initialize
-
14
super(0, :no_error)
-
end
-
end
-
-
25
attr_reader :streams, :pending
-
-
25
def initialize(buffer, options)
-
2516
@options = options
-
2516
@settings = @options.http2_settings
-
2516
@pending = []
-
2516
@streams = {}
-
2516
@drains = {}
-
2516
@pings = []
-
2516
@buffer = buffer
-
2516
@handshake_completed = false
-
2516
@wait_for_handshake = @settings.key?(:wait_for_handshake) ? @settings.delete(:wait_for_handshake) : true
-
2516
@max_concurrent_requests = @options.max_concurrent_requests || MAX_CONCURRENT_REQUESTS
-
2516
@max_requests = @options.max_requests
-
2516
init_connection
-
end
-
-
25
def timeout
-
4967
return @options.timeout[:operation_timeout] if @handshake_completed
-
-
2481
@options.timeout[:settings_timeout]
-
end
-
-
25
def interests
-
# waiting for WINDOW_UPDATE frames
-
9714486
return :r if @buffer.full?
-
-
9714486
if @connection.state == :closed
-
2225
return unless @handshake_completed
-
-
2183
return :w
-
end
-
-
9712261
unless @connection.state == :connected && @handshake_completed
-
10599
return @buffer.empty? ? :r : :rw
-
end
-
-
9701662
return :w if !@pending.empty? && can_buffer_more_requests?
-
-
9701662
return :w unless @drains.empty?
-
-
9700920
if @buffer.empty?
-
9700920
return if @streams.empty? && @pings.empty?
-
-
34760
return :r
-
end
-
-
:rw
-
end
-
-
25
def close
-
2113
unless @connection.state == :closed
-
2107
@connection.goaway
-
2107
emit(:timeout, @options.timeout[:close_handshake_timeout])
-
end
-
2113
emit(:close, true)
-
end
-
-
25
def empty?
-
2107
@connection.state == :closed || @streams.empty?
-
end
-
-
25
def exhausted?
-
2520
!@max_requests.positive?
-
end
-
-
25
def <<(data)
-
25336
@connection << data
-
end
-
-
25
def send(request, head = false)
-
5498
unless can_buffer_more_requests?
-
2660
head ? @pending.unshift(request) : @pending << request
-
2660
return false
-
end
-
2838
unless (stream = @streams[request])
-
2838
stream = @connection.new_stream
-
2838
handle_stream(stream, request)
-
2838
@streams[request] = stream
-
2838
@max_requests -= 1
-
end
-
2838
handle(request, stream)
-
2826
true
-
rescue ::HTTP2::Error::StreamLimitExceeded
-
@pending.unshift(request)
-
false
-
end
-
-
25
def consume
-
19804
@streams.each do |request, stream|
-
7943
next unless request.can_buffer?
-
-
850
handle(request, stream)
-
end
-
end
-
-
25
def handle_error(ex, request = nil)
-
209
if ex.is_a?(OperationTimeoutError) && !@handshake_completed && @connection.state != :closed
-
6
@connection.goaway(:settings_timeout, "closing due to settings timeout")
-
6
emit(:close_handshake)
-
6
settings_ex = SettingsTimeoutError.new(ex.timeout, ex.message)
-
6
settings_ex.set_backtrace(ex.backtrace)
-
6
ex = settings_ex
-
end
-
209
@streams.each_key do |req|
-
172
next if request && request == req
-
-
14
emit(:error, req, ex)
-
end
-
445
while (req = @pending.shift)
-
27
next if request && request == req
-
-
27
emit(:error, req, ex)
-
end
-
end
-
-
25
def ping
-
16
ping = SecureRandom.gen_random(8)
-
16
@connection.ping(ping.dup)
-
ensure
-
16
@pings << ping
-
end
-
-
25
private
-
-
25
def can_buffer_more_requests?
-
5891
(@handshake_completed || !@wait_for_handshake) &&
-
@streams.size < @max_concurrent_requests &&
-
@streams.size < @max_requests
-
end
-
-
25
def send_pending
-
7468
while (request = @pending.shift)
-
2563
break unless send(request, true)
-
end
-
end
-
-
25
def handle(request, stream)
-
3796
catch(:buffer_full) do
-
3796
request.transition(:headers)
-
3790
join_headers(stream, request) if request.state == :headers
-
3790
request.transition(:body)
-
3790
join_body(stream, request) if request.state == :body
-
2964
request.transition(:trailers)
-
2964
join_trailers(stream, request) if request.state == :trailers && !request.body.empty?
-
2964
request.transition(:done)
-
end
-
end
-
-
25
def init_connection
-
2516
@connection = ::HTTP2::Client.new(@settings)
-
2516
@connection.on(:frame, &method(:on_frame))
-
2516
@connection.on(:frame_sent, &method(:on_frame_sent))
-
2516
@connection.on(:frame_received, &method(:on_frame_received))
-
2516
@connection.on(:origin, &method(:on_origin))
-
2516
@connection.on(:promise, &method(:on_promise))
-
2516
@connection.on(:altsvc) { |frame| on_altsvc(frame[:origin], frame) }
-
2516
@connection.on(:settings_ack, &method(:on_settings))
-
2516
@connection.on(:ack, &method(:on_pong))
-
2516
@connection.on(:goaway, &method(:on_close))
-
#
-
# Some servers initiate HTTP/2 negotiation right away, some don't.
-
# As such, we have to check the socket buffer. If there is something
-
# to read, the server initiated the negotiation. If not, we have to
-
# initiate it.
-
#
-
2516
@connection.send_connection_preface
-
end
-
-
25
alias_method :reset, :init_connection
-
25
public :reset
-
-
25
def handle_stream(stream, request)
-
2850
request.on(:refuse, &method(:on_stream_refuse).curry(3)[stream, request])
-
2850
stream.on(:close, &method(:on_stream_close).curry(3)[stream, request])
-
2850
stream.on(:half_close) do
-
2820
log(level: 2) { "#{stream.id}: waiting for response..." }
-
end
-
2850
stream.on(:altsvc, &method(:on_altsvc).curry(2)[request.origin])
-
2850
stream.on(:headers, &method(:on_stream_headers).curry(3)[stream, request])
-
2850
stream.on(:data, &method(:on_stream_data).curry(3)[stream, request])
-
end
-
-
25
def set_protocol_headers(request)
-
{
-
2832
":scheme" => request.scheme,
-
":method" => request.verb,
-
":path" => request.path,
-
":authority" => request.authority,
-
}
-
end
-
-
25
def join_headers(stream, request)
-
2832
extra_headers = set_protocol_headers(request)
-
-
2832
if request.headers.key?("host")
-
6
log { "forbidden \"host\" header found (#{log_redact(request.headers["host"])}), will use it as authority..." }
-
6
extra_headers[":authority"] = request.headers["host"]
-
end
-
-
2832
log(level: 1, color: :yellow) do
-
108
request.headers.merge(extra_headers).each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact(v)}" }.join("\n")
-
end
-
2832
stream.headers(request.headers.each(extra_headers), end_stream: request.body.empty?)
-
end
-
-
25
def join_trailers(stream, request)
-
1201
unless request.trailers?
-
1195
stream.data("", end_stream: true) if request.callbacks_for?(:trailers)
-
1195
return
-
end
-
-
6
log(level: 1, color: :yellow) do
-
12
request.trailers.each.map { |k, v| "#{stream.id}: -> HEADER: #{k}: #{log_redact(v)}" }.join("\n")
-
end
-
6
stream.headers(request.trailers.each, end_stream: true)
-
end
-
-
25
def join_body(stream, request)
-
3646
return if request.body.empty?
-
-
2027
chunk = @drains.delete(request) || request.drain_body
-
2027
while chunk
-
2183
next_chunk = request.drain_body
-
2183
send_chunk(request, stream, chunk, next_chunk)
-
-
2111
if next_chunk && (@buffer.full? || request.body.unbounded_body?)
-
754
@drains[request] = next_chunk
-
754
throw(:buffer_full)
-
end
-
-
1357
chunk = next_chunk
-
end
-
-
1201
return unless (error = request.drain_error)
-
-
24
on_stream_refuse(stream, request, error)
-
end
-
-
25
def send_chunk(request, stream, chunk, next_chunk)
-
2201
log(level: 1, color: :green) { "#{stream.id}: -> DATA: #{chunk.bytesize} bytes..." }
-
2201
log(level: 2, color: :green) { "#{stream.id}: -> #{log_redact(chunk.inspect)}" }
-
2183
stream.data(chunk, end_stream: end_stream?(request, next_chunk))
-
end
-
-
25
def end_stream?(request, next_chunk)
-
2111
!(next_chunk || request.trailers? || request.callbacks_for?(:trailers))
-
end
-
-
######
-
# HTTP/2 Callbacks
-
######
-
-
25
def on_stream_headers(stream, request, h)
-
2820
response = request.response
-
-
2820
if response.is_a?(Response) && response.version == "2.0"
-
114
on_stream_trailers(stream, response, h)
-
114
return
-
end
-
-
2706
log(color: :yellow) do
-
108
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{log_redact(v)}" }.join("\n")
-
end
-
2706
_, status = h.shift
-
2706
headers = request.options.headers_class.new(h)
-
2706
response = request.options.response_class.new(request, status, "2.0", headers)
-
2706
request.response = response
-
2700
@streams[request] = stream
-
-
2700
handle(request, stream) if request.expects?
-
end
-
-
25
def on_stream_trailers(stream, response, h)
-
114
log(color: :yellow) do
-
h.map { |k, v| "#{stream.id}: <- HEADER: #{k}: #{log_redact(v)}" }.join("\n")
-
end
-
114
response.merge_headers(h)
-
end
-
-
25
def on_stream_data(stream, request, data)
-
4922
log(level: 1, color: :green) { "#{stream.id}: <- DATA: #{data.bytesize} bytes..." }
-
4922
log(level: 2, color: :green) { "#{stream.id}: <- #{log_redact(data.inspect)}" }
-
4904
request.response << data
-
end
-
-
25
def on_stream_refuse(stream, request, error)
-
24
on_stream_close(stream, request, error)
-
24
stream.close
-
end
-
-
25
def on_stream_close(stream, request, error)
-
2664
return if error == :stream_closed && !@streams.key?(request)
-
-
2652
log(level: 2) { "#{stream.id}: closing stream" }
-
2640
@drains.delete(request)
-
2640
@streams.delete(request)
-
-
2640
if error
-
24
case error
-
when :http_1_1_required
-
emit(:error, request, error)
-
else
-
24
ex = Error.new(stream.id, error)
-
24
ex.set_backtrace(caller)
-
24
response = ErrorResponse.new(request, ex)
-
24
request.response = response
-
24
emit(:response, request, response)
-
end
-
else
-
2616
response = request.response
-
2616
if response && response.is_a?(Response) && response.status == 421
-
6
emit(:error, request, :http_1_1_required)
-
else
-
2610
emit(:response, request, response)
-
end
-
end
-
2634
send(@pending.shift) unless @pending.empty?
-
-
2634
return unless @streams.empty? && exhausted?
-
-
6
if @pending.empty?
-
close
-
else
-
6
emit(:exhausted)
-
end
-
end
-
-
25
def on_frame(bytes)
-
15595
@buffer << bytes
-
end
-
-
25
def on_settings(*)
-
2486
@handshake_completed = true
-
2486
emit(:current_timeout)
-
2486
@max_concurrent_requests = [@max_concurrent_requests, @connection.remote_settings[:settings_max_concurrent_streams]].min
-
2486
send_pending
-
end
-
-
25
def on_close(_last_frame, error, _payload)
-
26
is_connection_closed = @connection.state == :closed
-
26
if error
-
26
@buffer.clear if is_connection_closed
-
26
case error
-
when :http_1_1_required
-
18
while (request = @pending.shift)
-
6
emit(:error, request, error)
-
end
-
when :no_error
-
14
ex = GoawayError.new
-
14
@pending.unshift(*@streams.keys)
-
14
@drains.clear
-
14
@streams.clear
-
else
-
6
ex = Error.new(0, error)
-
end
-
-
26
if ex
-
20
ex.set_backtrace(caller)
-
20
handle_error(ex)
-
end
-
end
-
26
return unless is_connection_closed && @streams.empty?
-
-
26
emit(:close, is_connection_closed)
-
end
-
-
25
def on_frame_sent(frame)
-
13145
log(level: 2) { "#{frame[:stream]}: frame was sent!" }
-
13073
log(level: 2, color: :blue) do
-
payload =
-
72
case frame[:type]
-
when :data
-
18
frame.merge(payload: frame[:payload].bytesize)
-
when :headers, :ping
-
18
frame.merge(payload: log_redact(frame[:payload]))
-
else
-
36
frame
-
end
-
72
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
25
def on_frame_received(frame)
-
13862
log(level: 2) { "#{frame[:stream]}: frame was received!" }
-
13808
log(level: 2, color: :magenta) do
-
payload =
-
54
case frame[:type]
-
when :data
-
18
frame.merge(payload: frame[:payload].bytesize)
-
when :headers, :ping
-
12
frame.merge(payload: log_redact(frame[:payload]))
-
else
-
24
frame
-
end
-
54
"#{frame[:stream]}: #{payload}"
-
end
-
end
-
-
25
def on_altsvc(origin, frame)
-
log(level: 2) { "#{frame[:stream]}: altsvc frame was received" }
-
log(level: 2) { "#{frame[:stream]}: #{log_redact(frame.inspect)}" }
-
alt_origin = URI.parse("#{frame[:proto]}://#{frame[:host]}:#{frame[:port]}")
-
params = { "ma" => frame[:max_age] }
-
emit(:altsvc, origin, alt_origin, origin, params)
-
end
-
-
25
def on_promise(stream)
-
18
emit(:promise, @streams.key(stream.parent), stream)
-
end
-
-
25
def on_origin(origin)
-
emit(:origin, origin)
-
end
-
-
25
def on_pong(ping)
-
6
raise PingError unless @pings.delete(ping.to_s)
-
-
6
emit(:pong)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
#
-
# domain_name.rb - Domain Name manipulation library for Ruby
-
#
-
# Copyright (C) 2011-2017 Akinori MUSHA, All rights reserved.
-
#
-
# Redistribution and use in source and binary forms, with or without
-
# modification, are permitted provided that the following conditions
-
# are met:
-
# 1. Redistributions of source code must retain the above copyright
-
# notice, this list of conditions and the following disclaimer.
-
# 2. Redistributions in binary form must reproduce the above copyright
-
# notice, this list of conditions and the following disclaimer in the
-
# documentation and/or other materials provided with the distribution.
-
#
-
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-
# SUCH DAMAGE.
-
-
25
require "ipaddr"
-
-
25
module HTTPX
-
# Represents a domain name ready for extracting its registered domain
-
# and TLD.
-
25
class DomainName
-
25
include Comparable
-
-
# The full host name normalized, ASCII-ized and downcased using the
-
# Unicode NFC rules and the Punycode algorithm. If initialized with
-
# an IP address, the string representation of the IP address
-
# suitable for opening a connection to.
-
25
attr_reader :hostname
-
-
# The Unicode representation of the #hostname property.
-
#
-
# :attr_reader: hostname_idn
-
-
# The least "universally original" domain part of this domain name.
-
# For example, "example.co.uk" for "www.sub.example.co.uk". This
-
# may be nil if the hostname does not have one, like when it is an
-
# IP address, an effective TLD or higher itself, or of a
-
# non-canonical domain.
-
25
attr_reader :domain
-
-
25
class << self
-
25
def new(domain)
-
642
return domain if domain.is_a?(self)
-
-
594
super(domain)
-
end
-
-
# Normalizes a _domain_ using the Punycode algorithm as necessary.
-
# The result will be a downcased, ASCII-only string.
-
25
def normalize(domain)
-
570
unless domain.ascii_only?
-
domain = domain.chomp(".").unicode_normalize(:nfc)
-
domain = Punycode.encode_hostname(domain)
-
end
-
-
570
domain.downcase
-
end
-
end
-
-
# Parses _hostname_ into a DomainName object. An IP address is also
-
# accepted. An IPv6 address may be enclosed in square brackets.
-
25
def initialize(hostname)
-
594
hostname = String(hostname)
-
-
594
raise ArgumentError, "domain name must not start with a dot: #{hostname}" if hostname.start_with?(".")
-
-
begin
-
594
@ipaddr = IPAddr.new(hostname)
-
24
@hostname = @ipaddr.to_s
-
24
return
-
rescue IPAddr::Error
-
570
nil
-
end
-
-
570
@hostname = DomainName.normalize(hostname)
-
570
tld = if (last_dot = @hostname.rindex("."))
-
138
@hostname[(last_dot + 1)..-1]
-
else
-
432
@hostname
-
end
-
-
# unknown/local TLD
-
570
@domain = if last_dot
-
# fallback - accept cookies down to second level
-
# cf. http://www.dkim-reputation.org/regdom-libs/
-
138
if (penultimate_dot = @hostname.rindex(".", last_dot - 1))
-
36
@hostname[(penultimate_dot + 1)..-1]
-
else
-
102
@hostname
-
end
-
else
-
# no domain part - must be a local hostname
-
432
tld
-
end
-
end
-
-
# Checks if the server represented by this domain is qualified to
-
# send and receive cookies with a domain attribute value of
-
# _domain_. A true value given as the second argument represents
-
# cookies without a domain attribute value, in which case only
-
# hostname equality is checked.
-
25
def cookie_domain?(domain, host_only = false)
-
# RFC 6265 #5.3
-
# When the user agent "receives a cookie":
-
24
return self == @domain if host_only
-
-
24
domain = DomainName.new(domain)
-
-
# RFC 6265 #5.1.3
-
# Do not perform subdomain matching against IP addresses.
-
24
@hostname == domain.hostname if @ipaddr
-
-
# RFC 6265 #4.1.1
-
# Domain-value must be a subdomain.
-
24
@domain && self <= domain && domain <= @domain
-
end
-
-
25
def <=>(other)
-
36
other = DomainName.new(other)
-
36
othername = other.hostname
-
36
if othername == @hostname
-
12
0
-
24
elsif @hostname.end_with?(othername) && @hostname[-othername.size - 1, 1] == "."
-
# The other is higher
-
12
-1
-
else
-
# The other is lower
-
12
1
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
# the default exception class for exceptions raised by HTTPX.
-
25
class Error < StandardError; end
-
-
25
class UnsupportedSchemeError < Error; end
-
-
25
class ConnectionError < Error; end
-
-
# Error raised when there was a timeout. Its subclasses allow for finer-grained
-
# control of which timeout happened.
-
25
class TimeoutError < Error
-
# The timeout value which caused this error to be raised.
-
25
attr_reader :timeout
-
-
# initializes the timeout exception with the +timeout+ causing the error, and the
-
# error +message+ for it.
-
25
def initialize(timeout, message)
-
400
@timeout = timeout
-
400
super(message)
-
end
-
-
# clones this error into a HTTPX::ConnectionTimeoutError.
-
25
def to_connection_error
-
18
ex = ConnectTimeoutError.new(@timeout, message)
-
18
ex.set_backtrace(backtrace)
-
18
ex
-
end
-
end
-
-
# Raise when it can't acquire a connection from the pool.
-
25
class PoolTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout establishing the connection to a server.
-
# This may be raised due to timeouts during TCP and TLS (when applicable) connection
-
# establishment.
-
25
class ConnectTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while sending a request, or receiving a response
-
# from the server.
-
25
class RequestTimeoutError < TimeoutError
-
# The HTTPX::Request request object this exception refers to.
-
25
attr_reader :request
-
-
# initializes the exception with the +request+ and +response+ it refers to, and the
-
# +timeout+ causing the error, and the
-
25
def initialize(request, response, timeout)
-
309
@request = request
-
309
@response = response
-
309
super(timeout, "Timed out after #{timeout} seconds")
-
end
-
-
25
def marshal_dump
-
[message]
-
end
-
end
-
-
# Error raised when there was a timeout while receiving a response from the server.
-
25
class ReadTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while sending a request from the server.
-
25
class WriteTimeoutError < RequestTimeoutError; end
-
-
# Error raised when there was a timeout while waiting for the HTTP/2 settings frame from the server.
-
25
class SettingsTimeoutError < TimeoutError; end
-
-
# Error raised when there was a timeout while resolving a domain to an IP.
-
25
class ResolveTimeoutError < TimeoutError; end
-
-
# Error raise when there was a timeout waiting for readiness of the socket the request is related to.
-
25
class OperationTimeoutError < TimeoutError; end
-
-
# Error raised when there was an error while resolving a domain to an IP.
-
25
class ResolveError < Error; end
-
-
# Error raised when there was an error while resolving a domain to an IP
-
# using a HTTPX::Resolver::Native resolver.
-
25
class NativeResolveError < ResolveError
-
25
attr_reader :connection, :host
-
-
# initializes the exception with the +connection+ it refers to, the +host+ domain
-
# which failed to resolve, and the error +message+.
-
25
def initialize(connection, host, message = "Can't resolve #{host}")
-
114
@connection = connection
-
114
@host = host
-
114
super(message)
-
end
-
end
-
-
# The exception class for HTTP responses with 4xx or 5xx status.
-
25
class HTTPError < Error
-
# The HTTPX::Response response object this exception refers to.
-
25
attr_reader :response
-
-
# Creates the instance and assigns the HTTPX::Response +response+.
-
25
def initialize(response)
-
72
@response = response
-
72
super("HTTP Error: #{@response.status} #{@response.headers}\n#{@response.body}")
-
end
-
-
# The HTTP response status.
-
#
-
# error.status #=> 404
-
25
def status
-
12
@response.status
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "uri"
-
-
25
module HTTPX
-
25
module ArrayExtensions
-
25
module FilterMap
-
refine Array do
-
# Ruby 2.7 backport
-
def filter_map
-
return to_enum(:filter_map) unless block_given?
-
-
each_with_object([]) do |item, res|
-
processed = yield(item)
-
res << processed if processed
-
end
-
end
-
25
end unless Array.method_defined?(:filter_map)
-
end
-
-
25
module Intersect
-
refine Array do
-
# Ruby 3.1 backport
-
4
def intersect?(arr)
-
if size < arr.size
-
smaller = self
-
else
-
smaller, arr = arr, self
-
end
-
(arr & smaller).size > 0
-
end
-
25
end unless Array.method_defined?(:intersect?)
-
end
-
end
-
-
25
module URIExtensions
-
# uri 0.11 backport, ships with ruby 3.1
-
25
refine URI::Generic do
-
-
25
def non_ascii_hostname
-
389
@non_ascii_hostname
-
end
-
-
25
def non_ascii_hostname=(hostname)
-
24
@non_ascii_hostname = hostname
-
end
-
-
def authority
-
5694
return host if port == default_port
-
-
598
"#{host}:#{port}"
-
25
end unless URI::HTTP.method_defined?(:authority)
-
-
def origin
-
4634
"#{scheme}://#{authority}"
-
25
end unless URI::HTTP.method_defined?(:origin)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
class Headers
-
25
class << self
-
25
def new(headers = nil)
-
20314
return headers if headers.is_a?(self)
-
-
9233
super
-
end
-
end
-
-
25
def initialize(headers = nil)
-
9233
if headers.nil? || headers.empty?
-
1458
@headers = headers.to_h
-
1458
return
-
end
-
-
7775
@headers = {}
-
-
7775
headers.each do |field, value|
-
47982
field = downcased(field)
-
-
47982
value = array_value(value)
-
-
47982
current = @headers[field]
-
-
47982
if current.nil?
-
47941
@headers[field] = value
-
else
-
41
current.concat(value)
-
end
-
end
-
end
-
-
# cloned initialization
-
25
def initialize_clone(orig, **kwargs)
-
6
super
-
6
@headers = orig.instance_variable_get(:@headers).clone(**kwargs)
-
end
-
-
# dupped initialization
-
25
def initialize_dup(orig)
-
12219
super
-
12219
@headers = orig.instance_variable_get(:@headers).dup
-
end
-
-
# freezes the headers hash
-
25
def freeze
-
15880
@headers.freeze
-
15880
super
-
end
-
-
# merges headers with another header-quack.
-
# the merge rule is, if the header already exists,
-
# ignore what the +other+ headers has. Otherwise, set
-
#
-
25
def merge(other)
-
3883
headers = dup
-
3883
other.each do |field, value|
-
3966
headers[downcased(field)] = value
-
end
-
3883
headers
-
end
-
-
# returns the comma-separated values of the header field
-
# identified by +field+, or nil otherwise.
-
#
-
25
def [](field)
-
74663
a = @headers[downcased(field)] || return
-
22403
a.join(", ")
-
end
-
-
# sets +value+ (if not nil) as single value for the +field+ header.
-
#
-
25
def []=(field, value)
-
33151
return unless value
-
-
33151
@headers[downcased(field)] = array_value(value)
-
end
-
-
# deletes all values associated with +field+ header.
-
#
-
25
def delete(field)
-
210
canonical = downcased(field)
-
210
@headers.delete(canonical) if @headers.key?(canonical)
-
end
-
-
# adds additional +value+ to the existing, for header +field+.
-
#
-
25
def add(field, value)
-
444
(@headers[downcased(field)] ||= []) << String(value)
-
end
-
-
# helper to be used when adding an header field as a value to another field
-
#
-
# h2_headers.add_header("vary", "accept-encoding")
-
# h2_headers["vary"] #=> "accept-encoding"
-
# h1_headers.add_header("vary", "accept-encoding")
-
# h1_headers["vary"] #=> "Accept-Encoding"
-
#
-
25
alias_method :add_header, :add
-
-
# returns the enumerable headers store in pairs of header field + the values in
-
# the comma-separated string format
-
#
-
25
def each(extra_headers = nil)
-
53903
return enum_for(__method__, extra_headers) { @headers.size } unless block_given?
-
-
28690
@headers.each do |field, value|
-
39181
yield(field, value.join(", ")) unless value.empty?
-
end
-
-
5080
extra_headers.each do |field, value|
-
19193
yield(field, value) unless value.empty?
-
28690
end if extra_headers
-
end
-
-
25
def ==(other)
-
16750
other == to_hash
-
end
-
-
25
def empty?
-
234
@headers.empty?
-
end
-
-
# the headers store in Hash format
-
25
def to_hash
-
18295
Hash[to_a]
-
end
-
25
alias_method :to_h, :to_hash
-
-
# the headers store in array of pairs format
-
25
def to_a
-
18312
Array(each)
-
end
-
-
# headers as string
-
25
def to_s
-
1626
@headers.to_s
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"#{to_hash.inspect}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# this is internal API and doesn't abide to other public API
-
# guarantees, like downcasing strings.
-
# Please do not use this outside of core!
-
#
-
25
def key?(downcased_key)
-
50795
@headers.key?(downcased_key)
-
end
-
-
# returns the values for the +field+ header in array format.
-
# This method is more internal, and for this reason doesn't try
-
# to "correct" the user input, i.e. it doesn't downcase the key.
-
#
-
25
def get(field)
-
227
@headers[field] || EMPTY
-
end
-
-
25
private
-
-
25
def array_value(value)
-
81133
Array(value)
-
end
-
-
25
def downcased(field)
-
160416
String(field).downcase
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "socket"
-
25
require "httpx/io/udp"
-
25
require "httpx/io/tcp"
-
25
require "httpx/io/unix"
-
-
begin
-
25
require "httpx/io/ssl"
-
rescue LoadError
-
end
-
# frozen_string_literal: true
-
-
25
require "openssl"
-
-
25
module HTTPX
-
25
TLSError = OpenSSL::SSL::SSLError
-
-
25
class SSL < TCP
-
# rubocop:disable Style/MutableConstant
-
25
TLS_OPTIONS = { alpn_protocols: %w[h2 http/1.1].freeze }
-
# https://github.com/jruby/jruby-openssl/issues/284
-
# TODO: remove when dropping support for jruby-openssl < 0.15.4
-
25
TLS_OPTIONS[:verify_hostname] = true if RUBY_ENGINE == "jruby" && JOpenSSL::VERSION < "0.15.4"
-
# rubocop:enable Style/MutableConstant
-
25
TLS_OPTIONS.freeze
-
-
25
attr_writer :ssl_session
-
-
25
def initialize(_, _, options)
-
2326
super
-
-
2326
ctx_options = TLS_OPTIONS.merge(options.ssl)
-
2326
@sni_hostname = ctx_options.delete(:hostname) || @hostname
-
-
2326
if @keep_open && @io.is_a?(OpenSSL::SSL::SSLSocket)
-
# externally initiated ssl socket
-
18
@ctx = @io.context
-
18
@state = :negotiated
-
else
-
2308
@ctx = OpenSSL::SSL::SSLContext.new
-
2308
@ctx.set_params(ctx_options) unless ctx_options.empty?
-
2308
unless @ctx.session_cache_mode.nil? # a dummy method on JRuby
-
2308
@ctx.session_cache_mode =
-
OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE
-
end
-
-
2308
yield(self) if block_given?
-
end
-
-
2326
@verify_hostname = @ctx.verify_hostname
-
end
-
-
25
if OpenSSL::SSL::SSLContext.method_defined?(:session_new_cb=)
-
25
def session_new_cb(&pr)
-
6638
@ctx.session_new_cb = proc { |_, sess| pr.call(sess) }
-
end
-
else
-
# session_new_cb not implemented under JRuby
-
def session_new_cb; end
-
end
-
-
25
def protocol
-
2509
@io.alpn_protocol || super
-
rescue StandardError
-
7
super
-
end
-
-
25
if RUBY_ENGINE == "jruby"
-
# in jruby, alpn_protocol may return ""
-
# https://github.com/jruby/jruby-openssl/issues/287
-
def protocol
-
proto = @io.alpn_protocol
-
-
return super if proto.nil? || proto.empty?
-
-
proto
-
rescue StandardError
-
super
-
end
-
end
-
-
25
def can_verify_peer?
-
13
@ctx.verify_mode == OpenSSL::SSL::VERIFY_PEER
-
end
-
-
25
def verify_hostname(host)
-
15
return false if @ctx.verify_mode == OpenSSL::SSL::VERIFY_NONE
-
15
return false if !@io.respond_to?(:peer_cert) || @io.peer_cert.nil?
-
-
15
OpenSSL::SSL.verify_certificate_identity(@io.peer_cert, host)
-
end
-
-
25
def connected?
-
10334
@state == :negotiated
-
end
-
-
25
def expired?
-
super || ssl_session_expired?
-
end
-
-
25
def ssl_session_expired?
-
2471
@ssl_session.nil? || Process.clock_gettime(Process::CLOCK_REALTIME) >= (@ssl_session.time.to_f + @ssl_session.timeout)
-
end
-
-
25
def connect
-
10382
return if @state == :negotiated
-
-
10382
unless @state == :connected
-
5649
super
-
5619
return unless @state == :connected
-
end
-
-
7135
unless @io.is_a?(OpenSSL::SSL::SSLSocket)
-
2471
if (hostname_is_ip = (@ip == @sni_hostname))
-
# IPv6 address would be "[::1]", must turn to "0000:0000:0000:0000:0000:0000:0000:0001" for cert SAN check
-
24
@sni_hostname = @ip.to_string
-
# IP addresses in SNI is not valid per RFC 6066, section 3.
-
24
@ctx.verify_hostname = false
-
end
-
-
2471
@io = OpenSSL::SSL::SSLSocket.new(@io, @ctx)
-
-
2471
@io.hostname = @sni_hostname unless hostname_is_ip
-
2471
@io.session = @ssl_session unless ssl_session_expired?
-
2471
@io.sync_close = true
-
end
-
7135
try_ssl_connect
-
end
-
-
25
def try_ssl_connect
-
7135
ret = @io.connect_nonblock(exception: false)
-
7152
log(level: 3, color: :cyan) { "TLS CONNECT: #{ret}..." }
-
7117
case ret
-
when :wait_readable
-
4682
@interests = :r
-
4682
return
-
when :wait_writable
-
@interests = :w
-
return
-
end
-
2435
@io.post_connection_check(@sni_hostname) if @ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE && @verify_hostname
-
2435
transition(:negotiated)
-
2435
@interests = :w
-
end
-
-
25
private
-
-
25
def transition(nextstate)
-
9630
case nextstate
-
when :negotiated
-
2435
return unless @state == :connected
-
-
when :closed
-
2361
return unless @state == :negotiated ||
-
@state == :connected
-
end
-
9630
do_transition(nextstate)
-
end
-
-
25
def log_transition_state(nextstate)
-
54
return super unless nextstate == :negotiated
-
-
12
server_cert = @io.peer_cert
-
-
12
"#{super}\n\n" \
-
"SSL connection using #{@io.ssl_version} / #{Array(@io.cipher).first}\n" \
-
"ALPN, server accepted to use #{protocol}\n" \
-
"Server certificate:\n " \
-
"subject: #{server_cert.subject}\n " \
-
"start date: #{server_cert.not_before}\n " \
-
"expire date: #{server_cert.not_after}\n " \
-
"issuer: #{server_cert.issuer}\n " \
-
"SSL certificate verify ok."
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "resolv"
-
25
require "ipaddr"
-
-
25
module HTTPX
-
25
class TCP
-
25
include Loggable
-
-
25
using URIExtensions
-
-
25
attr_reader :ip, :port, :addresses, :state, :interests
-
-
25
alias_method :host, :ip
-
-
25
def initialize(origin, addresses, options)
-
5481
@state = :idle
-
5481
@addresses = []
-
5481
@hostname = origin.host
-
5481
@options = options
-
5481
@fallback_protocol = @options.fallback_protocol
-
5481
@port = origin.port
-
5481
@interests = :w
-
5481
if @options.io
-
42
@io = case @options.io
-
when Hash
-
12
@options.io[origin.authority]
-
else
-
30
@options.io
-
end
-
42
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
42
_, _, _, @ip = @io.addr
-
42
@addresses << @ip
-
42
@keep_open = true
-
42
@state = :connected
-
else
-
5439
add_addresses(addresses)
-
end
-
5481
@ip_index = @addresses.size - 1
-
end
-
-
25
def socket
-
147
@io
-
end
-
-
25
def add_addresses(addrs)
-
5665
return if addrs.empty?
-
-
18120
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
5665
ip_index = @ip_index || (@addresses.size - 1)
-
5665
if addrs.first.ipv6?
-
# should be the next in line
-
226
@addresses = [*@addresses[0, ip_index], *addrs, *@addresses[ip_index..-1]]
-
else
-
5439
@addresses.unshift(*addrs)
-
5439
@ip_index += addrs.size if @ip_index
-
end
-
end
-
-
25
def to_io
-
19016
@io.to_io
-
end
-
-
25
def protocol
-
3452
@fallback_protocol
-
end
-
-
25
def connect
-
24115
return unless closed?
-
-
24018
if !@io || @io.closed?
-
6003
transition(:idle)
-
6003
@io = build_socket
-
end
-
24018
try_connect
-
rescue Errno::ECONNREFUSED,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
SocketError,
-
IOError => e
-
880
raise e if @ip_index <= 0
-
-
826
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
814
@ip_index -= 1
-
814
@io = build_socket
-
814
retry
-
rescue Errno::ETIMEDOUT => e
-
raise ConnectTimeoutError.new(@options.timeout[:connect_timeout], e.message) if @ip_index <= 0
-
-
log { "failed connecting to #{@ip} (#{e.message}), trying next..." }
-
@ip_index -= 1
-
@io = build_socket
-
retry
-
end
-
-
25
def try_connect
-
24018
ret = @io.connect_nonblock(Socket.sockaddr_in(@port, @ip.to_s), exception: false)
-
12838
log(level: 3, color: :cyan) { "TCP CONNECT: #{ret}..." }
-
12742
case ret
-
when :wait_readable
-
@interests = :r
-
return
-
when :wait_writable
-
6805
@interests = :w
-
6805
return
-
end
-
5937
transition(:connected)
-
5937
@interests = :w
-
rescue Errno::EALREADY
-
10396
@interests = :w
-
end
-
25
private :try_connect
-
-
25
def read(size, buffer)
-
40199
ret = @io.read_nonblock(size, buffer, exception: false)
-
40199
if ret == :wait_readable
-
8886
buffer.clear
-
8886
return 0
-
end
-
31313
return if ret.nil?
-
-
31365
log { "READ: #{buffer.bytesize} bytes..." }
-
31297
buffer.bytesize
-
end
-
-
25
def write(buffer)
-
16812
siz = @io.write_nonblock(buffer, exception: false)
-
16795
return 0 if siz == :wait_writable
-
16783
return if siz.nil?
-
-
16855
log { "WRITE: #{siz} bytes..." }
-
-
16783
buffer.shift!(siz)
-
16783
siz
-
end
-
-
25
def close
-
6545
return if @keep_open || closed?
-
-
begin
-
5761
@io.close
-
ensure
-
5761
transition(:closed)
-
end
-
end
-
-
25
def connected?
-
17628
@state == :connected
-
end
-
-
25
def closed?
-
30648
@state == :idle || @state == :closed
-
end
-
-
25
def expired?
-
# do not mess with external sockets
-
return false if @options.io
-
-
return true unless @addresses
-
-
resolver_addresses = Resolver.nolookup_resolve(@hostname)
-
-
(Array(resolver_addresses) & @addresses).empty?
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"#{@ip}:#{@port} " \
-
skipped
"@state=#{@state} " \
-
skipped
"@hostname=#{@hostname} " \
-
skipped
"@addresses=#{@addresses} " \
-
skipped
"@state=#{@state}>"
-
skipped
end
-
skipped
# :nocov:
-
-
25
private
-
-
25
def build_socket
-
6817
@ip = @addresses[@ip_index]
-
6817
Socket.new(@ip.family, :STREAM, 0)
-
end
-
-
25
def transition(nextstate)
-
10524
case nextstate
-
# when :idle
-
when :connected
-
3547
return unless @state == :idle
-
when :closed
-
3400
return unless @state == :connected
-
end
-
10524
do_transition(nextstate)
-
end
-
-
25
def do_transition(nextstate)
-
20286
log(level: 1) { log_transition_state(nextstate) }
-
20154
@state = nextstate
-
end
-
-
25
def log_transition_state(nextstate)
-
132
label = host
-
132
label = "#{label}(##{@io.fileno})" if nextstate == :connected
-
132
"#{label} #{@state} -> #{nextstate}"
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "ipaddr"
-
-
25
module HTTPX
-
25
class UDP
-
25
include Loggable
-
-
25
def initialize(ip, port, options)
-
320
@host = ip
-
320
@port = port
-
320
@io = UDPSocket.new(IPAddr.new(ip).family)
-
320
@options = options
-
end
-
-
25
def to_io
-
975
@io.to_io
-
end
-
-
25
def connect; end
-
-
25
def connected?
-
320
true
-
end
-
-
25
def close
-
320
@io.close
-
end
-
-
25
if RUBY_ENGINE == "jruby"
-
# In JRuby, sendmsg_nonblock is not implemented
-
def write(buffer)
-
siz = @io.send(buffer.to_s, 0, @host, @port)
-
log { "WRITE: #{siz} bytes..." }
-
buffer.shift!(siz)
-
siz
-
end
-
else
-
25
def write(buffer)
-
649
siz = @io.sendmsg_nonblock(buffer.to_s, 0, Socket.sockaddr_in(@port, @host.to_s), exception: false)
-
649
return 0 if siz == :wait_writable
-
649
return if siz.nil?
-
-
649
log { "WRITE: #{siz} bytes..." }
-
-
649
buffer.shift!(siz)
-
649
siz
-
end
-
end
-
-
25
def read(size, buffer)
-
1138
ret = @io.recvfrom_nonblock(size, 0, buffer, exception: false)
-
1138
return 0 if ret == :wait_readable
-
580
return if ret.nil?
-
-
580
log { "READ: #{buffer.bytesize} bytes..." }
-
-
580
buffer.bytesize
-
rescue IOError
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
class UNIX < TCP
-
25
using URIExtensions
-
-
25
attr_reader :path
-
-
25
alias_method :host, :path
-
-
25
def initialize(origin, path, options)
-
24
@addresses = []
-
24
@hostname = origin.host
-
24
@state = :idle
-
24
@options = options
-
24
@fallback_protocol = @options.fallback_protocol
-
24
if @options.io
-
12
@io = case @options.io
-
when Hash
-
6
@options.io[origin.authority]
-
else
-
6
@options.io
-
end
-
12
raise Error, "Given IO objects do not match the request authority" unless @io
-
-
12
@path = @io.path
-
12
@keep_open = true
-
12
@state = :connected
-
12
elsif path
-
12
@path = path
-
else
-
raise Error, "No path given where to store the socket"
-
end
-
24
@io ||= build_socket
-
end
-
-
25
def connect
-
18
return unless closed?
-
-
begin
-
18
if @io.closed?
-
6
transition(:idle)
-
6
@io = build_socket
-
end
-
18
@io.connect_nonblock(Socket.sockaddr_un(@path))
-
rescue Errno::EISCONN
-
end
-
12
transition(:connected)
-
rescue Errno::EINPROGRESS,
-
Errno::EALREADY,
-
::IO::WaitReadable
-
end
-
-
25
def expired?
-
false
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} @path=#{@path}) @state=#{@state})>"
-
skipped
end
-
skipped
# :nocov:
-
-
25
private
-
-
25
def build_socket
-
18
Socket.new(Socket::PF_UNIX, :STREAM, 0)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Loggable
-
25
COLORS = {
-
black: 30,
-
red: 31,
-
green: 32,
-
yellow: 33,
-
blue: 34,
-
magenta: 35,
-
cyan: 36,
-
white: 37,
-
}.freeze
-
-
25
USE_DEBUG_LOG = ENV.key?("HTTPX_DEBUG")
-
-
25
def log(
-
level: @options.debug_level,
-
color: nil,
-
debug_level: @options.debug_level,
-
debug: @options.debug,
-
&msg
-
)
-
10068993
return unless debug_level >= level
-
-
176917
debug_stream = debug || ($stderr if USE_DEBUG_LOG)
-
-
176917
return unless debug_stream
-
-
1929
klass = self.class
-
-
4242
until (class_name = klass.name)
-
384
klass = klass.superclass
-
end
-
-
1929
message = +"(pid:#{Process.pid} tid:#{Thread.current.object_id}, self:#{class_name}##{object_id}) "
-
1929
message << msg.call << "\n"
-
1929
message = "\e[#{COLORS[color]}m#{message}\e[0m" if color && debug_stream.respond_to?(:isatty) && debug_stream.isatty
-
1929
debug_stream << message
-
end
-
-
25
def log_exception(ex, level: @options.debug_level, color: nil, debug_level: @options.debug_level, debug: @options.debug)
-
974
log(level: level, color: color, debug_level: debug_level, debug: debug) { ex.full_message }
-
end
-
-
25
def log_redact(text, should_redact = @options.debug_redact)
-
600
return text.to_s unless should_redact
-
-
84
"[REDACTED]"
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "socket"
-
-
25
module HTTPX
-
# Contains a set of options which are passed and shared across from session to its requests or
-
# responses.
-
25
class Options
-
25
BUFFER_SIZE = 1 << 14
-
25
WINDOW_SIZE = 1 << 14 # 16K
-
25
MAX_BODY_THRESHOLD_SIZE = (1 << 10) * 112 # 112K
-
25
KEEP_ALIVE_TIMEOUT = 20
-
25
SETTINGS_TIMEOUT = 10
-
25
CLOSE_HANDSHAKE_TIMEOUT = 10
-
25
CONNECT_TIMEOUT = READ_TIMEOUT = WRITE_TIMEOUT = 60
-
25
REQUEST_TIMEOUT = OPERATION_TIMEOUT = nil
-
-
# https://github.com/ruby/resolv/blob/095f1c003f6073730500f02acbdbc55f83d70987/lib/resolv.rb#L408
-
ip_address_families = begin
-
25
list = Socket.ip_address_list
-
102
if list.any? { |a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? && !a.ipv6_unique_local? }
-
[Socket::AF_INET6, Socket::AF_INET]
-
else
-
25
[Socket::AF_INET]
-
end
-
rescue NotImplementedError
-
[Socket::AF_INET]
-
end.freeze
-
-
25
SET_TEMPORARY_NAME = ->(mod, pl = nil) do
-
7813
if mod.respond_to?(:set_temporary_name) # ruby 3.4 only
-
2713
name = mod.name || "#{mod.superclass.name}(plugin)"
-
2713
name = "#{name}/#{pl}" if pl
-
2713
mod.set_temporary_name(name)
-
end
-
end
-
-
DEFAULT_OPTIONS = {
-
25
:max_requests => Float::INFINITY,
-
:debug => nil,
-
25
:debug_level => (ENV["HTTPX_DEBUG"] || 1).to_i,
-
:debug_redact => ENV.key?("HTTPX_DEBUG_REDACT"),
-
:ssl => EMPTY_HASH,
-
:http2_settings => { settings_enable_push: 0 }.freeze,
-
:fallback_protocol => "http/1.1",
-
:supported_compression_formats => %w[gzip deflate],
-
:decompress_response_body => true,
-
:compress_request_body => true,
-
:timeout => {
-
connect_timeout: CONNECT_TIMEOUT,
-
settings_timeout: SETTINGS_TIMEOUT,
-
close_handshake_timeout: CLOSE_HANDSHAKE_TIMEOUT,
-
operation_timeout: OPERATION_TIMEOUT,
-
keep_alive_timeout: KEEP_ALIVE_TIMEOUT,
-
read_timeout: READ_TIMEOUT,
-
write_timeout: WRITE_TIMEOUT,
-
request_timeout: REQUEST_TIMEOUT,
-
},
-
:headers_class => Class.new(Headers, &SET_TEMPORARY_NAME),
-
:headers => {},
-
:window_size => WINDOW_SIZE,
-
:buffer_size => BUFFER_SIZE,
-
:body_threshold_size => MAX_BODY_THRESHOLD_SIZE,
-
:request_class => Class.new(Request, &SET_TEMPORARY_NAME),
-
:response_class => Class.new(Response, &SET_TEMPORARY_NAME),
-
:request_body_class => Class.new(Request::Body, &SET_TEMPORARY_NAME),
-
:response_body_class => Class.new(Response::Body, &SET_TEMPORARY_NAME),
-
:pool_class => Class.new(Pool, &SET_TEMPORARY_NAME),
-
:connection_class => Class.new(Connection, &SET_TEMPORARY_NAME),
-
:options_class => Class.new(self, &SET_TEMPORARY_NAME),
-
:transport => nil,
-
:addresses => nil,
-
:persistent => false,
-
25
:resolver_class => (ENV["HTTPX_RESOLVER"] || :native).to_sym,
-
:resolver_options => { cache: true }.freeze,
-
:pool_options => EMPTY_HASH,
-
:ip_families => ip_address_families,
-
:close_on_fork => false,
-
}.freeze
-
-
25
class << self
-
25
def new(options = {})
-
# let enhanced options go through
-
9247
return options if self == Options && options.class < self
-
7126
return options if options.is_a?(self)
-
-
3442
super
-
end
-
-
25
def method_added(meth)
-
17407
super
-
-
17407
return unless meth =~ /^option_(.+)$/
-
-
8042
optname = Regexp.last_match(1).to_sym
-
-
8042
attr_reader(optname)
-
end
-
end
-
-
# creates a new options instance from a given hash, which optionally define the following:
-
#
-
# :debug :: an object which log messages are written to (must respond to <tt><<</tt>)
-
# :debug_level :: the log level of messages (can be 1, 2, or 3).
-
# :debug_redact :: whether header/body payload should be redacted (defaults to <tt>false</tt>).
-
# :ssl :: a hash of options which can be set as params of OpenSSL::SSL::SSLContext (see HTTPX::IO::SSL)
-
# :http2_settings :: a hash of options to be passed to a HTTP2::Connection (ex: <tt>{ max_concurrent_streams: 2 }</tt>)
-
# :fallback_protocol :: version of HTTP protocol to use by default in the absence of protocol negotiation
-
# like ALPN (defaults to <tt>"http/1.1"</tt>)
-
# :supported_compression_formats :: list of compressions supported by the transcoder layer (defaults to <tt>%w[gzip deflate]</tt>).
-
# :decompress_response_body :: whether to auto-decompress response body (defaults to <tt>true</tt>).
-
# :compress_request_body :: whether to auto-decompress response body (defaults to <tt>true</tt>)
-
# :timeout :: hash of timeout configurations (supports <tt>:connect_timeout</tt>, <tt>:settings_timeout</tt>,
-
# <tt>:operation_timeout</tt>, <tt>:keep_alive_timeout</tt>, <tt>:read_timeout</tt>, <tt>:write_timeout</tt>
-
# and <tt>:request_timeout</tt>
-
# :headers :: hash of HTTP headers (ex: <tt>{ "x-custom-foo" => "bar" }</tt>)
-
# :window_size :: number of bytes to read from a socket
-
# :buffer_size :: internal read and write buffer size in bytes
-
# :body_threshold_size :: maximum size in bytes of response payload that is buffered in memory.
-
# :request_class :: class used to instantiate a request
-
# :response_class :: class used to instantiate a response
-
# :headers_class :: class used to instantiate headers
-
# :request_body_class :: class used to instantiate a request body
-
# :response_body_class :: class used to instantiate a response body
-
# :connection_class :: class used to instantiate connections
-
# :pool_class :: class used to instantiate the session connection pool
-
# :options_class :: class used to instantiate options
-
# :transport :: type of transport to use (set to "unix" for UNIX sockets)
-
# :addresses :: bucket of peer addresses (can be a list of IP addresses, a hash of domain to list of adddresses;
-
# paths should be used for UNIX sockets instead)
-
# :io :: open socket, or domain/ip-to-socket hash, which requests should be sent to
-
# :persistent :: whether to persist connections in between requests (defaults to <tt>true</tt>)
-
# :resolver_class :: which resolver to use (defaults to <tt>:native</tt>, can also be <tt>:system<tt> for
-
# using getaddrinfo or <tt>:https</tt> for DoH resolver, or a custom class)
-
# :resolver_options :: hash of options passed to the resolver. Accepted keys depend on the resolver type.
-
# :pool_options :: hash of options passed to the connection pool (See Pool#initialize).
-
# :ip_families :: which socket families are supported (system-dependent)
-
# :origin :: HTTP origin to set on requests with relative path (ex: "https://api.serv.com")
-
# :base_path :: path to prefix given relative paths with (ex: "/v2")
-
# :max_concurrent_requests :: max number of requests which can be set concurrently
-
# :max_requests :: max number of requests which can be made on socket before it reconnects.
-
# :close_on_fork :: whether the session automatically closes when the process is fork (defaults to <tt>false</tt>).
-
# it only works if the session is persistent (and ruby 3.1 or higher is used).
-
#
-
# This list of options are enhanced with each loaded plugin, see the plugin docs for details.
-
25
def initialize(options = {})
-
3442
do_initialize(options)
-
3430
freeze
-
end
-
-
25
def freeze
-
9349
@origin.freeze
-
9349
@base_path.freeze
-
9349
@timeout.freeze
-
9349
@headers.freeze
-
9349
@addresses.freeze
-
9349
@supported_compression_formats.freeze
-
9349
@ssl.freeze
-
9349
@http2_settings.freeze
-
9349
@pool_options.freeze
-
9349
@resolver_options.freeze
-
9349
@ip_families.freeze
-
9349
super
-
end
-
-
25
def option_origin(value)
-
528
URI(value)
-
end
-
-
25
def option_base_path(value)
-
24
String(value)
-
end
-
-
25
def option_headers(value)
-
6239
headers_class.new(value)
-
end
-
-
25
def option_timeout(value)
-
6761
Hash[value]
-
end
-
-
25
def option_supported_compression_formats(value)
-
5783
Array(value).map(&:to_s)
-
end
-
-
25
def option_transport(value)
-
42
transport = value.to_s
-
42
raise TypeError, "#{transport} is an unsupported transport type" unless %w[unix].include?(transport)
-
-
42
transport
-
end
-
-
25
def option_addresses(value)
-
36
Array(value)
-
end
-
-
25
def option_ip_families(value)
-
5759
Array(value)
-
end
-
-
# number options
-
25
%i[
-
max_concurrent_requests max_requests window_size buffer_size
-
body_threshold_size debug_level
-
].each do |option|
-
150
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
# converts +v+ into an Integer before setting the +#{option}+ option.
-
def option_#{option}(value) # def option_max_requests(v)
-
value = Integer(value) unless value.infinite?
-
raise TypeError, ":#{option} must be positive" unless value.positive? # raise TypeError, ":max_requests must be positive" unless value.positive?
-
-
value
-
end
-
OUT
-
end
-
-
# hashable options
-
25
%i[ssl http2_settings resolver_options pool_options].each do |option|
-
100
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
# converts +v+ into an Hash before setting the +#{option}+ option.
-
def option_#{option}(value) # def option_ssl(v)
-
Hash[value]
-
end
-
OUT
-
end
-
-
25
%i[
-
request_class response_class headers_class request_body_class
-
response_body_class connection_class options_class
-
pool_class pool_options
-
io fallback_protocol debug debug_redact resolver_class
-
compress_request_body decompress_response_body
-
persistent close_on_fork
-
].each do |method_name|
-
450
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
# sets +v+ as the value of the +#{method_name}+ option
-
def option_#{method_name}(v); v; end # def option_smth(v); v; end
-
OUT
-
end
-
-
25
REQUEST_BODY_IVARS = %i[@headers].freeze
-
-
25
def ==(other)
-
1655
super || options_equals?(other)
-
end
-
-
25
def options_equals?(other, ignore_ivars = REQUEST_BODY_IVARS)
-
# headers and other request options do not play a role, as they are
-
# relevant only for the request.
-
349
ivars = instance_variables - ignore_ivars
-
349
other_ivars = other.instance_variables - ignore_ivars
-
-
349
return false if ivars.size != other_ivars.size
-
-
336
return false if ivars.sort != other_ivars.sort
-
-
336
ivars.all? do |ivar|
-
8813
instance_variable_get(ivar) == other.instance_variable_get(ivar)
-
end
-
end
-
-
25
def merge(other)
-
28563
ivar_map = nil
-
28563
other_ivars = case other
-
when Hash
-
34092
ivar_map = other.keys.to_h { |k| [:"@#{k}", k] }
-
19840
ivar_map.keys
-
else
-
8723
other.instance_variables
-
end
-
-
28563
return self if other_ivars.empty?
-
-
248613
return self if other_ivars.all? { |ivar| instance_variable_get(ivar) == access_option(other, ivar, ivar_map) }
-
-
10564
opts = dup
-
-
10564
other_ivars.each do |ivar|
-
80076
v = access_option(other, ivar, ivar_map)
-
-
80076
unless v
-
7489
opts.instance_variable_set(ivar, v)
-
7489
next
-
end
-
-
72587
v = opts.__send__(:"option_#{ivar[1..-1]}", v)
-
-
72575
orig_v = instance_variable_get(ivar)
-
-
72575
v = orig_v.merge(v) if orig_v.respond_to?(:merge) && v.respond_to?(:merge)
-
-
72575
opts.instance_variable_set(ivar, v)
-
end
-
-
10552
opts
-
end
-
-
25
def to_hash
-
2696
instance_variables.each_with_object({}) do |ivar, hs|
-
76320
hs[ivar[1..-1].to_sym] = instance_variable_get(ivar)
-
end
-
end
-
-
25
def extend_with_plugin_classes(pl)
-
5882
if defined?(pl::RequestMethods) || defined?(pl::RequestClassMethods)
-
1706
@request_class = @request_class.dup
-
1706
SET_TEMPORARY_NAME[@request_class, pl]
-
1706
@request_class.__send__(:include, pl::RequestMethods) if defined?(pl::RequestMethods)
-
1706
@request_class.extend(pl::RequestClassMethods) if defined?(pl::RequestClassMethods)
-
end
-
5882
if defined?(pl::ResponseMethods) || defined?(pl::ResponseClassMethods)
-
1972
@response_class = @response_class.dup
-
1972
SET_TEMPORARY_NAME[@response_class, pl]
-
1972
@response_class.__send__(:include, pl::ResponseMethods) if defined?(pl::ResponseMethods)
-
1972
@response_class.extend(pl::ResponseClassMethods) if defined?(pl::ResponseClassMethods)
-
end
-
5882
if defined?(pl::HeadersMethods) || defined?(pl::HeadersClassMethods)
-
114
@headers_class = @headers_class.dup
-
114
SET_TEMPORARY_NAME[@headers_class, pl]
-
114
@headers_class.__send__(:include, pl::HeadersMethods) if defined?(pl::HeadersMethods)
-
114
@headers_class.extend(pl::HeadersClassMethods) if defined?(pl::HeadersClassMethods)
-
end
-
5882
if defined?(pl::RequestBodyMethods) || defined?(pl::RequestBodyClassMethods)
-
288
@request_body_class = @request_body_class.dup
-
288
SET_TEMPORARY_NAME[@request_body_class, pl]
-
288
@request_body_class.__send__(:include, pl::RequestBodyMethods) if defined?(pl::RequestBodyMethods)
-
288
@request_body_class.extend(pl::RequestBodyClassMethods) if defined?(pl::RequestBodyClassMethods)
-
end
-
5882
if defined?(pl::ResponseBodyMethods) || defined?(pl::ResponseBodyClassMethods)
-
674
@response_body_class = @response_body_class.dup
-
674
SET_TEMPORARY_NAME[@response_body_class, pl]
-
674
@response_body_class.__send__(:include, pl::ResponseBodyMethods) if defined?(pl::ResponseBodyMethods)
-
674
@response_body_class.extend(pl::ResponseBodyClassMethods) if defined?(pl::ResponseBodyClassMethods)
-
end
-
5882
if defined?(pl::PoolMethods)
-
511
@pool_class = @pool_class.dup
-
511
SET_TEMPORARY_NAME[@pool_class, pl]
-
511
@pool_class.__send__(:include, pl::PoolMethods)
-
end
-
5882
if defined?(pl::ConnectionMethods)
-
2348
@connection_class = @connection_class.dup
-
2348
SET_TEMPORARY_NAME[@connection_class, pl]
-
2348
@connection_class.__send__(:include, pl::ConnectionMethods)
-
end
-
5882
return unless defined?(pl::OptionsMethods)
-
-
2344
@options_class = @options_class.dup
-
2344
@options_class.__send__(:include, pl::OptionsMethods)
-
end
-
-
25
private
-
-
25
def do_initialize(options = {})
-
3442
defaults = DEFAULT_OPTIONS.merge(options)
-
3442
defaults.each do |k, v|
-
107474
next if v.nil?
-
-
97148
option_method_name = :"option_#{k}"
-
97148
raise Error, "unknown option: #{k}" unless respond_to?(option_method_name)
-
-
97142
value = __send__(option_method_name, v)
-
97136
instance_variable_set(:"@#{k}", value)
-
end
-
end
-
-
25
def access_option(obj, k, ivar_map)
-
311171
case obj
-
when Hash
-
23119
obj[ivar_map[k]]
-
else
-
288052
obj.instance_variable_get(k)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Parser
-
25
class Error < Error; end
-
-
25
class HTTP1
-
25
VERSIONS = %w[1.0 1.1].freeze
-
-
25
attr_reader :status_code, :http_version, :headers
-
-
25
def initialize(observer)
-
3549
@observer = observer
-
3549
@state = :idle
-
3549
@buffer = "".b
-
3549
@headers = {}
-
end
-
-
25
def <<(chunk)
-
5853
@buffer << chunk
-
5853
parse
-
end
-
-
25
def reset!
-
7495
@state = :idle
-
7495
@headers = {}
-
7495
@content_length = nil
-
7495
@_has_trailers = nil
-
end
-
-
25
def upgrade?
-
3680
@upgrade
-
end
-
-
25
def upgrade_data
-
24
@buffer
-
end
-
-
25
private
-
-
25
def parse
-
5853
loop do
-
12364
state = @state
-
12364
case @state
-
when :idle
-
3947
parse_headline
-
when :headers, :trailers
-
4015
parse_headers
-
when :data
-
4402
parse_data
-
end
-
9123
return if @buffer.empty? || state == @state
-
end
-
end
-
-
25
def parse_headline
-
3947
idx = @buffer.index("\n")
-
3947
return unless idx
-
-
3947
(m = %r{\AHTTP(?:/(\d+\.\d+))?\s+(\d\d\d)(?:\s+(.*))?}in.match(@buffer)) ||
-
raise(Error, "wrong head line format")
-
3941
version, code, _ = m.captures
-
3941
raise(Error, "unsupported HTTP version (HTTP/#{version})") unless version && VERSIONS.include?(version)
-
-
3935
@http_version = version.split(".").map(&:to_i)
-
3935
@status_code = code.to_i
-
3935
raise(Error, "wrong status code (#{@status_code})") unless (100..599).cover?(@status_code)
-
-
3929
@buffer = @buffer.byteslice((idx + 1)..-1)
-
3929
nextstate(:headers)
-
end
-
-
25
def parse_headers
-
4015
headers = @headers
-
4015
buffer = @buffer
-
-
34612
while (idx = buffer.index("\n"))
-
# @type var line: String
-
30523
line = buffer.byteslice(0..idx)
-
30523
raise Error, "wrong header format" if line.start_with?("\s", "\t")
-
-
30517
line.lstrip!
-
30517
buffer = @buffer = buffer.byteslice((idx + 1)..-1)
-
30517
if line.empty?
-
3929
case @state
-
when :headers
-
3917
prepare_data(headers)
-
3917
@observer.on_headers(headers)
-
3424
return unless @state == :headers
-
-
# state might have been reset
-
# in the :headers callback
-
3370
nextstate(:data)
-
3370
headers.clear
-
when :trailers
-
12
@observer.on_trailers(headers)
-
12
headers.clear
-
12
nextstate(:complete)
-
end
-
3376
return
-
end
-
26588
separator_index = line.index(":")
-
26588
raise Error, "wrong header format" unless separator_index
-
-
# @type var key: String
-
26582
key = line.byteslice(0..(separator_index - 1))
-
-
26582
key.rstrip! # was lstripped previously!
-
# @type var value: String
-
26582
value = line.byteslice((separator_index + 1)..-1)
-
26582
value.strip!
-
26582
raise Error, "wrong header format" if value.nil?
-
-
26582
(headers[key.downcase] ||= []) << value
-
end
-
end
-
-
25
def parse_data
-
4402
if @buffer.respond_to?(:each)
-
153
@buffer.each do |chunk|
-
176
@observer.on_data(chunk)
-
end
-
4249
elsif @content_length
-
# @type var data: String
-
4219
data = @buffer.byteslice(0, @content_length)
-
4219
@buffer = @buffer.byteslice(@content_length..-1) || "".b
-
4219
@content_length -= data.bytesize
-
4219
@observer.on_data(data)
-
4201
data.clear
-
else
-
30
@observer.on_data(@buffer)
-
30
@buffer.clear
-
end
-
4378
return unless no_more_data?
-
-
3256
@buffer = @buffer.to_s
-
3256
if @_has_trailers
-
12
nextstate(:trailers)
-
else
-
3244
nextstate(:complete)
-
end
-
end
-
-
25
def prepare_data(headers)
-
3917
@upgrade = headers.key?("upgrade")
-
-
3917
@_has_trailers = headers.key?("trailer")
-
-
3917
if (tr_encodings = headers["transfer-encoding"])
-
86
tr_encodings.reverse_each do |tr_encoding|
-
86
tr_encoding.split(/ *, */).each do |encoding|
-
86
case encoding
-
when "chunked"
-
86
@buffer = Transcoder::Chunker::Decoder.new(@buffer, @_has_trailers)
-
end
-
end
-
end
-
else
-
3831
@content_length = headers["content-length"][0].to_i if headers.key?("content-length")
-
end
-
end
-
-
25
def no_more_data?
-
4378
if @content_length
-
4201
@content_length <= 0
-
177
elsif @buffer.respond_to?(:finished?)
-
147
@buffer.finished?
-
else
-
30
false
-
end
-
end
-
-
25
def nextstate(state)
-
10567
@state = state
-
10567
case state
-
when :headers
-
3929
@observer.on_start
-
when :complete
-
3256
@observer.on_complete
-
562
reset!
-
562
nextstate(:idle) unless @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds a shim +authorization+ method to the session, which will fill
-
# the HTTP Authorization header, and another, +bearer_auth+, which fill the "Bearer " prefix
-
# in its value.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#auth
-
#
-
6
module Auth
-
6
module InstanceMethods
-
6
def authorization(token)
-
108
with(headers: { "authorization" => token })
-
end
-
-
6
def bearer_auth(token)
-
12
authorization("Bearer #{token}")
-
end
-
end
-
end
-
6
register_plugin :auth, Auth
-
end
-
end
-
# frozen_string_literal: true
-
-
7
require "httpx/base64"
-
-
7
module HTTPX
-
7
module Plugins
-
7
module Authentication
-
7
class Basic
-
7
def initialize(user, password, **)
-
208
@user = user
-
208
@password = password
-
end
-
-
7
def authenticate(*)
-
195
"Basic #{Base64.strict_encode64("#{@user}:#{@password}")}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "time"
-
6
require "securerandom"
-
6
require "digest"
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Authentication
-
6
class Digest
-
6
def initialize(user, password, hashed: false, **)
-
132
@user = user
-
132
@password = password
-
132
@nonce = 0
-
132
@hashed = hashed
-
end
-
-
6
def can_authenticate?(authenticate)
-
120
authenticate && /Digest .*/.match?(authenticate)
-
end
-
-
6
def authenticate(request, authenticate)
-
120
"Digest #{generate_header(request.verb, request.path, authenticate)}"
-
end
-
-
6
private
-
-
6
def generate_header(meth, uri, authenticate)
-
# discard first token, it's Digest
-
120
auth_info = authenticate[/^(\w+) (.*)/, 2]
-
-
120
params = auth_info.split(/ *, */)
-
624
.to_h { |val| val.split("=", 2) }
-
624
.transform_values { |v| v.delete("\"") }
-
120
nonce = params["nonce"]
-
120
nc = next_nonce
-
-
# verify qop
-
120
qop = params["qop"]
-
-
120
if params["algorithm"] =~ /(.*?)(-sess)?$/
-
108
alg = Regexp.last_match(1)
-
108
algorithm = ::Digest.const_get(alg)
-
108
raise DigestError, "unknown algorithm \"#{alg}\"" unless algorithm
-
-
108
sess = Regexp.last_match(2)
-
else
-
12
algorithm = ::Digest::MD5
-
end
-
-
120
if qop || sess
-
120
cnonce = make_cnonce
-
120
nc = format("%<nonce>08x", nonce: nc)
-
end
-
-
120
a1 = if sess
-
[
-
24
(@hashed ? @password : algorithm.hexdigest("#{@user}:#{params["realm"]}:#{@password}")),
-
nonce,
-
cnonce,
-
].join ":"
-
else
-
96
@hashed ? @password : "#{@user}:#{params["realm"]}:#{@password}"
-
end
-
-
120
ha1 = algorithm.hexdigest(a1)
-
120
ha2 = algorithm.hexdigest("#{meth}:#{uri}")
-
120
request_digest = [ha1, nonce]
-
120
request_digest.push(nc, cnonce, qop) if qop
-
120
request_digest << ha2
-
120
request_digest = request_digest.join(":")
-
-
header = [
-
120
%(username="#{@user}"),
-
%(nonce="#{nonce}"),
-
%(uri="#{uri}"),
-
%(response="#{algorithm.hexdigest(request_digest)}"),
-
]
-
120
header << %(realm="#{params["realm"]}") if params.key?("realm")
-
120
header << %(algorithm=#{params["algorithm"]}) if params.key?("algorithm")
-
120
header << %(cnonce="#{cnonce}") if cnonce
-
120
header << %(nc=#{nc})
-
120
header << %(qop=#{qop}) if qop
-
120
header << %(opaque="#{params["opaque"]}") if params.key?("opaque")
-
120
header.join ", "
-
end
-
-
6
def make_cnonce
-
120
::Digest::MD5.hexdigest [
-
Time.now.to_i,
-
Process.pid,
-
SecureRandom.random_number(2**32),
-
].join ":"
-
end
-
-
6
def next_nonce
-
120
@nonce += 1
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
3
require "httpx/base64"
-
3
require "ntlm"
-
-
3
module HTTPX
-
3
module Plugins
-
3
module Authentication
-
3
class Ntlm
-
3
def initialize(user, password, domain: nil)
-
4
@user = user
-
4
@password = password
-
4
@domain = domain
-
end
-
-
3
def can_authenticate?(authenticate)
-
2
authenticate && /NTLM .*/.match?(authenticate)
-
end
-
-
3
def negotiate
-
4
"NTLM #{NTLM.negotiate(domain: @domain).to_base64}"
-
end
-
-
3
def authenticate(_req, www)
-
2
challenge = www[/NTLM (.*)/, 1]
-
-
2
challenge = Base64.decode64(challenge)
-
2
ntlm_challenge = NTLM.authenticate(challenge, @user, @domain, @password).to_base64
-
-
2
"NTLM #{ntlm_challenge}"
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Authentication
-
8
class Socks5
-
8
def initialize(user, password, **)
-
36
@user = user
-
36
@password = password
-
end
-
-
8
def can_authenticate?(*)
-
36
@user && @password
-
end
-
-
8
def authenticate(*)
-
36
[0x01, @user.bytesize, @user, @password.bytesize, @password].pack("CCA*CA*")
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin applies AWS Sigv4 to requests, using the AWS SDK credentials and configuration.
-
#
-
# It requires the "aws-sdk-core" gem.
-
#
-
6
module AwsSdkAuthentication
-
# Mock configuration, to be used only when resolving credentials
-
6
class Configuration
-
6
attr_reader :profile
-
-
6
def initialize(profile)
-
24
@profile = profile
-
end
-
-
6
def respond_to_missing?(*)
-
12
true
-
end
-
-
6
def method_missing(*); end
-
end
-
-
#
-
# encapsulates access to an AWS SDK credentials store.
-
#
-
6
class Credentials
-
6
def initialize(aws_credentials)
-
12
@aws_credentials = aws_credentials
-
end
-
-
6
def username
-
12
@aws_credentials.access_key_id
-
end
-
-
6
def password
-
12
@aws_credentials.secret_access_key
-
end
-
-
6
def security_token
-
12
@aws_credentials.session_token
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(_klass)
-
12
require "aws-sdk-core"
-
end
-
-
6
def configure(klass)
-
12
klass.plugin(:aws_sigv4)
-
end
-
-
6
def extra_options(options)
-
12
options.merge(max_concurrent_requests: 1)
-
end
-
-
6
def credentials(profile)
-
12
mock_configuration = Configuration.new(profile)
-
12
Credentials.new(Aws::CredentialProviderChain.new(mock_configuration).resolve)
-
end
-
-
6
def region(profile)
-
# https://github.com/aws/aws-sdk-ruby/blob/version-3/gems/aws-sdk-core/lib/aws-sdk-core/plugins/regional_endpoint.rb#L62
-
12
keys = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION]
-
12
env_region = ENV.values_at(*keys).compact.first
-
12
env_region = nil if env_region == ""
-
12
cfg_region = Aws.shared_config.region(profile: profile)
-
12
env_region || cfg_region
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :aws_profile :: AWS account profile to retrieve credentials from.
-
6
module OptionsMethods
-
6
def option_aws_profile(value)
-
60
String(value)
-
end
-
end
-
-
6
module InstanceMethods
-
#
-
# aws_authentication
-
# aws_authentication(credentials: Aws::Credentials.new('akid', 'secret'))
-
# aws_authentication()
-
#
-
6
def aws_sdk_authentication(
-
credentials: AwsSdkAuthentication.credentials(@options.aws_profile),
-
region: AwsSdkAuthentication.region(@options.aws_profile),
-
**options
-
)
-
-
12
aws_sigv4_authentication(
-
credentials: credentials,
-
region: region,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
**options
-
)
-
end
-
6
alias_method :aws_auth, :aws_sdk_authentication
-
end
-
end
-
6
register_plugin :aws_sdk_authentication, AwsSdkAuthentication
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds AWS Sigv4 authentication.
-
#
-
# https://docs.aws.amazon.com/IAM/latest/UserGuide/signing-elements.html
-
#
-
# https://gitlab.com/os85/httpx/wikis/AWS-SigV4
-
#
-
6
module AWSSigV4
-
6
Credentials = Struct.new(:username, :password, :security_token)
-
-
# Signs requests using the AWS sigv4 signing.
-
6
class Signer
-
6
def initialize(
-
service:,
-
region:,
-
credentials: nil,
-
username: nil,
-
password: nil,
-
security_token: nil,
-
provider_prefix: "aws",
-
header_provider_field: "amz",
-
unsigned_headers: [],
-
apply_checksum_header: true,
-
algorithm: "SHA256"
-
)
-
114
@credentials = credentials || Credentials.new(username, password, security_token)
-
114
@service = service
-
114
@region = region
-
-
114
@unsigned_headers = Set.new(unsigned_headers.map(&:downcase))
-
114
@unsigned_headers << "authorization"
-
114
@unsigned_headers << "x-amzn-trace-id"
-
114
@unsigned_headers << "expect"
-
-
114
@apply_checksum_header = apply_checksum_header
-
114
@provider_prefix = provider_prefix
-
114
@header_provider_field = header_provider_field
-
-
114
@algorithm = algorithm
-
end
-
-
6
def sign!(request)
-
114
lower_provider_prefix = "#{@provider_prefix}4"
-
114
upper_provider_prefix = lower_provider_prefix.upcase
-
-
114
downcased_algorithm = @algorithm.downcase
-
-
114
datetime = (request.headers["x-#{@header_provider_field}-date"] ||= Time.now.utc.strftime("%Y%m%dT%H%M%SZ"))
-
114
date = datetime[0, 8]
-
-
114
content_hashed = request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] || hexdigest(request.body)
-
-
108
request.headers["x-#{@header_provider_field}-content-#{downcased_algorithm}"] ||= content_hashed if @apply_checksum_header
-
108
request.headers["x-#{@header_provider_field}-security-token"] ||= @credentials.security_token if @credentials.security_token
-
-
108
signature_headers = request.headers.each.reject do |k, _|
-
738
@unsigned_headers.include?(k)
-
end
-
# aws sigv4 needs to declare the host, regardless of protocol version
-
108
signature_headers << ["host", request.authority] unless request.headers.key?("host")
-
108
signature_headers.sort_by!(&:first)
-
-
108
signed_headers = signature_headers.map(&:first).join(";")
-
-
108
canonical_headers = signature_headers.map do |k, v|
-
# eliminate whitespace between value fields, unless it's a quoted value
-
726
"#{k}:#{v.start_with?("\"") && v.end_with?("\"") ? v : v.gsub(/\s+/, " ").strip}\n"
-
end.join
-
-
# canonical request
-
108
creq = "#{request.verb}" \
-
"\n#{request.canonical_path}" \
-
"\n#{request.canonical_query}" \
-
"\n#{canonical_headers}" \
-
"\n#{signed_headers}" \
-
"\n#{content_hashed}"
-
-
108
credential_scope = "#{date}" \
-
"/#{@region}" \
-
"/#{@service}" \
-
"/#{lower_provider_prefix}_request"
-
-
108
algo_line = "#{upper_provider_prefix}-HMAC-#{@algorithm}"
-
# string to sign
-
108
sts = "#{algo_line}" \
-
"\n#{datetime}" \
-
"\n#{credential_scope}" \
-
"\n#{OpenSSL::Digest.new(@algorithm).hexdigest(creq)}"
-
-
# signature
-
108
k_date = hmac("#{upper_provider_prefix}#{@credentials.password}", date)
-
108
k_region = hmac(k_date, @region)
-
108
k_service = hmac(k_region, @service)
-
108
k_credentials = hmac(k_service, "#{lower_provider_prefix}_request")
-
108
sig = hexhmac(k_credentials, sts)
-
-
108
credential = "#{@credentials.username}/#{credential_scope}"
-
# apply signature
-
108
request.headers["authorization"] =
-
"#{algo_line} " \
-
"Credential=#{credential}, " \
-
"SignedHeaders=#{signed_headers}, " \
-
"Signature=#{sig}"
-
end
-
-
6
private
-
-
6
def hexdigest(value)
-
108
digest = OpenSSL::Digest.new(@algorithm)
-
-
108
if value.respond_to?(:read)
-
24
if value.respond_to?(:to_path)
-
# files, pathnames
-
6
digest.file(value.to_path).hexdigest
-
else
-
# gzipped request bodies
-
18
raise Error, "request body must be rewindable" unless value.respond_to?(:rewind)
-
-
18
buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
begin
-
18
IO.copy_stream(value, buffer)
-
18
buffer.flush
-
-
18
digest.file(buffer.to_path).hexdigest
-
ensure
-
18
value.rewind
-
18
buffer.close
-
18
buffer.unlink
-
end
-
end
-
else
-
# error on endless generators
-
84
raise Error, "hexdigest for endless enumerators is not supported" if value.unbounded_body?
-
-
78
mb_buffer = value.each.with_object("".b) do |chunk, b|
-
42
b << chunk
-
42
break if b.bytesize >= 1024 * 1024
-
end
-
-
78
digest.hexdigest(mb_buffer)
-
end
-
end
-
-
6
def hmac(key, value)
-
432
OpenSSL::HMAC.digest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
-
6
def hexhmac(key, value)
-
108
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(@algorithm), key, value)
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(*)
-
114
require "set"
-
114
require "digest/sha2"
-
114
require "cgi/escape"
-
end
-
-
6
def configure(klass)
-
114
klass.plugin(:expect)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :sigv4_signer :: instance of HTTPX::Plugins::AWSSigV4 used to sign requests.
-
6
module OptionsMethods
-
6
def option_sigv4_signer(value)
-
240
value.is_a?(Signer) ? value : Signer.new(value)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def aws_sigv4_authentication(**options)
-
114
with(sigv4_signer: Signer.new(**options))
-
end
-
-
6
def build_request(*)
-
114
request = super
-
-
114
return request if request.headers.key?("authorization")
-
-
114
signer = request.options.sigv4_signer
-
-
114
return request unless signer
-
-
114
signer.sign!(request)
-
-
108
request
-
end
-
end
-
-
6
module RequestMethods
-
6
def canonical_path
-
108
path = uri.path.dup
-
108
path << "/" if path.empty?
-
132
path.gsub(%r{[^/]+}) { |part| CGI.escape(part.encode("UTF-8")).gsub("+", "%20").gsub("%7E", "~") }
-
end
-
-
6
def canonical_query
-
132
params = query.split("&")
-
# params = params.map { |p| p.match(/=/) ? p : p + '=' }
-
# From: https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html#create-canonical-request
-
# Sort the parameter names by character code point in ascending order.
-
# Parameters with duplicate names should be sorted by value.
-
#
-
# Default sort <=> in JRuby will swap members
-
# occasionally when <=> is 0 (considered still sorted), but this
-
# causes our normalized query string to not match the sent querystring.
-
# When names match, we then sort by their values. When values also
-
# match then we sort by their original order
-
132
params.each.with_index.sort do |a, b|
-
48
a, a_offset = a
-
48
b, b_offset = b
-
48
a_name, a_value = a.split("=", 2)
-
48
b_name, b_value = b.split("=", 2)
-
48
if a_name == b_name
-
24
if a_value == b_value
-
12
a_offset <=> b_offset
-
else
-
12
a_value <=> b_value
-
end
-
else
-
24
a_name <=> b_name
-
end
-
end.map(&:first).join("&")
-
end
-
end
-
end
-
6
register_plugin :aws_sigv4, AWSSigV4
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds helper methods to implement HTTP Basic Auth (https://datatracker.ietf.org/doc/html/rfc7617)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#basic-auth
-
#
-
6
module BasicAuth
-
6
class << self
-
6
def load_dependencies(_klass)
-
84
require_relative "auth/basic"
-
end
-
-
6
def configure(klass)
-
84
klass.plugin(:auth)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def basic_auth(user, password)
-
96
authorization(Authentication::Basic.new(user, password).authenticate)
-
end
-
end
-
end
-
6
register_plugin :basic_auth, BasicAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Brotli
-
6
class Deflater < Transcoder::Deflater
-
6
def deflate(chunk)
-
24
return unless chunk
-
-
12
::Brotli.deflate(chunk)
-
end
-
end
-
-
6
module RequestBodyClassMethods
-
6
def initialize_deflater_body(body, encoding)
-
24
return Brotli.encode(body) if encoding == "br"
-
-
12
super
-
end
-
end
-
-
6
module ResponseBodyClassMethods
-
6
def initialize_inflater_by_encoding(encoding, response, **kwargs)
-
24
return Brotli.decode(response, **kwargs) if encoding == "br"
-
-
12
super
-
end
-
end
-
-
6
module_function
-
-
6
def load_dependencies(*)
-
24
require "brotli"
-
end
-
-
6
def self.extra_options(options)
-
24
options.merge(supported_compression_formats: %w[br] + options.supported_compression_formats)
-
end
-
-
6
def encode(body)
-
12
Deflater.new(body)
-
end
-
-
6
def decode(_response, **)
-
12
::Brotli.method(:inflate)
-
end
-
end
-
6
register_plugin :brotli, Brotli
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Plugins
-
#
-
# This plugin adds suppoort for callbacks around the request/response lifecycle.
-
#
-
# https://gitlab.com/os85/httpx/-/wikis/Events
-
#
-
25
module Callbacks
-
25
CALLBACKS = %i[
-
connection_opened connection_closed
-
request_error
-
request_started request_body_chunk request_completed
-
response_started response_body_chunk response_completed
-
].freeze
-
-
# connection closed user-space errors happen after errors can be surfaced to requests,
-
# so they need to pierce through the scheduler, which is only possible by simulating an
-
# interrupt.
-
25
class CallbackError < Exception; end # rubocop:disable Lint/InheritException
-
-
25
module InstanceMethods
-
25
include HTTPX::Callbacks
-
-
25
CALLBACKS.each do |meth|
-
225
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
def on_#{meth}(&blk) # def on_connection_opened(&blk)
-
on(:#{meth}, &blk) # on(:connection_opened, &blk)
-
self # self
-
end # end
-
MOD
-
end
-
-
25
private
-
-
25
def branch(options, &blk)
-
12
super(options).tap do |sess|
-
12
CALLBACKS.each do |cb|
-
108
next unless callbacks_for?(cb)
-
-
12
sess.callbacks(cb).concat(callbacks(cb))
-
end
-
12
sess.wrap(&blk) if blk
-
end
-
end
-
-
25
def do_init_connection(connection, selector)
-
169
super
-
169
connection.on(:open) do
-
147
next unless connection.current_session == self
-
-
147
emit_or_callback_error(:connection_opened, connection.origin, connection.io.socket)
-
end
-
169
connection.on(:close) do
-
159
next unless connection.current_session == self
-
-
159
emit_or_callback_error(:connection_closed, connection.origin) if connection.used?
-
end
-
-
169
connection
-
end
-
-
25
def set_request_callbacks(request)
-
171
super
-
-
171
request.on(:headers) do
-
135
emit_or_callback_error(:request_started, request)
-
end
-
171
request.on(:body_chunk) do |chunk|
-
12
emit_or_callback_error(:request_body_chunk, request, chunk)
-
end
-
171
request.on(:done) do
-
123
emit_or_callback_error(:request_completed, request)
-
end
-
-
171
request.on(:response_started) do |res|
-
135
if res.is_a?(Response)
-
111
emit_or_callback_error(:response_started, request, res)
-
99
res.on(:chunk_received) do |chunk|
-
120
emit_or_callback_error(:response_body_chunk, request, res, chunk)
-
end
-
else
-
24
emit_or_callback_error(:request_error, request, res.error)
-
end
-
end
-
171
request.on(:response) do |res|
-
99
emit_or_callback_error(:response_completed, request, res)
-
end
-
end
-
-
25
def emit_or_callback_error(*args)
-
918
emit(*args)
-
rescue StandardError => e
-
96
ex = CallbackError.new(e.message)
-
96
ex.set_backtrace(e.backtrace)
-
96
raise ex
-
end
-
-
25
def receive_requests(*)
-
171
super
-
rescue CallbackError => e
-
90
raise e.cause
-
end
-
-
25
def close(*)
-
169
super
-
rescue CallbackError => e
-
6
raise e.cause
-
end
-
end
-
end
-
25
register_plugin :callbacks, Callbacks
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements a circuit breaker around connection errors.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Circuit-Breaker
-
#
-
6
module CircuitBreaker
-
6
using URIExtensions
-
-
6
def self.load_dependencies(*)
-
42
require_relative "circuit_breaker/circuit"
-
42
require_relative "circuit_breaker/circuit_store"
-
end
-
-
6
def self.extra_options(options)
-
42
options.merge(
-
circuit_breaker_max_attempts: 3,
-
circuit_breaker_reset_attempts_in: 60,
-
circuit_breaker_break_in: 60,
-
circuit_breaker_half_open_drip_rate: 1
-
)
-
end
-
-
6
module InstanceMethods
-
6
include HTTPX::Callbacks
-
-
6
def initialize(*)
-
42
super
-
42
@circuit_store = CircuitStore.new(@options)
-
end
-
-
6
%i[circuit_open].each do |meth|
-
6
class_eval(<<-MOD, __FILE__, __LINE__ + 1)
-
def on_#{meth}(&blk) # def on_circuit_open(&blk)
-
on(:#{meth}, &blk) # on(:circuit_open, &blk)
-
self # self
-
end # end
-
MOD
-
end
-
-
6
private
-
-
6
def send_requests(*requests)
-
# @type var short_circuit_responses: Array[response]
-
168
short_circuit_responses = []
-
-
# run all requests through the circuit breaker, see if the circuit is
-
# open for any of them.
-
168
real_requests = requests.each_with_index.with_object([]) do |(req, idx), real_reqs|
-
168
short_circuit_response = @circuit_store.try_respond(req)
-
168
if short_circuit_response.nil?
-
132
real_reqs << req
-
132
next
-
end
-
36
short_circuit_responses[idx] = short_circuit_response
-
end
-
-
# run requests for the remainder
-
168
unless real_requests.empty?
-
132
responses = super(*real_requests)
-
-
132
real_requests.each_with_index do |request, idx|
-
132
short_circuit_responses[requests.index(request)] = responses[idx]
-
end
-
end
-
-
168
short_circuit_responses
-
end
-
-
6
def set_request_callbacks(request)
-
168
super
-
168
request.on(:response) do |response|
-
132
emit(:circuit_open, request) if try_circuit_open(request, response)
-
end
-
end
-
-
6
def try_circuit_open(request, response)
-
132
if response.is_a?(ErrorResponse)
-
96
case response.error
-
when RequestTimeoutError
-
60
@circuit_store.try_open(request.uri, response)
-
else
-
36
@circuit_store.try_open(request.origin, response)
-
end
-
36
elsif (break_on = request.options.circuit_breaker_break_on) && break_on.call(response)
-
12
@circuit_store.try_open(request.uri, response)
-
else
-
24
@circuit_store.try_close(request.uri)
-
4
nil
-
end
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :circuit_breaker_max_attempts :: the number of attempts the circuit allows, before it is opened (defaults to <tt>3</tt>).
-
# :circuit_breaker_reset_attempts_in :: the time a circuit stays open at most, before it resets (defaults to <tt>60</tt>).
-
# :circuit_breaker_break_on :: callable defining an alternative rule for a response to break
-
# (i.e. <tt>->(res) { res.status == 429 } </tt>)
-
# :circuit_breaker_break_in :: the time that must elapse before an open circuit can transit to the half-open state
-
# (defaults to <tt><60</tt>).
-
# :circuit_breaker_half_open_drip_rate :: the rate of requests a circuit allows to be performed when in an half-open state
-
# (defaults to <tt>1</tt>).
-
6
module OptionsMethods
-
6
def option_circuit_breaker_max_attempts(value)
-
84
attempts = Integer(value)
-
84
raise TypeError, ":circuit_breaker_max_attempts must be positive" unless attempts.positive?
-
-
84
attempts
-
end
-
-
6
def option_circuit_breaker_reset_attempts_in(value)
-
48
timeout = Float(value)
-
48
raise TypeError, ":circuit_breaker_reset_attempts_in must be positive" unless timeout.positive?
-
-
48
timeout
-
end
-
-
6
def option_circuit_breaker_break_in(value)
-
66
timeout = Float(value)
-
66
raise TypeError, ":circuit_breaker_break_in must be positive" unless timeout.positive?
-
-
66
timeout
-
end
-
-
6
def option_circuit_breaker_half_open_drip_rate(value)
-
66
ratio = Float(value)
-
66
raise TypeError, ":circuit_breaker_half_open_drip_rate must be a number between 0 and 1" unless (0..1).cover?(ratio)
-
-
66
ratio
-
end
-
-
6
def option_circuit_breaker_break_on(value)
-
12
raise TypeError, ":circuit_breaker_break_on must be called with the response" unless value.respond_to?(:call)
-
-
12
value
-
end
-
end
-
end
-
6
register_plugin :circuit_breaker, CircuitBreaker
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::CircuitBreaker
-
#
-
# A circuit is assigned to a given absoolute url or origin.
-
#
-
# It sets +max_attempts+, the number of attempts the circuit allows, before it is opened.
-
# It sets +reset_attempts_in+, the time a circuit stays open at most, before it resets.
-
# It sets +break_in+, the time that must elapse before an open circuit can transit to the half-open state.
-
# It sets +circuit_breaker_half_open_drip_rate+, the rate of requests a circuit allows to be performed when in an half-open state.
-
#
-
6
class Circuit
-
6
def initialize(max_attempts, reset_attempts_in, break_in, circuit_breaker_half_open_drip_rate)
-
42
@max_attempts = max_attempts
-
42
@reset_attempts_in = reset_attempts_in
-
42
@break_in = break_in
-
42
@circuit_breaker_half_open_drip_rate = circuit_breaker_half_open_drip_rate
-
42
@attempts = 0
-
-
42
total_real_attempts = @max_attempts * @circuit_breaker_half_open_drip_rate
-
42
@drip_factor = (@max_attempts / total_real_attempts).round
-
42
@state = :closed
-
end
-
-
6
def respond
-
168
try_close
-
-
168
case @state
-
when :closed
-
17
nil
-
when :half_open
-
42
@attempts += 1
-
-
# do real requests while drip rate valid
-
42
if (@real_attempts % @drip_factor).zero?
-
30
@real_attempts += 1
-
30
return
-
end
-
-
12
@response
-
when :open
-
-
24
@response
-
end
-
end
-
-
6
def try_open(response)
-
108
case @state
-
when :closed
-
90
now = Utils.now
-
-
90
if @attempts.positive?
-
# reset if error happened long ago
-
36
@attempts = 0 if now - @attempted_at > @reset_attempts_in
-
else
-
54
@attempted_at = now
-
end
-
-
90
@attempts += 1
-
-
90
return unless @attempts >= @max_attempts
-
-
48
@state = :open
-
48
@opened_at = now
-
48
@response = response
-
when :half_open
-
# open immediately
-
-
18
@state = :open
-
18
@attempted_at = @opened_at = Utils.now
-
18
@response = response
-
end
-
end
-
-
6
def try_close
-
192
case @state
-
when :closed
-
17
nil
-
when :half_open
-
-
# do not close circuit unless attempts exhausted
-
36
return unless @attempts >= @max_attempts
-
-
# reset!
-
12
@attempts = 0
-
12
@opened_at = @attempted_at = @response = nil
-
12
@state = :closed
-
-
when :open
-
54
if Utils.elapsed_time(@opened_at) > @break_in
-
30
@state = :half_open
-
30
@attempts = 0
-
30
@real_attempts = 0
-
end
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX::Plugins::CircuitBreaker
-
6
using HTTPX::URIExtensions
-
-
6
class CircuitStore
-
6
def initialize(options)
-
42
@circuits = Hash.new do |h, k|
-
42
h[k] = Circuit.new(
-
options.circuit_breaker_max_attempts,
-
options.circuit_breaker_reset_attempts_in,
-
options.circuit_breaker_break_in,
-
options.circuit_breaker_half_open_drip_rate
-
)
-
end
-
42
@circuits_mutex = Thread::Mutex.new
-
end
-
-
6
def try_open(uri, response)
-
216
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(uri) }
-
-
108
circuit.try_open(response)
-
end
-
-
6
def try_close(uri)
-
24
circuit = @circuits_mutex.synchronize do
-
24
return unless @circuits.key?(uri.origin) || @circuits.key?(uri.to_s)
-
-
24
get_circuit_for_uri(uri)
-
end
-
-
24
circuit.try_close
-
end
-
-
# if circuit is open, it'll respond with the stored response.
-
# if not, nil.
-
6
def try_respond(request)
-
336
circuit = @circuits_mutex.synchronize { get_circuit_for_uri(request.uri) }
-
-
168
circuit.respond
-
end
-
-
6
private
-
-
6
def get_circuit_for_uri(uri)
-
300
if uri.respond_to?(:origin) && @circuits.key?(uri.origin)
-
216
@circuits[uri.origin]
-
else
-
84
@circuits[uri.to_s]
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds `Content-Digest` headers to requests
-
# and can validate these headers on responses
-
#
-
# https://datatracker.ietf.org/doc/html/rfc9530
-
#
-
6
module ContentDigest
-
6
class Error < HTTPX::Error; end
-
-
# Error raised on response "content-digest" header validation.
-
6
class ValidationError < Error
-
6
attr_reader :response
-
-
6
def initialize(message, response)
-
36
super(message)
-
36
@response = response
-
end
-
end
-
-
6
class MissingContentDigestError < ValidationError; end
-
6
class InvalidContentDigestError < ValidationError; end
-
-
SUPPORTED_ALGORITHMS = {
-
6
"sha-256" => OpenSSL::Digest::SHA256,
-
"sha-512" => OpenSSL::Digest::SHA512,
-
}.freeze
-
-
6
class << self
-
6
def extra_options(options)
-
156
options.merge(encode_content_digest: true, validate_content_digest: false, content_digest_algorithm: "sha-256")
-
end
-
end
-
-
# add support for the following options:
-
#
-
# :content_digest_algorithm :: the digest algorithm to use. Currently supports `sha-256` and `sha-512`. (defaults to `sha-256`)
-
# :encode_content_digest :: whether a <tt>Content-Digest</tt> header should be computed for the request;
-
# can also be a callable object (i.e. <tt>->(req) { ... }</tt>, defaults to <tt>true</tt>)
-
# :validate_content_digest :: whether a <tt>Content-Digest</tt> header in the response should be validated;
-
# can also be a callable object (i.e. <tt>->(res) { ... }</tt>, defaults to <tt>false</tt>)
-
6
module OptionsMethods
-
6
def option_content_digest_algorithm(value)
-
162
raise TypeError, ":content_digest_algorithm must be one of 'sha-256', 'sha-512'" unless SUPPORTED_ALGORITHMS.key?(value)
-
-
162
value
-
end
-
-
6
def option_encode_content_digest(value)
-
156
value
-
end
-
-
6
def option_validate_content_digest(value)
-
108
value
-
end
-
end
-
-
6
module ResponseBodyMethods
-
6
attr_reader :content_digest_buffer
-
-
6
def initialize(response, options)
-
132
super
-
-
132
return unless response.headers.key?("content-digest")
-
-
96
should_validate = options.validate_content_digest
-
96
should_validate = should_validate.call(response) if should_validate.respond_to?(:call)
-
-
96
return unless should_validate
-
-
84
@content_digest_buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
end
-
-
6
def write(chunk)
-
216
@content_digest_buffer.write(chunk) if @content_digest_buffer
-
216
super
-
end
-
-
6
def close
-
84
if @content_digest_buffer
-
84
@content_digest_buffer.close
-
84
@content_digest_buffer = nil
-
end
-
84
super
-
end
-
end
-
-
6
module InstanceMethods
-
6
def build_request(*)
-
168
request = super
-
-
168
return request if request.empty?
-
-
36
return request if request.headers.key?("content-digest")
-
-
36
perform_encoding = @options.encode_content_digest
-
36
perform_encoding = perform_encoding.call(request) if perform_encoding.respond_to?(:call)
-
-
36
return request unless perform_encoding
-
-
30
digest = base64digest(request.body)
-
30
request.headers.add("content-digest", "#{@options.content_digest_algorithm}=:#{digest}:")
-
-
30
request
-
end
-
-
6
private
-
-
6
def fetch_response(request, _, _)
-
428
response = super
-
428
return response unless response.is_a?(Response)
-
-
132
perform_validation = @options.validate_content_digest
-
132
perform_validation = perform_validation.call(response) if perform_validation.respond_to?(:call)
-
-
132
validate_content_digest(response) if perform_validation
-
-
96
response
-
rescue ValidationError => e
-
36
ErrorResponse.new(request, e)
-
end
-
-
6
def validate_content_digest(response)
-
96
content_digest_header = response.headers["content-digest"]
-
-
96
raise MissingContentDigestError.new("response is missing a `content-digest` header", response) unless content_digest_header
-
-
84
digests = extract_content_digests(content_digest_header)
-
-
84
included_algorithms = SUPPORTED_ALGORITHMS.keys & digests.keys
-
-
84
raise MissingContentDigestError.new("unsupported algorithms: #{digests.keys.join(", ")}", response) if included_algorithms.empty?
-
-
84
content_buffer = response.body.content_digest_buffer
-
-
84
included_algorithms.each do |algorithm|
-
84
digest = SUPPORTED_ALGORITHMS.fetch(algorithm).new
-
84
digest_received = digests[algorithm]
-
digest_computed =
-
84
if content_buffer.respond_to?(:to_path)
-
12
content_buffer.flush
-
12
digest.file(content_buffer.to_path).base64digest
-
else
-
72
digest.base64digest(content_buffer.to_s)
-
end
-
-
raise InvalidContentDigestError.new("#{algorithm} digest does not match content",
-
84
response) unless digest_received == digest_computed
-
end
-
end
-
-
6
def extract_content_digests(header)
-
84
header.split(",").to_h do |entry|
-
96
algorithm, digest = entry.split("=", 2)
-
96
raise Error, "#{entry} is an invalid digest format" unless algorithm && digest
-
-
96
[algorithm, digest.byteslice(1..-2)]
-
end
-
end
-
-
6
def base64digest(body)
-
30
digest = SUPPORTED_ALGORITHMS.fetch(@options.content_digest_algorithm).new
-
-
30
if body.respond_to?(:read)
-
24
if body.respond_to?(:to_path)
-
6
digest.file(body.to_path).base64digest
-
else
-
18
raise ContentDigestError, "request body must be rewindable" unless body.respond_to?(:rewind)
-
-
18
buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
begin
-
18
IO.copy_stream(body, buffer)
-
18
buffer.flush
-
-
18
digest.file(buffer.to_path).base64digest
-
ensure
-
18
body.rewind
-
18
buffer.close
-
18
buffer.unlink
-
end
-
end
-
else
-
6
raise ContentDigestError, "base64digest for endless enumerators is not supported" if body.unbounded_body?
-
-
6
buffer = "".b
-
12
body.each { |chunk| buffer << chunk }
-
-
6
digest.base64digest(buffer)
-
end
-
end
-
end
-
end
-
6
register_plugin :content_digest, ContentDigest
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "forwardable"
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements a persistent cookie jar for the duration of a session.
-
#
-
# It also adds a *#cookies* helper, so that you can pre-fill the cookies of a session.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Cookies
-
#
-
6
module Cookies
-
6
def self.load_dependencies(*)
-
108
require "httpx/plugins/cookies/jar"
-
108
require "httpx/plugins/cookies/cookie"
-
108
require "httpx/plugins/cookies/set_cookie_parser"
-
end
-
-
6
module InstanceMethods
-
6
extend Forwardable
-
-
6
def_delegator :@options, :cookies
-
-
6
def initialize(options = {}, &blk)
-
216
super({ cookies: Jar.new }.merge(options), &blk)
-
end
-
-
6
def wrap
-
12
return super unless block_given?
-
-
12
super do |session|
-
12
old_cookies_jar = @options.cookies.dup
-
begin
-
12
yield session
-
ensure
-
12
@options = @options.merge(cookies: old_cookies_jar)
-
end
-
end
-
end
-
-
6
def build_request(*)
-
240
request = super
-
240
request.headers.set_cookie(request.options.cookies[request.uri])
-
240
request
-
end
-
-
6
private
-
-
6
def set_request_callbacks(request)
-
240
super
-
240
request.on(:response) do |response|
-
240
next unless response && response.respond_to?(:headers) && (set_cookie = response.headers["set-cookie"])
-
-
48
log { "cookies: set-cookie is over #{Cookie::MAX_LENGTH}" } if set_cookie.bytesize > Cookie::MAX_LENGTH
-
-
48
@options.cookies.parse(set_cookie)
-
end
-
end
-
end
-
-
6
module HeadersMethods
-
6
def set_cookie(cookies)
-
240
return if cookies.empty?
-
-
204
header_value = cookies.sort.join("; ")
-
-
204
add("cookie", header_value)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :cookies :: cookie jar for the session (can be a Hash, an Array, an instance of HTTPX::Plugins::Cookies::CookieJar)
-
6
module OptionsMethods
-
6
def option_headers(*)
-
240
value = super
-
-
240
merge_cookie_in_jar(value.delete("cookie"), @cookies) if defined?(@cookies) && value.key?("cookie")
-
-
240
value
-
end
-
-
6
def option_cookies(value)
-
360
jar = value.is_a?(Jar) ? value : Jar.new(value)
-
-
360
merge_cookie_in_jar(@headers.delete("cookie"), jar) if defined?(@headers) && @headers.key?("cookie")
-
-
360
jar
-
end
-
-
6
private
-
-
6
def merge_cookie_in_jar(cookies, jar)
-
12
cookies.each do |ck|
-
12
ck.split(/ *; */).each do |cookie|
-
24
name, value = cookie.split("=", 2)
-
24
jar.add(Cookie.new(name, value))
-
end
-
end
-
end
-
end
-
end
-
6
register_plugin :cookies, Cookies
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
# The HTTP Cookie.
-
#
-
# Contains the single cookie info: name, value and attributes.
-
6
class Cookie
-
6
include Comparable
-
# Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at
-
# least)
-
6
MAX_LENGTH = 4096
-
-
6
attr_reader :domain, :path, :name, :value, :created_at
-
-
6
def path=(path)
-
138
path = String(path)
-
138
@path = path.start_with?("/") ? path : "/"
-
end
-
-
# See #domain.
-
6
def domain=(domain)
-
30
domain = String(domain)
-
-
30
if domain.start_with?(".")
-
12
@for_domain = true
-
12
domain = domain[1..-1]
-
end
-
-
30
return if domain.empty?
-
-
30
@domain_name = DomainName.new(domain)
-
# RFC 6265 5.3 5.
-
30
@for_domain = false if @domain_name.domain.nil? # a public suffix or IP address
-
-
30
@domain = @domain_name.hostname
-
end
-
-
# Compares the cookie with another. When there are many cookies with
-
# the same name for a URL, the value of the smallest must be used.
-
6
def <=>(other)
-
# RFC 6265 5.4
-
# Precedence: 1. longer path 2. older creation
-
506
(@name <=> other.name).nonzero? ||
-
42
(other.path.length <=> @path.length).nonzero? ||
-
24
(@created_at <=> other.created_at).nonzero? || 0
-
end
-
-
6
class << self
-
6
def new(cookie, *args)
-
378
return cookie if cookie.is_a?(self)
-
-
378
super
-
end
-
-
# Tests if +target_path+ is under +base_path+ as described in RFC
-
# 6265 5.1.4. +base_path+ must be an absolute path.
-
# +target_path+ may be empty, in which case it is treated as the
-
# root path.
-
#
-
# e.g.
-
#
-
# path_match?('/admin/', '/admin/index') == true
-
# path_match?('/admin/', '/Admin/index') == false
-
# path_match?('/admin/', '/admin/') == true
-
# path_match?('/admin/', '/admin') == false
-
#
-
# path_match?('/admin', '/admin') == true
-
# path_match?('/admin', '/Admin') == false
-
# path_match?('/admin', '/admins') == false
-
# path_match?('/admin', '/admin/') == true
-
# path_match?('/admin', '/admin/index') == true
-
6
def path_match?(base_path, target_path)
-
1014
base_path.start_with?("/") || (return false)
-
# RFC 6265 5.1.4
-
1014
bsize = base_path.size
-
1014
tsize = target_path.size
-
1014
return bsize == 1 if tsize.zero? # treat empty target_path as "/"
-
1014
return false unless target_path.start_with?(base_path)
-
1008
return true if bsize == tsize || base_path.end_with?("/")
-
-
12
target_path[bsize] == "/"
-
end
-
end
-
-
6
def initialize(arg, *attrs)
-
378
@created_at = Time.now
-
-
378
if attrs.empty?
-
18
attr_hash = Hash.try_convert(arg)
-
else
-
360
@name = arg
-
360
@value, attr_hash = attrs
-
360
attr_hash = Hash.try_convert(attr_hash)
-
end
-
-
attr_hash.each do |key, val|
-
234
key = key.downcase.tr("-", "_").to_sym unless key.is_a?(Symbol)
-
-
234
case key
-
when :domain, :path
-
168
__send__(:"#{key}=", val)
-
else
-
66
instance_variable_set(:"@#{key}", val)
-
end
-
378
end if attr_hash
-
-
378
@path ||= "/"
-
378
raise ArgumentError, "name must be specified" if @name.nil?
-
-
378
@name = @name.to_s
-
end
-
-
6
def expires
-
570
@expires || (@created_at && @max_age ? @created_at + @max_age : nil)
-
end
-
-
6
def expired?(time = Time.now)
-
546
return false unless expires
-
-
24
expires <= time
-
end
-
-
# Returns a string for use in the Cookie header, i.e. `name=value`
-
# or `name="value"`.
-
6
def cookie_value
-
414
"#{@name}=#{Scanner.quote(@value.to_s)}"
-
end
-
6
alias_method :to_s, :cookie_value
-
-
# Tests if it is OK to send this cookie to a given `uri`. A
-
# RuntimeError is raised if the cookie's domain is unknown.
-
6
def valid_for_uri?(uri)
-
534
uri = URI(uri)
-
# RFC 6265 5.4
-
-
534
return false if @secure && uri.scheme != "https"
-
-
528
acceptable_from_uri?(uri) && Cookie.path_match?(@path, uri.path)
-
end
-
-
6
private
-
-
# Tests if it is OK to accept this cookie if it is sent from a given
-
# URI/URL, `uri`.
-
6
def acceptable_from_uri?(uri)
-
552
uri = URI(uri)
-
-
552
host = DomainName.new(uri.host)
-
-
# RFC 6265 5.3
-
552
if host.hostname == @domain
-
12
true
-
540
elsif @for_domain # !host-only-flag
-
24
host.cookie_domain?(@domain_name)
-
else
-
516
@domain.nil?
-
end
-
end
-
-
6
module Scanner
-
6
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
6
module_function
-
-
6
def quote(s)
-
414
return s unless s.match(RE_BAD_CHAR)
-
-
6
"\"#{s.gsub(/([\\"])/, "\\\\\\1")}\""
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
# The Cookie Jar
-
#
-
# It holds a bunch of cookies.
-
6
class Jar
-
6
using URIExtensions
-
-
6
include Enumerable
-
-
6
def initialize_dup(orig)
-
162
super
-
162
@cookies = orig.instance_variable_get(:@cookies).dup
-
end
-
-
6
def initialize(cookies = nil)
-
402
@cookies = []
-
-
100
cookies.each do |elem|
-
132
cookie = case elem
-
when Cookie
-
12
elem
-
when Array
-
108
Cookie.new(*elem)
-
else
-
12
Cookie.new(elem)
-
end
-
-
132
@cookies << cookie
-
402
end if cookies
-
end
-
-
6
def parse(set_cookie)
-
108
SetCookieParser.call(set_cookie) do |name, value, attrs|
-
156
add(Cookie.new(name, value, attrs))
-
end
-
end
-
-
6
def add(cookie, path = nil)
-
342
c = cookie.dup
-
-
342
c.path = path if path && c.path == "/"
-
-
# If the user agent receives a new cookie with the same cookie-name, domain-value, and path-value
-
# as a cookie that it has already stored, the existing cookie is evicted and replaced with the new cookie.
-
648
@cookies.delete_if { |ck| ck.name == c.name && ck.domain == c.domain && ck.path == c.path }
-
-
342
@cookies << c
-
end
-
-
6
def [](uri)
-
354
each(uri).sort
-
end
-
-
6
def each(uri = nil, &blk)
-
888
return enum_for(__method__, uri) unless blk
-
-
510
return @cookies.each(&blk) unless uri
-
-
354
now = Time.now
-
354
tpath = uri.path
-
-
354
@cookies.delete_if do |cookie|
-
546
if cookie.expired?(now)
-
12
true
-
else
-
534
yield cookie if cookie.valid_for_uri?(uri) && Cookie.path_match?(cookie.path, tpath)
-
534
false
-
end
-
end
-
end
-
-
6
def merge(other)
-
150
cookies_dup = dup
-
-
150
other.each do |elem|
-
162
cookie = case elem
-
when Cookie
-
150
elem
-
when Array
-
6
Cookie.new(*elem)
-
else
-
6
Cookie.new(elem)
-
end
-
-
162
cookies_dup.add(cookie)
-
end
-
-
150
cookies_dup
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "strscan"
-
6
require "time"
-
-
6
module HTTPX
-
6
module Plugins::Cookies
-
6
module SetCookieParser
-
# Whitespace.
-
6
RE_WSP = /[ \t]+/.freeze
-
-
# A pattern that matches a cookie name or attribute name which may
-
# be empty, capturing trailing whitespace.
-
6
RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/.freeze
-
-
6
RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/.freeze
-
-
# A pattern that matches the comma in a (typically date) value.
-
6
RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/.freeze
-
-
6
module_function
-
-
6
def scan_dquoted(scanner)
-
12
s = +""
-
-
12
until scanner.eos?
-
48
break if scanner.skip(/"/)
-
-
36
if scanner.skip(/\\/)
-
12
s << scanner.getch
-
24
elsif scanner.scan(/[^"\\]+/)
-
24
s << scanner.matched
-
end
-
end
-
-
12
s
-
end
-
-
6
def scan_value(scanner, comma_as_separator = false)
-
330
value = +""
-
-
330
until scanner.eos?
-
570
if scanner.scan(/[^,;"]+/)
-
324
value << scanner.matched
-
246
elsif scanner.skip(/"/)
-
# RFC 6265 2.2
-
# A cookie-value may be DQUOTE'd.
-
12
value << scan_dquoted(scanner)
-
234
elsif scanner.check(/;/)
-
174
break
-
60
elsif comma_as_separator && scanner.check(RE_COOKIE_COMMA)
-
48
break
-
else
-
12
value << scanner.getch
-
end
-
end
-
-
330
value.rstrip!
-
330
value
-
end
-
-
6
def scan_name_value(scanner, comma_as_separator = false)
-
330
name = scanner.scan(RE_NAME)
-
330
name.rstrip! if name
-
-
330
if scanner.skip(/=/)
-
324
value = scan_value(scanner, comma_as_separator)
-
else
-
6
scan_value(scanner, comma_as_separator)
-
6
value = nil
-
end
-
330
[name, value]
-
end
-
-
6
def call(set_cookie)
-
108
scanner = StringScanner.new(set_cookie)
-
-
# RFC 6265 4.1.1 & 5.2
-
108
until scanner.eos?
-
156
start = scanner.pos
-
156
len = nil
-
-
156
scanner.skip(RE_WSP)
-
-
156
name, value = scan_name_value(scanner, true)
-
156
value = nil if name && name.empty?
-
-
156
attrs = {}
-
-
156
until scanner.eos?
-
222
if scanner.skip(/,/)
-
# The comma is used as separator for concatenating multiple
-
# values of a header.
-
48
len = (scanner.pos - 1) - start
-
48
break
-
174
elsif scanner.skip(/;/)
-
174
scanner.skip(RE_WSP)
-
-
174
aname, avalue = scan_name_value(scanner, true)
-
-
174
next if (aname.nil? || aname.empty?) || value.nil?
-
-
174
aname.downcase!
-
-
174
case aname
-
when "expires"
-
12
next unless avalue
-
-
# RFC 6265 5.2.1
-
12
(avalue = Time.parse(avalue)) || next
-
when "max-age"
-
6
next unless avalue
-
# RFC 6265 5.2.2
-
6
next unless /\A-?\d+\z/.match?(avalue)
-
-
6
avalue = Integer(avalue)
-
when "domain"
-
# RFC 6265 5.2.3
-
# An empty value SHOULD be ignored.
-
18
next if avalue.nil? || avalue.empty?
-
when "path"
-
# RFC 6265 5.2.4
-
# A relative path must be ignored rather than normalizing it
-
# to "/".
-
132
next unless avalue && avalue.start_with?("/")
-
when "secure", "httponly"
-
# RFC 6265 5.2.5, 5.2.6
-
6
avalue = true
-
end
-
174
attrs[aname] = avalue
-
end
-
end
-
-
156
len ||= scanner.pos - start
-
-
156
next if len > Cookie::MAX_LENGTH
-
-
156
yield(name, value, attrs) if name && !name.empty? && value
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds helper methods to implement HTTP Digest Auth (https://datatracker.ietf.org/doc/html/rfc7616)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#digest-auth
-
#
-
6
module DigestAuth
-
6
DigestError = Class.new(Error)
-
-
6
class << self
-
6
def extra_options(options)
-
120
options.merge(max_concurrent_requests: 1)
-
end
-
-
6
def load_dependencies(*)
-
120
require_relative "auth/digest"
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :digest :: instance of HTTPX::Plugins::Authentication::Digest, used to authenticate requests in the session.
-
6
module OptionsMethods
-
6
def option_digest(value)
-
240
raise TypeError, ":digest must be a #{Authentication::Digest}" unless value.is_a?(Authentication::Digest)
-
-
240
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def digest_auth(user, password, hashed: false)
-
120
with(digest: Authentication::Digest.new(user, password, hashed: hashed))
-
end
-
-
6
private
-
-
6
def send_requests(*requests)
-
144
requests.flat_map do |request|
-
144
digest = request.options.digest
-
-
144
next super(request) unless digest
-
-
240
probe_response = wrap { super(request).first }
-
-
120
return probe_response unless probe_response.is_a?(Response)
-
-
120
if probe_response.status == 401 && digest.can_authenticate?(probe_response.headers["www-authenticate"])
-
108
request.transition(:idle)
-
108
request.headers["authorization"] = digest.authenticate(request, probe_response.headers["www-authenticate"])
-
108
super(request)
-
else
-
12
probe_response
-
end
-
end
-
end
-
end
-
end
-
-
6
register_plugin :digest_auth, DigestAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin makes all HTTP/1.1 requests with a body send the "Expect: 100-continue".
-
#
-
# https://gitlab.com/os85/httpx/wikis/Expect#expect
-
#
-
6
module Expect
-
6
EXPECT_TIMEOUT = 2
-
-
6
class << self
-
6
def no_expect_store
-
138
@no_expect_store ||= []
-
end
-
-
6
def extra_options(options)
-
162
options.merge(expect_timeout: EXPECT_TIMEOUT)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :expect_timeout :: time (in seconds) to wait for a 100-expect response,
-
# before retrying without the Expect header (defaults to <tt>2</tt>).
-
# :expect_threshold_size :: min threshold (in bytes) of the request payload to enable the 100-continue negotiation on.
-
6
module OptionsMethods
-
6
def option_expect_timeout(value)
-
288
seconds = Float(value)
-
288
raise TypeError, ":expect_timeout must be positive" unless seconds.positive?
-
-
288
seconds
-
end
-
-
6
def option_expect_threshold_size(value)
-
12
bytes = Integer(value)
-
12
raise TypeError, ":expect_threshold_size must be positive" unless bytes.positive?
-
-
12
bytes
-
end
-
end
-
-
6
module RequestMethods
-
6
def initialize(*)
-
186
super
-
186
return if @body.empty?
-
-
126
threshold = @options.expect_threshold_size
-
126
return if threshold && !@body.unbounded_body? && @body.bytesize < threshold
-
-
114
return if Expect.no_expect_store.include?(origin)
-
-
108
@headers["expect"] = "100-continue"
-
end
-
-
6
def response=(response)
-
138
if response.is_a?(Response) &&
-
response.status == 100 &&
-
!@headers.key?("expect") &&
-
3
(@state == :body || @state == :done)
-
-
# if we're past this point, this means that we just received a 100-Continue response,
-
# but the request doesn't have the expect flag, and is already flushing (or flushed) the body.
-
#
-
# this means that expect was deactivated for this request too soon, i.e. response took longer.
-
#
-
# so we have to reactivate it again.
-
9
@headers["expect"] = "100-continue"
-
9
@informational_status = 100
-
9
Expect.no_expect_store.delete(origin)
-
end
-
138
super
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def send_request_to_parser(request)
-
84
super
-
-
84
return unless request.headers["expect"] == "100-continue"
-
-
60
expect_timeout = request.options.expect_timeout
-
-
60
return if expect_timeout.nil? || expect_timeout.infinite?
-
-
60
set_request_timeout(:expect_timeout, request, expect_timeout, :expect, %i[body response]) do
-
# expect timeout expired
-
15
if request.state == :expect && !request.expects?
-
15
Expect.no_expect_store << request.origin
-
15
request.headers.delete("expect")
-
15
consume
-
end
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def fetch_response(request, selector, options)
-
343
response = super
-
-
343
return unless response
-
-
84
if response.is_a?(Response) && response.status == 417 && request.headers.key?("expect")
-
12
response.close
-
12
request.headers.delete("expect")
-
12
request.transition(:idle)
-
12
send_request(request, selector, options)
-
12
return
-
end
-
-
72
response
-
end
-
end
-
end
-
6
register_plugin :expect, Expect
-
end
-
end
-
# frozen_string_literal: true
-
-
13
module HTTPX
-
13
InsecureRedirectError = Class.new(Error)
-
13
module Plugins
-
#
-
# This plugin adds support for automatically following redirect (status 30X) responses.
-
#
-
# It has a default upper bound of followed redirects (see *MAX_REDIRECTS* and the *max_redirects* option),
-
# after which it will return the last redirect response. It will **not** raise an exception.
-
#
-
# It doesn't follow insecure redirects (https -> http) by default (see *follow_insecure_redirects*).
-
#
-
# It doesn't propagate authorization related headers to requests redirecting to different origins
-
# (see *allow_auth_to_other_origins*) to override.
-
#
-
# It allows customization of when to redirect via the *redirect_on* callback option).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Follow-Redirects
-
#
-
13
module FollowRedirects
-
13
MAX_REDIRECTS = 3
-
13
REDIRECT_STATUS = (300..399).freeze
-
13
REQUEST_BODY_HEADERS = %w[transfer-encoding content-encoding content-type content-length content-language content-md5 trailer].freeze
-
-
13
using URIExtensions
-
-
# adds support for the following options:
-
#
-
# :max_redirects :: max number of times a request will be redirected (defaults to <tt>3</tt>).
-
# :follow_insecure_redirects :: whether redirects to an "http://" URI, when coming from an "https//", are allowed
-
# (defaults to <tt>false</tt>).
-
# :allow_auth_to_other_origins :: whether auth-related headers, such as "Authorization", are propagated on redirection
-
# (defaults to <tt>false</tt>).
-
# :redirect_on :: optional callback which receives the redirect location and can halt the redirect chain if it returns <tt>false</tt>.
-
13
module OptionsMethods
-
13
def option_max_redirects(value)
-
350
num = Integer(value)
-
350
raise TypeError, ":max_redirects must be positive" if num.negative?
-
-
350
num
-
end
-
-
13
def option_follow_insecure_redirects(value)
-
18
value
-
end
-
-
13
def option_allow_auth_to_other_origins(value)
-
18
value
-
end
-
-
13
def option_redirect_on(value)
-
36
raise TypeError, ":redirect_on must be callable" unless value.respond_to?(:call)
-
-
36
value
-
end
-
end
-
-
13
module InstanceMethods
-
# returns a session with the *max_redirects* option set to +n+
-
13
def max_redirects(n)
-
36
with(max_redirects: n.to_i)
-
end
-
-
13
private
-
-
13
def fetch_response(request, selector, options)
-
3598578
redirect_request = request.redirect_request
-
3598578
response = super(redirect_request, selector, options)
-
3598578
return unless response
-
-
430
max_redirects = redirect_request.max_redirects
-
-
430
return response unless response.is_a?(Response)
-
418
return response unless REDIRECT_STATUS.include?(response.status) && response.headers.key?("location")
-
273
return response unless max_redirects.positive?
-
-
249
redirect_uri = __get_location_from_response(response)
-
-
249
if options.redirect_on
-
24
redirect_allowed = options.redirect_on.call(redirect_uri)
-
24
return response unless redirect_allowed
-
end
-
-
# build redirect request
-
237
request_body = redirect_request.body
-
237
redirect_method = "GET"
-
237
redirect_params = {}
-
-
237
if response.status == 305 && options.respond_to?(:proxy)
-
6
request_body.rewind
-
# The requested resource MUST be accessed through the proxy given by
-
# the Location field. The Location field gives the URI of the proxy.
-
6
redirect_options = options.merge(headers: redirect_request.headers,
-
proxy: { uri: redirect_uri },
-
max_redirects: max_redirects - 1)
-
-
6
redirect_params[:body] = request_body
-
6
redirect_uri = redirect_request.uri
-
6
options = redirect_options
-
else
-
231
redirect_headers = redirect_request_headers(redirect_request.uri, redirect_uri, request.headers, options)
-
231
redirect_opts = Hash[options]
-
231
redirect_params[:max_redirects] = max_redirects - 1
-
-
231
unless request_body.empty?
-
18
if response.status == 307
-
# The method and the body of the original request are reused to perform the redirected request.
-
6
redirect_method = redirect_request.verb
-
6
request_body.rewind
-
6
redirect_params[:body] = request_body
-
else
-
# redirects are **ALWAYS** GET, so remove body-related headers
-
12
REQUEST_BODY_HEADERS.each do |h|
-
84
redirect_headers.delete(h)
-
end
-
12
redirect_params[:body] = nil
-
end
-
end
-
-
231
options = options.class.new(redirect_opts.merge(headers: redirect_headers.to_h))
-
end
-
-
237
redirect_uri = Utils.to_uri(redirect_uri)
-
-
237
if !options.follow_insecure_redirects &&
-
response.uri.scheme == "https" &&
-
redirect_uri.scheme == "http"
-
6
error = InsecureRedirectError.new(redirect_uri.to_s)
-
6
error.set_backtrace(caller)
-
6
return ErrorResponse.new(request, error)
-
end
-
-
231
retry_request = build_request(redirect_method, redirect_uri, redirect_params, options)
-
-
231
request.redirect_request = retry_request
-
-
231
redirect_after = response.headers["retry-after"]
-
-
231
if redirect_after
-
# Servers send the "Retry-After" header field to indicate how long the
-
# user agent ought to wait before making a follow-up request.
-
# When sent with any 3xx (Redirection) response, Retry-After indicates
-
# the minimum time that the user agent is asked to wait before issuing
-
# the redirected request.
-
#
-
23
redirect_after = Utils.parse_retry_after(redirect_after)
-
-
23
retry_start = Utils.now
-
23
log { "redirecting after #{redirect_after} secs..." }
-
23
selector.after(redirect_after) do
-
23
if (response = request.response)
-
11
response.finish!
-
11
retry_request.response = response
-
# request has terminated abruptly meanwhile
-
11
retry_request.emit(:response, response)
-
else
-
12
log { "redirecting (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
12
send_request(retry_request, selector, options)
-
end
-
end
-
else
-
208
send_request(retry_request, selector, options)
-
end
-
42
nil
-
end
-
-
# :nodoc:
-
13
def redirect_request_headers(original_uri, redirect_uri, headers, options)
-
231
headers = headers.dup
-
-
231
return headers if options.allow_auth_to_other_origins
-
-
225
return headers unless headers.key?("authorization")
-
-
6
return headers if original_uri.origin == redirect_uri.origin
-
-
6
headers.delete("authorization")
-
-
6
headers
-
end
-
-
# :nodoc:
-
13
def __get_location_from_response(response)
-
# @type var location_uri: http_uri
-
249
location_uri = URI(response.headers["location"])
-
249
location_uri = response.uri.merge(location_uri) if location_uri.relative?
-
249
location_uri
-
end
-
end
-
-
13
module RequestMethods
-
# returns the top-most original HTTPX::Request from the redirect chain
-
13
attr_accessor :root_request
-
-
# returns the follow-up redirect request, or itself
-
13
def redirect_request
-
3598578
@redirect_request || self
-
end
-
-
# sets the follow-up redirect request
-
13
def redirect_request=(req)
-
231
@redirect_request = req
-
231
req.root_request = @root_request || self
-
231
@response = nil
-
end
-
-
13
def response
-
3599934
return super unless @redirect_request && @response.nil?
-
-
57
@redirect_request.response
-
end
-
-
13
def max_redirects
-
430
@options.max_redirects || MAX_REDIRECTS
-
end
-
end
-
-
13
module ConnectionMethods
-
13
private
-
-
13
def set_request_request_timeout(request)
-
407
return unless request.root_request.nil?
-
-
193
super
-
end
-
end
-
end
-
13
register_plugin :follow_redirects, FollowRedirects
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
GRPCError = Class.new(Error) do
-
6
attr_reader :status, :details, :metadata
-
-
6
def initialize(status, details, metadata)
-
24
@status = status
-
24
@details = details
-
24
@metadata = metadata
-
24
super("GRPC error, code=#{status}, details=#{details}, metadata=#{metadata}")
-
end
-
end
-
-
6
module Plugins
-
#
-
# This plugin adds DSL to build GRPC interfaces.
-
#
-
# https://gitlab.com/os85/httpx/wikis/GRPC
-
#
-
6
module GRPC
-
6
unless String.method_defined?(:underscore)
-
6
module StringExtensions
-
6
refine String do
-
6
def underscore
-
312
s = dup # Avoid mutating the argument, as it might be frozen.
-
312
s.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
-
312
s.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
-
312
s.tr!("-", "_")
-
312
s.downcase!
-
312
s
-
end
-
end
-
end
-
6
using StringExtensions
-
end
-
-
6
DEADLINE = 60
-
6
MARSHAL_METHOD = :encode
-
6
UNMARSHAL_METHOD = :decode
-
6
HEADERS = {
-
"content-type" => "application/grpc",
-
"te" => "trailers",
-
"accept" => "application/grpc",
-
# metadata fits here
-
# ex "foo-bin" => base64("bar")
-
}.freeze
-
-
6
class << self
-
6
def load_dependencies(*)
-
138
require "stringio"
-
138
require "httpx/plugins/grpc/grpc_encoding"
-
138
require "httpx/plugins/grpc/message"
-
138
require "httpx/plugins/grpc/call"
-
end
-
-
6
def configure(klass)
-
138
klass.plugin(:persistent)
-
138
klass.plugin(:stream)
-
end
-
-
6
def extra_options(options)
-
138
options.merge(
-
fallback_protocol: "h2",
-
grpc_rpcs: {}.freeze,
-
grpc_compression: false,
-
grpc_deadline: DEADLINE
-
)
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_grpc_service(value)
-
120
String(value)
-
end
-
-
6
def option_grpc_compression(value)
-
162
case value
-
when true, false
-
138
value
-
else
-
24
value.to_s
-
end
-
end
-
-
6
def option_grpc_rpcs(value)
-
1116
Hash[value]
-
end
-
-
6
def option_grpc_deadline(value)
-
804
raise TypeError, ":grpc_deadline must be positive" unless value.positive?
-
-
804
value
-
end
-
-
6
def option_call_credentials(value)
-
18
raise TypeError, ":call_credentials must respond to #call" unless value.respond_to?(:call)
-
-
18
value
-
end
-
end
-
-
6
module ResponseMethods
-
6
attr_reader :trailing_metadata
-
-
6
def merge_headers(trailers)
-
114
@trailing_metadata = Hash[trailers]
-
114
super
-
end
-
end
-
-
6
module RequestBodyMethods
-
6
def initialize(*, **)
-
126
super
-
-
126
if (compression = @headers["grpc-encoding"])
-
12
deflater_body = self.class.initialize_deflater_body(@body, compression)
-
12
@body = Transcoder::GRPCEncoding.encode(deflater_body || @body, compressed: !deflater_body.nil?)
-
else
-
114
@body = Transcoder::GRPCEncoding.encode(@body, compressed: false)
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def with_channel_credentials(ca_path, key = nil, cert = nil, **ssl_opts)
-
# @type var ssl_params: ::Hash[::Symbol, untyped]
-
72
ssl_params = {
-
**ssl_opts,
-
ca_file: ca_path,
-
}
-
72
if key
-
72
key = File.read(key) if File.file?(key)
-
72
ssl_params[:key] = OpenSSL::PKey.read(key)
-
end
-
-
72
if cert
-
72
cert = File.read(cert) if File.file?(cert)
-
72
ssl_params[:cert] = OpenSSL::X509::Certificate.new(cert)
-
end
-
-
72
with(ssl: ssl_params)
-
end
-
-
6
def rpc(rpc_name, input, output, **opts)
-
312
rpc_name = rpc_name.to_s
-
312
raise Error, "rpc #{rpc_name} already defined" if @options.grpc_rpcs.key?(rpc_name)
-
-
rpc_opts = {
-
312
deadline: @options.grpc_deadline,
-
}.merge(opts)
-
-
312
local_rpc_name = rpc_name.underscore
-
-
312
session_class = Class.new(self.class) do
-
# define rpc method with ruby style name
-
312
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
def #{local_rpc_name}(input, **opts) # def grpc_action(input, **opts)
-
rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
-
end # end
-
OUT
-
-
# define rpc method with original name
-
312
unless local_rpc_name == rpc_name
-
12
class_eval(<<-OUT, __FILE__, __LINE__ + 1)
-
def #{rpc_name}(input, **opts) # def grpcAction(input, **opts)
-
rpc_execute("#{local_rpc_name}", input, **opts) # rpc_execute("grpc_action", input, **opts)
-
end # end
-
OUT
-
end
-
end
-
-
312
session_class.new(@options.merge(
-
grpc_rpcs: @options.grpc_rpcs.merge(
-
local_rpc_name => [rpc_name, input, output, rpc_opts]
-
).freeze
-
))
-
end
-
-
6
def build_stub(origin, service: nil, compression: false)
-
138
scheme = @options.ssl.empty? ? "http" : "https"
-
-
138
origin = URI.parse("#{scheme}://#{origin}")
-
-
138
session = self
-
-
138
if service && service.respond_to?(:rpc_descs)
-
# it's a grpc generic service
-
60
service.rpc_descs.each do |rpc_name, rpc_desc|
-
rpc_opts = {
-
300
marshal_method: rpc_desc.marshal_method,
-
unmarshal_method: rpc_desc.unmarshal_method,
-
}
-
-
300
input = rpc_desc.input
-
300
input = input.type if input.respond_to?(:type)
-
-
300
output = rpc_desc.output
-
300
if output.respond_to?(:type)
-
120
rpc_opts[:stream] = true
-
120
output = output.type
-
end
-
-
300
session = session.rpc(rpc_name, input, output, **rpc_opts)
-
end
-
-
60
service = service.service_name
-
end
-
-
138
session.with(origin: origin, grpc_service: service, grpc_compression: compression)
-
end
-
-
6
def execute(rpc_method, input,
-
deadline: DEADLINE,
-
metadata: nil,
-
**opts)
-
126
grpc_request = build_grpc_request(rpc_method, input, deadline: deadline, metadata: metadata, **opts)
-
126
response = request(grpc_request, **opts)
-
126
response.raise_for_status unless opts[:stream]
-
114
GRPC::Call.new(response)
-
end
-
-
6
private
-
-
6
def rpc_execute(rpc_name, input, **opts)
-
60
rpc_name, input_enc, output_enc, rpc_opts = @options.grpc_rpcs[rpc_name]
-
-
60
exec_opts = rpc_opts.merge(opts)
-
-
60
marshal_method ||= exec_opts.delete(:marshal_method) || MARSHAL_METHOD
-
60
unmarshal_method ||= exec_opts.delete(:unmarshal_method) || UNMARSHAL_METHOD
-
-
60
messages = if input.respond_to?(:each)
-
24
Enumerator.new do |y|
-
24
input.each do |message|
-
48
y << input_enc.__send__(marshal_method, message)
-
end
-
end
-
else
-
36
input_enc.__send__(marshal_method, input)
-
end
-
-
60
call = execute(rpc_name, messages, **exec_opts)
-
-
60
call.decoder = output_enc.method(unmarshal_method)
-
-
60
call
-
end
-
-
6
def build_grpc_request(rpc_method, input, deadline:, metadata: nil, **)
-
126
uri = @options.origin.dup
-
126
rpc_method = "/#{rpc_method}" unless rpc_method.start_with?("/")
-
126
rpc_method = "/#{@options.grpc_service}#{rpc_method}" if @options.grpc_service
-
126
uri.path = rpc_method
-
-
126
headers = HEADERS.merge(
-
"grpc-accept-encoding" => ["identity", *@options.supported_compression_formats]
-
)
-
126
unless deadline == Float::INFINITY
-
# convert to milliseconds
-
126
deadline = (deadline * 1000.0).to_i
-
126
headers["grpc-timeout"] = "#{deadline}m"
-
end
-
-
126
headers = headers.merge(metadata.transform_keys(&:to_s)) if metadata
-
-
# prepare compressor
-
126
compression = @options.grpc_compression == true ? "gzip" : @options.grpc_compression
-
-
126
headers["grpc-encoding"] = compression if compression
-
-
126
headers.merge!(@options.call_credentials.call.transform_keys(&:to_s)) if @options.call_credentials
-
-
126
build_request("POST", uri, headers: headers, body: input)
-
end
-
end
-
end
-
6
register_plugin :grpc, GRPC
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
6
module GRPC
-
# Encapsulates call information
-
6
class Call
-
6
attr_writer :decoder
-
-
6
def initialize(response)
-
114
@response = response
-
156
@decoder = ->(z) { z }
-
114
@consumed = false
-
114
@grpc_response = nil
-
end
-
-
6
def inspect
-
"#{self.class}(#{grpc_response})"
-
end
-
-
6
def to_s
-
66
grpc_response.to_s
-
end
-
-
6
def metadata
-
response.headers
-
end
-
-
6
def trailing_metadata
-
72
return unless @consumed
-
-
48
@response.trailing_metadata
-
end
-
-
6
private
-
-
6
def grpc_response
-
186
@grpc_response ||= if @response.respond_to?(:each)
-
24
Enumerator.new do |y|
-
24
Message.stream(@response).each do |message|
-
48
y << @decoder.call(message)
-
end
-
24
@consumed = true
-
end
-
else
-
90
@consumed = true
-
90
@decoder.call(Message.unary(@response))
-
end
-
end
-
-
6
def respond_to_missing?(meth, *args, &blk)
-
24
grpc_response.respond_to?(meth, *args) || super
-
end
-
-
6
def method_missing(meth, *args, &blk)
-
48
return grpc_response.__send__(meth, *args, &blk) if grpc_response.respond_to?(meth)
-
-
super
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Transcoder
-
6
module GRPCEncoding
-
6
class Deflater
-
6
extend Forwardable
-
-
6
attr_reader :content_type
-
-
6
def initialize(body, compressed:)
-
126
@content_type = body.content_type
-
126
@body = BodyReader.new(body)
-
126
@compressed = compressed
-
end
-
-
6
def bytesize
-
450
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
Float::INFINITY
-
end
-
-
6
def read(length = nil, outbuf = nil)
-
276
buf = @body.read(length, outbuf)
-
-
252
return unless buf
-
-
138
compressed_flag = @compressed ? 1 : 0
-
-
138
buf = outbuf if outbuf
-
-
138
buf = buf.b if buf.frozen?
-
-
138
buf.prepend([compressed_flag, buf.bytesize].pack("CL>"))
-
138
buf
-
end
-
end
-
-
6
class Inflater
-
6
def initialize(response)
-
90
@response = response
-
90
@grpc_encodings = nil
-
end
-
-
6
def call(message, &blk)
-
114
data = "".b
-
-
114
until message.empty?
-
114
compressed, size = message.unpack("CL>")
-
-
114
encoded_data = message.byteslice(5..size + 5 - 1)
-
-
114
if compressed == 1
-
12
grpc_encodings.reverse_each do |encoding|
-
12
decoder = @response.body.class.initialize_inflater_by_encoding(encoding, @response, bytesize: encoded_data.bytesize)
-
12
encoded_data = decoder.call(encoded_data)
-
-
12
blk.call(encoded_data) if blk
-
-
12
data << encoded_data
-
end
-
else
-
102
blk.call(encoded_data) if blk
-
-
102
data << encoded_data
-
end
-
-
114
message = message.byteslice((size + 5)..-1)
-
end
-
-
114
data
-
end
-
-
6
private
-
-
6
def grpc_encodings
-
12
@grpc_encodings ||= @response.headers.get("grpc-encoding")
-
end
-
end
-
-
6
def self.encode(*args, **kwargs)
-
126
Deflater.new(*args, **kwargs)
-
end
-
-
6
def self.decode(response)
-
90
Inflater.new(response)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
6
module GRPC
-
# Encoding module for GRPC responses
-
#
-
# Can encode and decode grpc messages.
-
6
module Message
-
6
module_function
-
-
# decodes a unary grpc response
-
6
def unary(response)
-
90
verify_status(response)
-
-
66
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
66
decoder.call(response.to_s)
-
end
-
-
# lazy decodes a grpc stream response
-
6
def stream(response, &block)
-
48
return enum_for(__method__, response) unless block
-
-
24
decoder = Transcoder::GRPCEncoding.decode(response)
-
-
24
response.each do |frame|
-
48
decoder.call(frame, &block)
-
end
-
-
24
verify_status(response)
-
end
-
-
6
def cancel(request)
-
request.emit(:refuse, :client_cancellation)
-
end
-
-
# interprets the grpc call trailing metadata, and raises an
-
# exception in case of error code
-
6
def verify_status(response)
-
# return standard errors if need be
-
114
response.raise_for_status
-
-
114
status = Integer(response.headers["grpc-status"])
-
114
message = response.headers["grpc-message"]
-
-
114
return if status.zero?
-
-
24
response.close
-
24
raise GRPCError.new(status, message, response.trailing_metadata)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for upgrading a plaintext HTTP/1.1 connection to HTTP/2
-
# (https://datatracker.ietf.org/doc/html/rfc7540#section-3.2)
-
#
-
# https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2c
-
#
-
6
module H2C
-
6
VALID_H2C_VERBS = %w[GET OPTIONS HEAD].freeze
-
-
6
class << self
-
6
def load_dependencies(klass)
-
12
klass.plugin(:upgrade)
-
end
-
-
6
def call(connection, request, response)
-
12
connection.upgrade_to_h2c(request, response)
-
end
-
-
6
def extra_options(options)
-
12
options.merge(max_concurrent_requests: 1, upgrade_handlers: options.upgrade_handlers.merge("h2c" => self))
-
end
-
end
-
-
6
class H2CParser < Connection::HTTP2
-
6
def upgrade(request, response)
-
# skip checks, it is assumed that this is the first
-
# request in the connection
-
12
stream = @connection.upgrade
-
-
# on_settings
-
12
handle_stream(stream, request)
-
12
@streams[request] = stream
-
-
# clean up data left behind in the buffer, if the server started
-
# sending frames
-
12
data = response.read
-
12
@connection << data
-
end
-
end
-
-
6
module RequestMethods
-
6
def valid_h2c_verb?
-
12
VALID_H2C_VERBS.include?(@verb)
-
end
-
end
-
-
6
module ConnectionMethods
-
6
using URIExtensions
-
-
6
def initialize(*)
-
12
super
-
12
@h2c_handshake = false
-
end
-
-
6
def send(request)
-
42
return super if @h2c_handshake
-
-
12
return super unless request.valid_h2c_verb? && request.scheme == "http"
-
-
12
return super if @upgrade_protocol == "h2c"
-
-
12
@h2c_handshake = true
-
-
# build upgrade request
-
12
request.headers.add("connection", "upgrade")
-
12
request.headers.add("connection", "http2-settings")
-
12
request.headers["upgrade"] = "h2c"
-
12
request.headers["http2-settings"] = ::HTTP2::Client.settings_header(request.options.http2_settings)
-
-
12
super
-
end
-
-
6
def upgrade_to_h2c(request, response)
-
12
prev_parser = @parser
-
-
12
if prev_parser
-
12
prev_parser.reset
-
12
@inflight -= prev_parser.requests.size
-
end
-
-
12
@parser = H2CParser.new(@write_buffer, @options)
-
12
set_parser_callbacks(@parser)
-
12
@inflight += 1
-
12
@parser.upgrade(request, response)
-
12
@upgrade_protocol = "h2c"
-
-
12
prev_parser.requests.each do |req|
-
12
req.transition(:idle)
-
12
send(req)
-
end
-
end
-
-
6
private
-
-
6
def send_request_to_parser(request)
-
42
super
-
-
42
return unless request.headers["upgrade"] == "h2c" && parser.is_a?(Connection::HTTP1)
-
-
12
max_concurrent_requests = parser.max_concurrent_requests
-
-
12
return if max_concurrent_requests == 1
-
-
parser.max_concurrent_requests = 1
-
request.once(:response) do
-
parser.max_concurrent_requests = max_concurrent_requests
-
end
-
end
-
end
-
end
-
6
register_plugin(:h2c, H2C)
-
end
-
end
-
# frozen_string_literal: true
-
-
3
module HTTPX
-
3
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/Auth#ntlm-auth
-
#
-
3
module NTLMAuth
-
3
class << self
-
3
def load_dependencies(_klass)
-
2
require_relative "auth/ntlm"
-
end
-
-
3
def extra_options(options)
-
2
options.merge(max_concurrent_requests: 1)
-
end
-
end
-
-
3
module OptionsMethods
-
3
def option_ntlm(value)
-
8
raise TypeError, ":ntlm must be a #{Authentication::Ntlm}" unless value.is_a?(Authentication::Ntlm)
-
-
8
value
-
end
-
end
-
-
3
module InstanceMethods
-
3
def ntlm_auth(user, password, domain = nil)
-
4
with(ntlm: Authentication::Ntlm.new(user, password, domain: domain))
-
end
-
-
3
private
-
-
3
def send_requests(*requests)
-
8
requests.flat_map do |request|
-
8
ntlm = request.options.ntlm
-
-
8
if ntlm
-
4
request.headers["authorization"] = ntlm.negotiate
-
8
probe_response = wrap { super(request).first }
-
-
4
return probe_response unless probe_response.is_a?(Response)
-
-
4
if probe_response.status == 401 && ntlm.can_authenticate?(probe_response.headers["www-authenticate"])
-
2
request.transition(:idle)
-
2
request.headers["authorization"] = ntlm.authenticate(request, probe_response.headers["www-authenticate"])
-
2
super(request)
-
else
-
2
probe_response
-
end
-
else
-
4
super(request)
-
end
-
end
-
end
-
end
-
end
-
3
register_plugin :ntlm_auth, NTLMAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# https://gitlab.com/os85/httpx/wikis/OAuth
-
#
-
6
module OAuth
-
6
class << self
-
6
def load_dependencies(_klass)
-
108
require_relative "auth/basic"
-
end
-
end
-
-
6
SUPPORTED_GRANT_TYPES = %w[client_credentials refresh_token].freeze
-
6
SUPPORTED_AUTH_METHODS = %w[client_secret_basic client_secret_post].freeze
-
-
6
class OAuthSession
-
6
attr_reader :grant_type, :client_id, :client_secret, :access_token, :refresh_token, :scope
-
-
6
def initialize(
-
issuer:,
-
client_id:,
-
client_secret:,
-
access_token: nil,
-
refresh_token: nil,
-
scope: nil,
-
token_endpoint: nil,
-
response_type: nil,
-
grant_type: nil,
-
token_endpoint_auth_method: nil
-
)
-
96
@issuer = URI(issuer)
-
96
@client_id = client_id
-
96
@client_secret = client_secret
-
96
@token_endpoint = URI(token_endpoint) if token_endpoint
-
96
@response_type = response_type
-
96
@scope = case scope
-
when String
-
36
scope.split
-
when Array
-
24
scope
-
end
-
96
@access_token = access_token
-
96
@refresh_token = refresh_token
-
96
@token_endpoint_auth_method = String(token_endpoint_auth_method) if token_endpoint_auth_method
-
96
@grant_type = grant_type || (@refresh_token ? "refresh_token" : "client_credentials")
-
-
96
unless @token_endpoint_auth_method.nil? || SUPPORTED_AUTH_METHODS.include?(@token_endpoint_auth_method)
-
12
raise Error, "#{@token_endpoint_auth_method} is not a supported auth method"
-
end
-
-
84
return if SUPPORTED_GRANT_TYPES.include?(@grant_type)
-
-
12
raise Error, "#{@grant_type} is not a supported grant type"
-
end
-
-
6
def token_endpoint
-
84
@token_endpoint || "#{@issuer}/token"
-
end
-
-
6
def token_endpoint_auth_method
-
120
@token_endpoint_auth_method || "client_secret_basic"
-
end
-
-
6
def load(http)
-
36
return if @grant_type && @scope
-
-
12
metadata = http.get("#{@issuer}/.well-known/oauth-authorization-server").raise_for_status.json
-
-
12
@token_endpoint = metadata["token_endpoint"]
-
12
@scope = metadata["scopes_supported"]
-
48
@grant_type = Array(metadata["grant_types_supported"]).find { |gr| SUPPORTED_GRANT_TYPES.include?(gr) }
-
12
@token_endpoint_auth_method = Array(metadata["token_endpoint_auth_methods_supported"]).find do |am|
-
12
SUPPORTED_AUTH_METHODS.include?(am)
-
end
-
2
nil
-
end
-
-
6
def merge(other)
-
72
obj = dup
-
-
72
case other
-
when OAuthSession
-
36
other.instance_variables.each do |ivar|
-
324
val = other.instance_variable_get(ivar)
-
324
next unless val
-
-
252
obj.instance_variable_set(ivar, val)
-
end
-
when Hash
-
36
other.each do |k, v|
-
72
obj.instance_variable_set(:"@#{k}", v) if obj.instance_variable_defined?(:"@#{k}")
-
end
-
end
-
72
obj
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_oauth_session(value)
-
228
case value
-
when Hash
-
12
OAuthSession.new(**value)
-
when OAuthSession
-
204
value
-
else
-
12
raise TypeError, ":oauth_session must be a #{OAuthSession}"
-
end
-
end
-
end
-
-
6
module InstanceMethods
-
6
def oauth_auth(**args)
-
84
with(oauth_session: OAuthSession.new(**args))
-
end
-
-
6
def with_access_token
-
36
oauth_session = @options.oauth_session
-
-
36
oauth_session.load(self)
-
-
36
grant_type = oauth_session.grant_type
-
-
36
headers = {}
-
36
form_post = { "grant_type" => grant_type, "scope" => Array(oauth_session.scope).join(" ") }.compact
-
-
# auth
-
36
case oauth_session.token_endpoint_auth_method
-
when "client_secret_post"
-
12
form_post["client_id"] = oauth_session.client_id
-
12
form_post["client_secret"] = oauth_session.client_secret
-
when "client_secret_basic"
-
24
headers["authorization"] = Authentication::Basic.new(oauth_session.client_id, oauth_session.client_secret).authenticate
-
end
-
-
36
case grant_type
-
when "client_credentials"
-
# do nothing
-
when "refresh_token"
-
12
form_post["refresh_token"] = oauth_session.refresh_token
-
end
-
-
36
token_request = build_request("POST", oauth_session.token_endpoint, headers: headers, form: form_post)
-
36
token_request.headers.delete("authorization") unless oauth_session.token_endpoint_auth_method == "client_secret_basic"
-
-
36
token_response = request(token_request)
-
36
token_response.raise_for_status
-
-
36
payload = token_response.json
-
-
36
access_token = payload["access_token"]
-
36
refresh_token = payload["refresh_token"]
-
-
36
with(oauth_session: oauth_session.merge(access_token: access_token, refresh_token: refresh_token))
-
end
-
-
6
def build_request(*)
-
96
request = super
-
-
96
return request if request.headers.key?("authorization")
-
-
72
oauth_session = @options.oauth_session
-
-
72
return request unless oauth_session && oauth_session.access_token
-
-
48
request.headers["authorization"] = "Bearer #{oauth_session.access_token}"
-
-
48
request
-
end
-
end
-
end
-
6
register_plugin :oauth, OAuth
-
end
-
end
-
# frozen_string_literal: true
-
-
15
module HTTPX
-
15
module Plugins
-
# This plugin implements a session that persists connections over the duration of the process.
-
#
-
# This will improve connection reuse in a long-running process.
-
#
-
# One important caveat to note is, although this session might not close connections,
-
# other sessions from the same process that don't have this plugin turned on might.
-
#
-
# This session will still be able to work with it, as if, when expecting a connection
-
# terminated by a different session, it will just retry on a new one and keep it open.
-
#
-
# This plugin is also not recommendable when connecting to >9000 (like, a lot) different origins.
-
# So when you use this, make sure that you don't fall into this trap.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Persistent
-
#
-
15
module Persistent
-
15
def self.load_dependencies(klass)
-
424
max_retries = if klass.default_options.respond_to?(:max_retries)
-
6
[klass.default_options.max_retries, 1].max
-
else
-
418
1
-
end
-
424
klass.plugin(:retries, max_retries: max_retries)
-
end
-
-
15
def self.extra_options(options)
-
424
options.merge(persistent: true)
-
end
-
-
15
module InstanceMethods
-
15
private
-
-
15
def repeatable_request?(request, _)
-
439
super || begin
-
180
response = request.response
-
-
180
return false unless response && response.is_a?(ErrorResponse)
-
-
24
error = response.error
-
-
264
Retries::RECONNECTABLE_ERRORS.any? { |klass| error.is_a?(klass) }
-
end
-
end
-
-
15
def retryable_error?(ex)
-
64
super &&
-
# under the persistent plugin rules, requests are only retried for connection related errors,
-
# which do not include request timeout related errors. This only gets overriden if the end user
-
# manually changed +:max_retries+ to something else, which means it is aware of the
-
# consequences.
-
52
(!ex.is_a?(RequestTimeoutError) || @options.max_retries != 1)
-
end
-
-
15
def get_current_selector
-
417
super(&nil) || begin
-
404
return unless block_given?
-
-
404
default = yield
-
-
404
set_current_selector(default)
-
-
404
default
-
end
-
end
-
end
-
end
-
15
register_plugin :persistent, Persistent
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
class HTTPProxyError < ConnectionError; end
-
-
8
module Plugins
-
#
-
# This plugin adds support for proxies. It ships with support for:
-
#
-
# * HTTP proxies
-
# * HTTPS proxies
-
# * Socks4/4a proxies
-
# * Socks5 proxies
-
#
-
# https://gitlab.com/os85/httpx/wikis/Proxy
-
#
-
8
module Proxy
-
8
Error = HTTPProxyError
-
8
PROXY_ERRORS = [TimeoutError, IOError, SystemCallError, Error].freeze
-
-
8
class << self
-
8
def configure(klass)
-
255
klass.plugin(:"proxy/http")
-
255
klass.plugin(:"proxy/socks4")
-
255
klass.plugin(:"proxy/socks5")
-
end
-
-
8
def extra_options(options)
-
255
options.merge(supported_proxy_protocols: [])
-
end
-
end
-
-
8
class Parameters
-
8
attr_reader :uri, :username, :password, :scheme, :no_proxy
-
-
8
def initialize(uri: nil, scheme: nil, username: nil, password: nil, no_proxy: nil, **extra)
-
281
@no_proxy = Array(no_proxy) if no_proxy
-
281
@uris = Array(uri)
-
281
uri = @uris.first
-
-
281
@username = username
-
281
@password = password
-
-
281
@ns = 0
-
-
281
if uri
-
251
@uri = uri.is_a?(URI::Generic) ? uri : URI(uri)
-
251
@username ||= @uri.user
-
251
@password ||= @uri.password
-
end
-
-
281
@scheme = scheme
-
-
281
return unless @uri && @username && @password
-
-
160
@authenticator = nil
-
160
@scheme ||= infer_default_auth_scheme(@uri)
-
-
160
return unless @scheme
-
-
124
@authenticator = load_authenticator(@scheme, @username, @password, **extra)
-
end
-
-
8
def shift
-
# TODO: this operation must be synchronized
-
90
@ns += 1
-
90
@uri = @uris[@ns]
-
-
90
return unless @uri
-
-
12
@uri = URI(@uri) unless @uri.is_a?(URI::Generic)
-
-
12
scheme = infer_default_auth_scheme(@uri)
-
-
12
return unless scheme != @scheme
-
-
12
@scheme = scheme
-
12
@username = username || @uri.user
-
12
@password = password || @uri.password
-
12
@authenticator = load_authenticator(scheme, @username, @password)
-
end
-
-
8
def can_authenticate?(*args)
-
138
return false unless @authenticator
-
-
48
@authenticator.can_authenticate?(*args)
-
end
-
-
8
def authenticate(*args)
-
123
return unless @authenticator
-
-
123
@authenticator.authenticate(*args)
-
end
-
-
8
def ==(other)
-
332
case other
-
when Parameters
-
302
@uri == other.uri &&
-
@username == other.username &&
-
@password == other.password &&
-
@scheme == other.scheme
-
when URI::Generic, String
-
18
proxy_uri = @uri.dup
-
18
proxy_uri.user = @username
-
18
proxy_uri.password = @password
-
18
other_uri = other.is_a?(URI::Generic) ? other : URI.parse(other)
-
18
proxy_uri == other_uri
-
else
-
12
super
-
end
-
end
-
-
8
private
-
-
8
def infer_default_auth_scheme(uri)
-
160
case uri.scheme
-
when "socks5"
-
36
uri.scheme
-
when "http", "https"
-
88
"basic"
-
end
-
end
-
-
8
def load_authenticator(scheme, username, password, **extra)
-
136
auth_scheme = scheme.to_s.capitalize
-
-
136
require_relative "auth/#{scheme}" unless defined?(Authentication) && Authentication.const_defined?(auth_scheme, false)
-
-
136
Authentication.const_get(auth_scheme).new(username, password, **extra)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :proxy :: proxy options defining *:uri*, *:username*, *:password* or
-
# *:scheme* (i.e. <tt>{ uri: "http://proxy" }</tt>)
-
8
module OptionsMethods
-
8
def option_proxy(value)
-
510
value.is_a?(Parameters) ? value : Parameters.new(**Hash[value])
-
end
-
-
8
def option_supported_proxy_protocols(value)
-
1287
raise TypeError, ":supported_proxy_protocols must be an Array" unless value.is_a?(Array)
-
-
1287
value.map(&:to_s)
-
end
-
end
-
-
8
module InstanceMethods
-
8
def find_connection(request_uri, selector, options)
-
319
return super unless options.respond_to?(:proxy)
-
-
319
if (next_proxy = request_uri.find_proxy)
-
4
return super(request_uri, selector, options.merge(proxy: Parameters.new(uri: next_proxy)))
-
end
-
-
315
proxy = options.proxy
-
-
315
return super unless proxy
-
-
307
next_proxy = proxy.uri
-
-
307
raise Error, "Failed to connect to proxy" unless next_proxy
-
-
raise Error,
-
295
"#{next_proxy.scheme}: unsupported proxy protocol" unless options.supported_proxy_protocols.include?(next_proxy.scheme)
-
-
289
if (no_proxy = proxy.no_proxy)
-
12
no_proxy = no_proxy.join(",") if no_proxy.is_a?(Array)
-
-
# TODO: setting proxy to nil leaks the connection object in the pool
-
12
return super(request_uri, selector, options.merge(proxy: nil)) unless URI::Generic.use_proxy?(request_uri.host, next_proxy.host,
-
next_proxy.port, no_proxy)
-
end
-
-
283
super(request_uri, selector, options.merge(proxy: proxy))
-
end
-
-
8
private
-
-
8
def fetch_response(request, selector, options)
-
1256
response = super
-
-
1256
if response.is_a?(ErrorResponse) && proxy_error?(request, response, options)
-
90
options.proxy.shift
-
-
# return last error response if no more proxies to try
-
90
return response if options.proxy.uri.nil?
-
-
12
log { "failed connecting to proxy, trying next..." }
-
12
request.transition(:idle)
-
12
send_request(request, selector, options)
-
12
return
-
end
-
1166
response
-
end
-
-
8
def proxy_error?(_request, response, options)
-
127
return false unless options.proxy
-
-
126
error = response.error
-
126
case error
-
when NativeResolveError
-
12
proxy_uri = URI(options.proxy.uri)
-
-
12
peer = error.connection.peer
-
-
# failed resolving proxy domain
-
12
peer.host == proxy_uri.host && peer.port == proxy_uri.port
-
when ResolveError
-
proxy_uri = URI(options.proxy.uri)
-
-
error.message.end_with?(proxy_uri.to_s)
-
when *PROXY_ERRORS
-
# timeout errors connecting to proxy
-
114
true
-
else
-
false
-
end
-
end
-
end
-
-
8
module ConnectionMethods
-
8
using URIExtensions
-
-
8
def initialize(*)
-
294
super
-
294
return unless @options.proxy
-
-
# redefining the connection origin as the proxy's URI,
-
# as this will be used as the tcp peer ip.
-
280
@proxy_uri = URI(@options.proxy.uri)
-
end
-
-
8
def peer
-
734
@proxy_uri || super
-
end
-
-
8
def connecting?
-
3606
return super unless @options.proxy
-
-
3476
super || @state == :connecting || @state == :connected
-
end
-
-
8
def call
-
902
super
-
-
902
return unless @options.proxy
-
-
874
case @state
-
when :connecting
-
276
consume
-
end
-
end
-
-
8
def reset
-
292
return super unless @options.proxy
-
-
279
@state = :open
-
-
279
super
-
# emit(:close)
-
end
-
-
8
private
-
-
8
def initialize_type(uri, options)
-
294
return super unless options.proxy
-
-
280
"tcp"
-
end
-
-
8
def connect
-
803
return super unless @options.proxy
-
-
777
case @state
-
when :idle
-
542
transition(:connecting)
-
when :connected
-
235
transition(:open)
-
end
-
end
-
-
8
def handle_transition(nextstate)
-
1622
return super unless @options.proxy
-
-
1555
case nextstate
-
when :closing
-
# this is a hack so that we can use the super method
-
# and it'll think that the current state is open
-
285
@state = :open if @state == :connecting
-
end
-
1555
super
-
end
-
end
-
end
-
8
register_plugin :proxy, Proxy
-
end
-
-
8
class ProxySSL < SSL
-
8
def initialize(tcp, request_uri, options)
-
69
@io = tcp.to_io
-
69
super(request_uri, tcp.addresses, options)
-
69
@hostname = request_uri.host
-
69
@state = :connected
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
module Plugins
-
8
module Proxy
-
8
module HTTP
-
8
class << self
-
8
def extra_options(options)
-
255
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[http])
-
end
-
end
-
-
8
module InstanceMethods
-
8
def with_proxy_basic_auth(opts)
-
6
with(proxy: opts.merge(scheme: "basic"))
-
end
-
-
8
def with_proxy_digest_auth(opts)
-
18
with(proxy: opts.merge(scheme: "digest"))
-
end
-
-
8
def with_proxy_ntlm_auth(opts)
-
6
with(proxy: opts.merge(scheme: "ntlm"))
-
end
-
-
8
def fetch_response(request, selector, options)
-
1256
response = super
-
-
1256
if response &&
-
response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
response.headers.key?("proxy-authenticate") && options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
6
request.transition(:idle)
-
6
request.headers["proxy-authorization"] =
-
options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
6
send_request(request, selector, options)
-
6
return
-
end
-
-
1250
response
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def connecting?
-
3606
super || @state == :connecting || @state == :connected
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
1807
return super unless @options.proxy && @options.proxy.uri.scheme == "http"
-
-
894
case nextstate
-
when :connecting
-
236
return unless @state == :idle
-
-
236
@io.connect
-
236
return unless @io.connected?
-
-
118
@parser || begin
-
112
@parser = parser_type(@io.protocol).new(@write_buffer, @options.merge(max_concurrent_requests: 1))
-
112
parser = @parser
-
112
parser.extend(ProxyParser)
-
112
parser.on(:response, &method(:__http_on_connect))
-
112
parser.on(:close) do |force|
-
45
next unless @parser
-
-
6
if force
-
6
reset
-
6
emit(:terminate)
-
end
-
end
-
112
parser.on(:reset) do
-
12
if parser.empty?
-
6
reset
-
else
-
6
transition(:closing)
-
6
transition(:closed)
-
-
6
parser.reset if @parser
-
6
transition(:idle)
-
6
transition(:connecting)
-
end
-
end
-
112
__http_proxy_connect(parser)
-
end
-
118
return if @state == :connected
-
when :connected
-
106
return unless @state == :idle || @state == :connecting
-
-
106
case @state
-
when :connecting
-
39
parser = @parser
-
39
@parser = nil
-
39
parser.close
-
when :idle
-
67
@parser.callbacks.clear
-
67
set_parser_callbacks(@parser)
-
end
-
end
-
709
super
-
end
-
-
8
def __http_proxy_connect(parser)
-
112
req = @pending.first
-
112
if req && req.uri.scheme == "https"
-
# if the first request after CONNECT is to an https address, it is assumed that
-
# all requests in the queue are not only ALL HTTPS, but they also share the certificate,
-
# and therefore, will share the connection.
-
#
-
45
connect_request = ConnectRequest.new(req.uri, @options)
-
45
@inflight += 1
-
45
parser.send(connect_request)
-
else
-
67
handle_transition(:connected)
-
end
-
end
-
-
8
def __http_on_connect(request, response)
-
51
@inflight -= 1
-
51
if response.is_a?(Response) && response.status == 200
-
39
req = @pending.first
-
39
request_uri = req.uri
-
39
@io = ProxySSL.new(@io, request_uri, @options)
-
39
transition(:connected)
-
39
throw(:called)
-
12
elsif response.is_a?(Response) &&
-
response.status == 407 &&
-
!request.headers.key?("proxy-authorization") &&
-
@options.proxy.can_authenticate?(response.headers["proxy-authenticate"])
-
-
6
request.transition(:idle)
-
6
request.headers["proxy-authorization"] = @options.proxy.authenticate(request, response.headers["proxy-authenticate"])
-
6
@parser.send(request)
-
6
@inflight += 1
-
else
-
6
pending = @pending + @parser.pending
-
18
while (req = pending.shift)
-
6
response.finish!
-
6
req.response = response
-
6
req.emit(:response, response)
-
end
-
6
reset
-
end
-
end
-
end
-
-
8
module ProxyParser
-
8
def join_headline(request)
-
112
return super if request.verb == "CONNECT"
-
-
61
"#{request.verb} #{request.uri} HTTP/#{@version.join(".")}"
-
end
-
-
8
def set_protocol_headers(request)
-
118
extra_headers = super
-
-
118
proxy_params = @options.proxy
-
118
if proxy_params.scheme == "basic"
-
# opt for basic auth
-
75
extra_headers["proxy-authorization"] = proxy_params.authenticate(extra_headers)
-
end
-
118
extra_headers["proxy-connection"] = extra_headers.delete("connection") if extra_headers.key?("connection")
-
118
extra_headers
-
end
-
end
-
-
8
class ConnectRequest < Request
-
8
def initialize(uri, options)
-
45
super("CONNECT", uri, options)
-
45
@headers.delete("accept")
-
end
-
-
8
def path
-
57
"#{@uri.hostname}:#{@uri.port}"
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/http", Proxy::HTTP
-
end
-
end
-
# frozen_string_literal: true
-
-
8
require "resolv"
-
8
require "ipaddr"
-
-
8
module HTTPX
-
8
class Socks4Error < HTTPProxyError; end
-
-
8
module Plugins
-
8
module Proxy
-
8
module Socks4
-
8
VERSION = 4
-
8
CONNECT = 1
-
8
GRANTED = 0x5A
-
8
PROTOCOLS = %w[socks4 socks4a].freeze
-
-
8
Error = Socks4Error
-
-
8
class << self
-
8
def extra_options(options)
-
255
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + PROTOCOLS)
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def interests
-
3072
if @state == :connecting
-
return @write_buffer.empty? ? :r : :w
-
end
-
-
3072
super
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
1855
return super unless @options.proxy && PROTOCOLS.include?(@options.proxy.uri.scheme)
-
-
330
case nextstate
-
when :connecting
-
96
return unless @state == :idle
-
-
96
@io.connect
-
96
return unless @io.connected?
-
-
48
req = @pending.first
-
48
return unless req
-
-
48
request_uri = req.uri
-
48
@write_buffer << Packet.connect(@options.proxy, request_uri)
-
48
__socks4_proxy_connect
-
when :connected
-
36
return unless @state == :connecting
-
-
36
@parser = nil
-
end
-
282
log(level: 1) { "SOCKS4: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
282
super
-
end
-
-
8
def __socks4_proxy_connect
-
48
@parser = SocksParser.new(@write_buffer, @options)
-
48
@parser.once(:packet, &method(:__socks4_on_packet))
-
end
-
-
8
def __socks4_on_packet(packet)
-
48
_version, status, _port, _ip = packet.unpack("CCnN")
-
48
if status == GRANTED
-
36
req = @pending.first
-
36
request_uri = req.uri
-
36
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
36
transition(:connected)
-
36
throw(:called)
-
else
-
12
on_socks4_error("socks error: #{status}")
-
end
-
end
-
-
8
def on_socks4_error(message)
-
12
ex = Error.new(message)
-
12
ex.set_backtrace(caller)
-
12
on_error(ex)
-
12
throw(:called)
-
end
-
end
-
-
8
class SocksParser
-
8
include HTTPX::Callbacks
-
-
8
def initialize(buffer, options)
-
48
@buffer = buffer
-
48
@options = options
-
end
-
-
8
def close; end
-
-
8
def consume(*); end
-
-
8
def empty?
-
true
-
end
-
-
8
def <<(packet)
-
48
emit(:packet, packet)
-
end
-
end
-
-
8
module Packet
-
8
module_function
-
-
8
def connect(parameters, uri)
-
48
packet = [VERSION, CONNECT, uri.port].pack("CCn")
-
-
48
case parameters.uri.scheme
-
when "socks4"
-
36
socks_host = uri.host
-
begin
-
72
ip = IPAddr.new(socks_host)
-
36
packet << ip.hton
-
rescue IPAddr::InvalidAddressError
-
36
socks_host = Resolv.getaddress(socks_host)
-
36
retry
-
end
-
36
packet << [parameters.username].pack("Z*")
-
when "socks4a"
-
12
packet << "\x0\x0\x0\x1" << [parameters.username].pack("Z*") << uri.host << "\x0"
-
end
-
48
packet
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/socks4", Proxy::Socks4
-
end
-
end
-
# frozen_string_literal: true
-
-
8
module HTTPX
-
8
class Socks5Error < HTTPProxyError; end
-
-
8
module Plugins
-
8
module Proxy
-
8
module Socks5
-
8
VERSION = 5
-
8
NOAUTH = 0
-
8
PASSWD = 2
-
8
NONE = 0xff
-
8
CONNECT = 1
-
8
IPV4 = 1
-
8
DOMAIN = 3
-
8
IPV6 = 4
-
8
SUCCESS = 0
-
-
8
Error = Socks5Error
-
-
8
class << self
-
8
def load_dependencies(*)
-
255
require_relative "../auth/socks5"
-
end
-
-
8
def extra_options(options)
-
255
options.merge(supported_proxy_protocols: options.supported_proxy_protocols + %w[socks5])
-
end
-
end
-
-
8
module ConnectionMethods
-
8
def call
-
902
super
-
-
902
return unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
276
case @state
-
when :connecting,
-
:negotiating,
-
:authenticating
-
143
consume
-
end
-
end
-
-
8
def connecting?
-
3606
super || @state == :authenticating || @state == :negotiating
-
end
-
-
8
def interests
-
5188
if @state == :connecting || @state == :authenticating || @state == :negotiating
-
2116
return @write_buffer.empty? ? :r : :w
-
end
-
-
3072
super
-
end
-
-
8
private
-
-
8
def handle_transition(nextstate)
-
2071
return super unless @options.proxy && @options.proxy.uri.scheme == "socks5"
-
-
780
case nextstate
-
when :connecting
-
216
return unless @state == :idle
-
-
216
@io.connect
-
216
return unless @io.connected?
-
-
108
@write_buffer << Packet.negotiate(@options.proxy)
-
108
__socks5_proxy_connect
-
when :authenticating
-
36
return unless @state == :connecting
-
-
36
@write_buffer << Packet.authenticate(@options.proxy)
-
when :negotiating
-
144
return unless @state == :connecting || @state == :authenticating
-
-
36
req = @pending.first
-
36
request_uri = req.uri
-
36
@write_buffer << Packet.connect(request_uri)
-
when :connected
-
24
return unless @state == :negotiating
-
-
24
@parser = nil
-
end
-
564
log(level: 1) { "SOCKS5: #{nextstate}: #{@write_buffer.to_s.inspect}" } unless nextstate == :open
-
564
super
-
end
-
-
8
def __socks5_proxy_connect
-
108
@parser = SocksParser.new(@write_buffer, @options)
-
108
@parser.on(:packet, &method(:__socks5_on_packet))
-
108
transition(:negotiating)
-
end
-
-
8
def __socks5_on_packet(packet)
-
180
case @state
-
when :connecting
-
108
version, method = packet.unpack("CC")
-
108
__socks5_check_version(version)
-
108
case method
-
when PASSWD
-
36
transition(:authenticating)
-
6
nil
-
when NONE
-
60
__on_socks5_error("no supported authorization methods")
-
else
-
12
transition(:negotiating)
-
end
-
when :authenticating
-
36
_, status = packet.unpack("CC")
-
36
return transition(:negotiating) if status == SUCCESS
-
-
12
__on_socks5_error("socks authentication error: #{status}")
-
when :negotiating
-
36
version, reply, = packet.unpack("CC")
-
36
__socks5_check_version(version)
-
36
__on_socks5_error("socks5 negotiation error: #{reply}") unless reply == SUCCESS
-
24
req = @pending.first
-
24
request_uri = req.uri
-
24
@io = ProxySSL.new(@io, request_uri, @options) if request_uri.scheme == "https"
-
24
transition(:connected)
-
24
throw(:called)
-
end
-
end
-
-
8
def __socks5_check_version(version)
-
144
__on_socks5_error("invalid SOCKS version (#{version})") if version != 5
-
end
-
-
8
def __on_socks5_error(message)
-
84
ex = Error.new(message)
-
84
ex.set_backtrace(caller)
-
84
on_error(ex)
-
84
throw(:called)
-
end
-
end
-
-
8
class SocksParser
-
8
include HTTPX::Callbacks
-
-
8
def initialize(buffer, options)
-
108
@buffer = buffer
-
108
@options = options
-
end
-
-
8
def close; end
-
-
8
def consume(*); end
-
-
8
def empty?
-
true
-
end
-
-
8
def <<(packet)
-
180
emit(:packet, packet)
-
end
-
end
-
-
8
module Packet
-
8
module_function
-
-
8
def negotiate(parameters)
-
108
methods = [NOAUTH]
-
108
methods << PASSWD if parameters.can_authenticate?
-
108
methods.unshift(methods.size)
-
108
methods.unshift(VERSION)
-
108
methods.pack("C*")
-
end
-
-
8
def authenticate(parameters)
-
36
parameters.authenticate
-
end
-
-
8
def connect(uri)
-
36
packet = [VERSION, CONNECT, 0].pack("C*")
-
begin
-
36
ip = IPAddr.new(uri.host)
-
-
12
ipcode = ip.ipv6? ? IPV6 : IPV4
-
-
12
packet << [ipcode].pack("C") << ip.hton
-
rescue IPAddr::InvalidAddressError
-
24
packet << [DOMAIN, uri.host.bytesize, uri.host].pack("CCA*")
-
end
-
36
packet << [uri.port].pack("n")
-
36
packet
-
end
-
end
-
end
-
end
-
8
register_plugin :"proxy/socks5", Proxy::Socks5
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "httpx/plugins/proxy"
-
-
6
module HTTPX
-
6
module Plugins
-
6
module Proxy
-
6
module SSH
-
6
class << self
-
6
def load_dependencies(*)
-
12
require "net/ssh/gateway"
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_proxy(value)
-
24
Hash[value]
-
end
-
end
-
-
6
module InstanceMethods
-
6
def request(*args, **options)
-
12
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
12
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
-
12
request = requests.first or return super
-
-
12
request_options = request.options
-
-
12
return super unless request_options.proxy
-
-
12
ssh_options = request_options.proxy
-
12
ssh_uris = ssh_options.delete(:uri)
-
12
ssh_uri = URI.parse(ssh_uris.shift)
-
-
12
return super unless ssh_uri.scheme == "ssh"
-
-
12
ssh_username = ssh_options.delete(:username)
-
12
ssh_options[:port] ||= ssh_uri.port || 22
-
12
if request_options.debug
-
ssh_options[:verbose] = request_options.debug_level == 2 ? :debug : :info
-
end
-
-
12
request_uri = URI(requests.first.uri)
-
12
@_gateway = Net::SSH::Gateway.new(ssh_uri.host, ssh_username, ssh_options)
-
begin
-
12
@_gateway.open(request_uri.host, request_uri.port) do |local_port|
-
12
io = build_gateway_socket(local_port, request_uri, request_options)
-
12
super(*args, **options.merge(io: io))
-
end
-
ensure
-
12
@_gateway.shutdown!
-
end
-
end
-
-
6
private
-
-
6
def build_gateway_socket(port, request_uri, options)
-
12
case request_uri.scheme
-
when "https"
-
6
ctx = OpenSSL::SSL::SSLContext.new
-
6
ctx_options = SSL::TLS_OPTIONS.merge(options.ssl)
-
6
ctx.set_params(ctx_options) unless ctx_options.empty?
-
6
sock = TCPSocket.open("localhost", port)
-
6
io = OpenSSL::SSL::SSLSocket.new(sock, ctx)
-
6
io.hostname = request_uri.host
-
6
io.sync_close = true
-
6
io.connect
-
6
io.post_connection_check(request_uri.host) if ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE
-
6
io
-
when "http"
-
6
TCPSocket.open("localhost", port)
-
else
-
raise TypeError, "unexpected scheme: #{request_uri.scheme}"
-
end
-
end
-
end
-
-
6
module ConnectionMethods
-
# should not coalesce connections here, as the IP is the IP of the proxy
-
6
def coalescable?(*)
-
return super unless @options.proxy
-
-
false
-
end
-
end
-
end
-
end
-
6
register_plugin :"proxy/ssh", Proxy::SSH
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for HTTP/2 Push responses.
-
#
-
# In order to benefit from this, requests are sent one at a time, so that
-
# no push responses are received after corresponding request has been sent.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Push
-
#
-
6
module PushPromise
-
6
def self.extra_options(options)
-
12
options.merge(http2_settings: { settings_enable_push: 1 },
-
max_concurrent_requests: 1)
-
end
-
-
6
module ResponseMethods
-
6
def pushed?
-
12
@__pushed
-
end
-
-
6
def mark_as_pushed!
-
6
@__pushed = true
-
end
-
end
-
-
6
module InstanceMethods
-
6
private
-
-
6
def promise_headers
-
12
@promise_headers ||= {}
-
end
-
-
6
def on_promise(parser, stream)
-
12
stream.on(:promise_headers) do |h|
-
12
__on_promise_request(parser, stream, h)
-
end
-
12
stream.on(:headers) do |h|
-
6
__on_promise_response(parser, stream, h)
-
end
-
end
-
-
6
def __on_promise_request(parser, stream, h)
-
12
log(level: 1, color: :yellow) do
-
skipped
# :nocov:
-
skipped
h.map { |k, v| "#{stream.id}: -> PROMISE HEADER: #{k}: #{v}" }.join("\n")
-
skipped
# :nocov:
-
end
-
12
headers = @options.headers_class.new(h)
-
12
path = headers[":path"]
-
12
authority = headers[":authority"]
-
-
18
request = parser.pending.find { |r| r.authority == authority && r.path == path }
-
12
if request
-
6
request.merge_headers(headers)
-
6
promise_headers[stream] = request
-
6
parser.pending.delete(request)
-
6
parser.streams[request] = stream
-
6
request.transition(:done)
-
else
-
6
stream.refuse
-
end
-
end
-
-
6
def __on_promise_response(parser, stream, h)
-
6
request = promise_headers.delete(stream)
-
6
return unless request
-
-
6
parser.__send__(:on_stream_headers, stream, request, h)
-
6
response = request.response
-
6
response.mark_as_pushed!
-
6
stream.on(:data, &parser.method(:on_stream_data).curry(3)[stream, request])
-
6
stream.on(:close, &parser.method(:on_stream_close).curry(3)[stream, request])
-
end
-
end
-
end
-
6
register_plugin(:push_promise, PushPromise)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for using the experimental QUERY HTTP method
-
#
-
# https://gitlab.com/os85/httpx/wikis/Query
-
6
module Query
-
6
def self.subplugins
-
{
-
18
retries: QueryRetries,
-
}
-
end
-
-
6
module InstanceMethods
-
6
def query(*uri, **options)
-
12
request("QUERY", uri, **options)
-
end
-
end
-
-
6
module QueryRetries
-
6
module InstanceMethods
-
6
private
-
-
6
def repeatable_request?(request, options)
-
18
super || request.verb == "QUERY"
-
end
-
end
-
end
-
end
-
-
6
register_plugin :query, Query
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for retrying requests when the request:
-
#
-
# * is rate limited;
-
# * when the server is unavailable (503);
-
# * when a 3xx request comes with a "retry-after" value
-
#
-
# https://gitlab.com/os85/httpx/wikis/Rate-Limiter
-
#
-
6
module RateLimiter
-
6
class << self
-
6
RATE_LIMIT_CODES = [429, 503].freeze
-
-
6
def configure(klass)
-
48
klass.plugin(:retries,
-
retry_change_requests: true,
-
retry_on: method(:retry_on_rate_limited_response),
-
retry_after: method(:retry_after_rate_limit))
-
end
-
-
6
def retry_on_rate_limited_response(response)
-
96
return false unless response.is_a?(Response)
-
-
96
status = response.status
-
-
96
RATE_LIMIT_CODES.include?(status)
-
end
-
-
# Servers send the "Retry-After" header field to indicate how long the
-
# user agent ought to wait before making a follow-up request. When
-
# sent with a 503 (Service Unavailable) response, Retry-After indicates
-
# how long the service is expected to be unavailable to the client.
-
# When sent with any 3xx (Redirection) response, Retry-After indicates
-
# the minimum time that the user agent is asked to wait before issuing
-
# the redirected request.
-
#
-
6
def retry_after_rate_limit(_, response)
-
48
return unless response.is_a?(Response)
-
-
48
retry_after = response.headers["retry-after"]
-
-
48
return unless retry_after
-
-
24
Utils.parse_retry_after(retry_after)
-
end
-
end
-
end
-
-
6
register_plugin :rate_limiter, RateLimiter
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for retrying requests when certain errors happen.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Response-Cache
-
#
-
6
module ResponseCache
-
6
CACHEABLE_VERBS = %w[GET HEAD].freeze
-
6
CACHEABLE_STATUS_CODES = [200, 203, 206, 300, 301, 410].freeze
-
6
SUPPORTED_VARY_HEADERS = %w[accept accept-encoding accept-language cookie origin].sort.freeze
-
6
private_constant :CACHEABLE_VERBS
-
6
private_constant :CACHEABLE_STATUS_CODES
-
-
6
class << self
-
6
def load_dependencies(*)
-
168
require_relative "response_cache/store"
-
168
require_relative "response_cache/file_store"
-
end
-
-
# whether the +response+ can be stored in the response cache.
-
# (i.e. has a cacheable body, does not contain directives prohibiting storage, etc...)
-
6
def cacheable_response?(response)
-
102
response.is_a?(Response) &&
-
(
-
102
response.cache_control.nil? ||
-
# TODO: !response.cache_control.include?("private") && is shared cache
-
!response.cache_control.include?("no-store")
-
) &&
-
CACHEABLE_STATUS_CODES.include?(response.status) &&
-
# RFC 2616 13.4 - A response received with a status code of 200, 203, 206, 300, 301 or
-
# 410 MAY be stored by a cache and used in reply to a subsequent
-
# request, subject to the expiration mechanism, unless a cache-control
-
# directive prohibits caching. However, a cache that does not support
-
# the Range and Content-Range headers MUST NOT cache 206 (Partial
-
# Content) responses.
-
response.status != 206
-
end
-
-
# whether the +response+
-
6
def not_modified?(response)
-
126
response.is_a?(Response) && response.status == 304
-
end
-
-
6
def extra_options(options)
-
168
options.merge(
-
supported_vary_headers: SUPPORTED_VARY_HEADERS,
-
response_cache_store: :store,
-
)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :supported_vary_headers :: array of header values that will be considered for a "vary" header based cache validation
-
# (defaults to {SUPPORTED_VARY_HEADERS}).
-
# :response_cache_store :: object where cached responses are fetch from or stored in; defaults to <tt>:store</tt> (in-memory
-
# cache), can be set to <tt>:file_store</tt> (file system cache store) as well, or any object which
-
# abides by the Cache Store Interface
-
#
-
# The Cache Store Interface requires implementation of the following methods:
-
#
-
# * +#get(request) -> response or nil+
-
# * +#set(request, response) -> void+
-
# * +#clear() -> void+)
-
#
-
6
module OptionsMethods
-
6
def option_response_cache_store(value)
-
282
case value
-
when :store
-
180
Store.new
-
when :file_store
-
12
FileStore.new
-
else
-
90
value
-
end
-
end
-
-
6
def option_supported_vary_headers(value)
-
168
Array(value).sort
-
end
-
end
-
-
6
module InstanceMethods
-
# wipes out all cached responses from the cache store.
-
6
def clear_response_cache
-
102
@options.response_cache_store.clear
-
end
-
-
6
def build_request(*)
-
348
request = super
-
348
return request unless cacheable_request?(request)
-
-
336
prepare_cache(request)
-
-
336
request
-
end
-
-
6
private
-
-
6
def send_request(request, *)
-
126
return request if request.response
-
-
114
super
-
end
-
-
6
def fetch_response(request, *)
-
409
response = super
-
-
409
return unless response
-
-
126
if ResponseCache.not_modified?(response)
-
24
log { "returning cached response for #{request.uri}" }
-
-
24
response.copy_from_cached!
-
102
elsif request.cacheable_verb? && ResponseCache.cacheable_response?(response)
-
84
request.options.response_cache_store.set(request, response) unless response.cached?
-
end
-
-
126
response
-
end
-
-
# will either assign a still-fresh cached response to +request+, or set up its HTTP
-
# cache invalidation headers in case it's not fresh anymore.
-
6
def prepare_cache(request)
-
504
cached_response = request.options.response_cache_store.get(request)
-
-
504
return unless cached_response && match_by_vary?(request, cached_response)
-
-
228
cached_response.body.rewind
-
-
228
if cached_response.fresh?
-
48
cached_response = cached_response.dup
-
48
cached_response.mark_as_cached!
-
48
request.response = cached_response
-
48
request.emit(:response, cached_response)
-
48
return
-
end
-
-
180
request.cached_response = cached_response
-
-
180
if !request.headers.key?("if-modified-since") && (last_modified = cached_response.headers["last-modified"])
-
24
request.headers.add("if-modified-since", last_modified)
-
end
-
-
180
if !request.headers.key?("if-none-match") && (etag = cached_response.headers["etag"]) # rubocop:disable Style/GuardClause
-
132
request.headers.add("if-none-match", etag)
-
end
-
end
-
-
6
def cacheable_request?(request)
-
348
request.cacheable_verb? &&
-
(
-
336
!request.headers.key?("cache-control") || !request.headers.get("cache-control").include?("no-store")
-
)
-
end
-
-
# whether the +response+ complies with the directives set by the +request+ "vary" header
-
# (true when none is available).
-
6
def match_by_vary?(request, response)
-
228
vary = response.vary
-
-
228
return true unless vary
-
-
72
original_request = response.original_request
-
-
72
if vary == %w[*]
-
24
request.options.supported_vary_headers.each do |field|
-
120
return false unless request.headers[field] == original_request.headers[field]
-
end
-
-
24
return true
-
end
-
-
48
vary.all? do |field|
-
48
!original_request.headers.key?(field) || request.headers[field] == original_request.headers[field]
-
end
-
end
-
end
-
-
6
module RequestMethods
-
# points to a previously cached Response corresponding to this request.
-
6
attr_accessor :cached_response
-
-
6
def initialize(*)
-
468
super
-
468
@cached_response = nil
-
end
-
-
6
def merge_headers(*)
-
222
super
-
222
@response_cache_key = nil
-
end
-
-
# returns whether this request is cacheable as per HTTP caching rules.
-
6
def cacheable_verb?
-
450
CACHEABLE_VERBS.include?(@verb)
-
end
-
-
# returns a unique cache key as a String identifying this request
-
6
def response_cache_key
-
972
@response_cache_key ||= begin
-
354
keys = [@verb, @uri]
-
-
354
@options.supported_vary_headers.each do |field|
-
1770
value = @headers[field]
-
-
1770
keys << value if value
-
end
-
354
Digest::SHA1.hexdigest("httpx-response-cache-#{keys.join("-")}")
-
end
-
end
-
end
-
-
6
module ResponseMethods
-
6
attr_writer :original_request
-
-
6
def initialize(*)
-
378
super
-
378
@cached = false
-
end
-
-
# a copy of the request this response was originally cached from
-
6
def original_request
-
72
@original_request || @request
-
end
-
-
# whether this Response was duplicated from a previously {RequestMethods#cached_response}.
-
6
def cached?
-
84
@cached
-
end
-
-
# sets this Response as being duplicated from a previously cached response.
-
6
def mark_as_cached!
-
48
@cached = true
-
end
-
-
# eager-copies the response headers and body from {RequestMethods#cached_response}.
-
6
def copy_from_cached!
-
24
cached_response = @request.cached_response
-
-
24
return unless cached_response
-
-
# 304 responses do not have content-type, which are needed for decoding.
-
24
@headers = @headers.class.new(cached_response.headers.merge(@headers))
-
-
24
@body = cached_response.body.dup
-
-
24
@body.rewind
-
end
-
-
# A response is fresh if its age has not yet exceeded its freshness lifetime.
-
# other (#cache_control} directives may influence the outcome, as per the rules
-
# from the {rfc}[https://www.rfc-editor.org/rfc/rfc7234]
-
6
def fresh?
-
228
if cache_control
-
84
return false if cache_control.include?("no-cache")
-
-
60
return true if cache_control.include?("immutable")
-
-
# check age: max-age
-
144
max_age = cache_control.find { |directive| directive.start_with?("s-maxage") }
-
-
144
max_age ||= cache_control.find { |directive| directive.start_with?("max-age") }
-
-
60
max_age = max_age[/age=(\d+)/, 1] if max_age
-
-
60
max_age = max_age.to_i if max_age
-
-
60
return max_age > age if max_age
-
end
-
-
# check age: expires
-
144
if @headers.key?("expires")
-
begin
-
36
expires = Time.httpdate(@headers["expires"])
-
rescue ArgumentError
-
12
return false
-
end
-
-
24
return (expires - Time.now).to_i.positive?
-
end
-
-
108
false
-
end
-
-
# returns the "cache-control" directives as an Array of String(s).
-
6
def cache_control
-
636
return @cache_control if defined?(@cache_control)
-
-
@cache_control = begin
-
288
return unless @headers.key?("cache-control")
-
-
84
@headers["cache-control"].split(/ *, */)
-
end
-
end
-
-
# returns the "vary" header value as an Array of (String) headers.
-
6
def vary
-
228
return @vary if defined?(@vary)
-
-
@vary = begin
-
204
return unless @headers.key?("vary")
-
-
48
@headers["vary"].split(/ *, */).map(&:downcase)
-
end
-
end
-
-
6
private
-
-
# returns the value of the "age" header as an Integer (time since epoch).
-
# if no "age" of header exists, it returns the number of seconds since {#date}.
-
6
def age
-
60
return @headers["age"].to_i if @headers.key?("age")
-
-
60
(Time.now - date).to_i
-
end
-
-
# returns the value of the "date" header as a Time object
-
6
def date
-
60
@date ||= Time.httpdate(@headers["date"])
-
rescue NoMethodError, ArgumentError
-
12
Time.now
-
end
-
end
-
end
-
6
register_plugin :response_cache, ResponseCache
-
end
-
end
-
# frozen_string_literal: true
-
-
6
require "pathname"
-
-
6
module HTTPX::Plugins
-
6
module ResponseCache
-
# Implementation of a file system based cache store.
-
#
-
# It stores cached responses in a file under a directory pointed by the +dir+
-
# variable (defaults to the default temp directory from the OS), in a custom
-
# format (similar but different from HTTP/1.1 request/response framing).
-
6
class FileStore
-
6
CRLF = HTTPX::Connection::HTTP1::CRLF
-
-
6
attr_reader :dir
-
-
6
def initialize(dir = Dir.tmpdir)
-
60
@dir = Pathname.new(dir).join("httpx-response-cache")
-
-
60
FileUtils.mkdir_p(@dir)
-
end
-
-
6
def clear
-
48
FileUtils.rm_rf(@dir)
-
end
-
-
6
def get(request)
-
222
path = file_path(request)
-
-
222
return unless File.exist?(path)
-
-
114
File.open(path, mode: File::RDONLY | File::BINARY) do |f|
-
114
f.flock(File::Constants::LOCK_SH)
-
-
114
read_from_file(request, f)
-
end
-
end
-
-
6
def set(request, response)
-
72
path = file_path(request)
-
-
72
file_exists = File.exist?(path)
-
-
72
mode = file_exists ? File::RDWR : File::CREAT | File::Constants::WRONLY
-
-
72
File.open(path, mode: mode | File::BINARY) do |f|
-
72
f.flock(File::Constants::LOCK_EX)
-
-
72
if file_exists
-
6
cached_response = read_from_file(request, f)
-
-
6
if cached_response
-
6
next if cached_response == request.cached_response
-
-
6
cached_response.close
-
-
6
f.truncate(0)
-
-
6
f.rewind
-
end
-
end
-
# cache the request headers
-
72
f << request.verb << CRLF
-
72
f << request.uri << CRLF
-
-
72
request.headers.each do |field, value|
-
216
f << field << ":" << value << CRLF
-
end
-
-
72
f << CRLF
-
-
# cache the response
-
72
f << response.status << CRLF
-
72
f << response.version << CRLF
-
-
72
response.headers.each do |field, value|
-
198
f << field << ":" << value << CRLF
-
end
-
-
72
f << CRLF
-
-
72
response.body.rewind
-
-
72
::IO.copy_stream(response.body, f)
-
end
-
end
-
-
6
private
-
-
6
def file_path(request)
-
294
@dir.join(request.response_cache_key)
-
end
-
-
6
def read_from_file(request, f)
-
# if it's an empty file
-
120
return if f.eof?
-
-
# read request data
-
120
verb = f.readline.delete_suffix!(CRLF)
-
120
uri = f.readline.delete_suffix!(CRLF)
-
-
120
request_headers = {}
-
600
while (line = f.readline) != CRLF
-
360
line.delete_suffix!(CRLF)
-
360
sep_index = line.index(":")
-
-
360
field = line.byteslice(0..(sep_index - 1))
-
360
value = line.byteslice((sep_index + 1)..-1)
-
-
360
request_headers[field] = value
-
end
-
-
120
status = f.readline.delete_suffix!(CRLF)
-
120
version = f.readline.delete_suffix!(CRLF)
-
-
120
response_headers = {}
-
570
while (line = f.readline) != CRLF
-
330
line.delete_suffix!(CRLF)
-
330
sep_index = line.index(":")
-
-
330
field = line.byteslice(0..(sep_index - 1))
-
330
value = line.byteslice((sep_index + 1)..-1)
-
-
330
response_headers[field] = value
-
end
-
-
120
original_request = request.options.request_class.new(verb, uri, request.options)
-
120
original_request.merge_headers(request_headers)
-
-
120
response = request.options.response_class.new(request, status, version, response_headers)
-
120
response.original_request = original_request
-
120
response.finish!
-
-
120
::IO.copy_stream(f, response.body)
-
-
120
response
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX::Plugins
-
6
module ResponseCache
-
# Implementation of a thread-safe in-memory cache store.
-
6
class Store
-
6
def initialize
-
222
@store = {}
-
222
@store_mutex = Thread::Mutex.new
-
end
-
-
6
def clear
-
108
@store_mutex.synchronize { @store.clear }
-
end
-
-
6
def get(request)
-
336
@store_mutex.synchronize do
-
336
@store[request.response_cache_key]
-
end
-
end
-
-
6
def set(request, response)
-
150
@store_mutex.synchronize do
-
150
cached_response = @store[request.response_cache_key]
-
-
150
cached_response.close if cached_response
-
-
150
@store[request.response_cache_key] = response
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
15
module HTTPX
-
15
module Plugins
-
#
-
# This plugin adds support for retrying requests when errors happen.
-
#
-
# It has a default max number of retries (see *MAX_RETRIES* and the *max_retries* option),
-
# after which it will return the last response, error or not. It will **not** raise an exception.
-
#
-
# It does not retry which are not considered idempotent (see *retry_change_requests* to override).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Retries
-
#
-
15
module Retries
-
15
MAX_RETRIES = 3
-
# TODO: pass max_retries in a configure/load block
-
-
15
IDEMPOTENT_METHODS = %w[GET OPTIONS HEAD PUT DELETE].freeze
-
-
# subset of retryable errors which are safe to retry when reconnecting
-
RECONNECTABLE_ERRORS = [
-
15
IOError,
-
EOFError,
-
Errno::ECONNRESET,
-
Errno::ECONNABORTED,
-
Errno::EPIPE,
-
Errno::EINVAL,
-
Errno::ETIMEDOUT,
-
ConnectionError,
-
TLSError,
-
Connection::HTTP2::Error,
-
].freeze
-
-
15
RETRYABLE_ERRORS = (RECONNECTABLE_ERRORS + [
-
Parser::Error,
-
TimeoutError,
-
]).freeze
-
15
DEFAULT_JITTER = ->(interval) { interval * ((rand + 1) * 0.5) }
-
-
15
if ENV.key?("HTTPX_NO_JITTER")
-
14
def self.extra_options(options)
-
632
options.merge(max_retries: MAX_RETRIES)
-
end
-
else
-
1
def self.extra_options(options)
-
2
options.merge(max_retries: MAX_RETRIES, retry_jitter: DEFAULT_JITTER)
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :max_retries :: max number of times a request will be retried (defaults to <tt>3</tt>).
-
# :retry_change_requests :: whether idempotent requests are retried (defaults to <tt>false</tt>).
-
# :retry_after:: seconds after which a request is retried; can also be a callable object (i.e. <tt>->(req, res) { ... } </tt>)
-
# :retry_jitter :: number of seconds applied to *:retry_after* (must be a callable, i.e. <tt>->(retry_after) { ... } </tt>).
-
# :retry_on :: callable which alternatively defines a different rule for when a response is to be retried
-
# (i.e. <tt>->(res) { ... }</tt>).
-
15
module OptionsMethods
-
15
def option_retry_after(value)
-
# return early if callable
-
156
unless value.respond_to?(:call)
-
72
value = Float(value)
-
72
raise TypeError, ":retry_after must be positive" unless value.positive?
-
end
-
-
156
value
-
end
-
-
15
def option_retry_jitter(value)
-
# return early if callable
-
42
raise TypeError, ":retry_jitter must be callable" unless value.respond_to?(:call)
-
-
42
value
-
end
-
-
15
def option_max_retries(value)
-
1986
num = Integer(value)
-
1986
raise TypeError, ":max_retries must be positive" unless num >= 0
-
-
1986
num
-
end
-
-
15
def option_retry_change_requests(v)
-
96
v
-
end
-
-
15
def option_retry_on(value)
-
216
raise TypeError, ":retry_on must be called with the response" unless value.respond_to?(:call)
-
-
216
value
-
end
-
end
-
-
15
module InstanceMethods
-
# returns a `:retries` plugin enabled session with +n+ maximum retries per request setting.
-
15
def max_retries(n)
-
72
with(max_retries: n)
-
end
-
-
15
private
-
-
15
def fetch_response(request, selector, options)
-
6069534
response = super
-
-
6069534
if response &&
-
request.retries.positive? &&
-
repeatable_request?(request, options) &&
-
(
-
(
-
235
response.is_a?(ErrorResponse) && retryable_error?(response.error)
-
) ||
-
(
-
167
options.retry_on && options.retry_on.call(response)
-
)
-
)
-
376
try_partial_retry(request, response)
-
376
log { "failed to get response, #{request.retries} tries to go..." }
-
376
request.retries -= 1 unless request.ping? # do not exhaust retries on connection liveness probes
-
376
request.transition(:idle)
-
-
376
retry_after = options.retry_after
-
376
retry_after = retry_after.call(request, response) if retry_after.respond_to?(:call)
-
-
376
if retry_after
-
# apply jitter
-
72
if (jitter = request.options.retry_jitter)
-
12
retry_after = jitter.call(retry_after)
-
end
-
-
72
retry_start = Utils.now
-
72
log { "retrying after #{retry_after} secs..." }
-
72
selector.after(retry_after) do
-
72
if (response = request.response)
-
response.finish!
-
# request has terminated abruptly meanwhile
-
request.emit(:response, response)
-
else
-
72
log { "retrying (elapsed time: #{Utils.elapsed_time(retry_start)})!!" }
-
72
send_request(request, selector, options)
-
end
-
end
-
else
-
304
send_request(request, selector, options)
-
end
-
-
376
return
-
end
-
6069158
response
-
end
-
-
# returns whether +request+ can be retried.
-
15
def repeatable_request?(request, options)
-
859
IDEMPOTENT_METHODS.include?(request.verb) || options.retry_change_requests
-
end
-
-
# returns whether the +ex+ exception happend for a retriable request.
-
15
def retryable_error?(ex)
-
2781
RETRYABLE_ERRORS.any? { |klass| ex.is_a?(klass) }
-
end
-
-
15
def proxy_error?(request, response, _)
-
48
super && !request.retries.positive?
-
end
-
-
#
-
# Attempt to set the request to perform a partial range request.
-
# This happens if the peer server accepts byte-range requests, and
-
# the last response contains some body payload.
-
#
-
15
def try_partial_retry(request, response)
-
376
response = response.response if response.is_a?(ErrorResponse)
-
-
376
return unless response
-
-
179
unless response.headers.key?("accept-ranges") &&
-
response.headers["accept-ranges"] == "bytes" && # there's nothing else supported though...
-
12
(original_body = response.body)
-
167
response.body.close
-
167
return
-
end
-
-
12
request.partial_response = response
-
-
12
size = original_body.bytesize
-
-
12
request.headers["range"] = "bytes=#{size}-"
-
end
-
end
-
-
15
module RequestMethods
-
# number of retries left.
-
15
attr_accessor :retries
-
-
# a response partially received before.
-
15
attr_writer :partial_response
-
-
# initializes the request instance, sets the number of retries for the request.
-
15
def initialize(*args)
-
657
super
-
657
@retries = @options.max_retries
-
end
-
-
15
def response=(response)
-
1045
if @partial_response
-
12
if response.is_a?(Response) && response.status == 206
-
12
response.from_partial_response(@partial_response)
-
else
-
@partial_response.close
-
end
-
12
@partial_response = nil
-
end
-
-
1045
super
-
end
-
end
-
-
15
module ResponseMethods
-
15
def from_partial_response(response)
-
12
@status = response.status
-
12
@headers = response.headers
-
12
@body = response.body
-
end
-
end
-
end
-
15
register_plugin :retries, Retries
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
class ServerSideRequestForgeryError < Error; end
-
-
6
module Plugins
-
#
-
# This plugin adds support for preventing Server-Side Request Forgery attacks.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Server-Side-Request-Forgery-Filter
-
#
-
6
module SsrfFilter
-
6
module IPAddrExtensions
-
6
refine IPAddr do
-
6
def prefixlen
-
96
mask_addr = @mask_addr
-
96
raise "Invalid mask" if mask_addr.zero?
-
-
96
mask_addr >>= 1 while (mask_addr & 0x1).zero?
-
-
96
length = 0
-
96
while mask_addr & 0x1 == 0x1
-
1518
length += 1
-
1518
mask_addr >>= 1
-
end
-
-
96
length
-
end
-
end
-
end
-
-
6
using IPAddrExtensions
-
-
# https://en.wikipedia.org/wiki/Reserved_IP_addresses
-
IPV4_BLACKLIST = [
-
6
IPAddr.new("0.0.0.0/8"), # Current network (only valid as source address)
-
IPAddr.new("10.0.0.0/8"), # Private network
-
IPAddr.new("100.64.0.0/10"), # Shared Address Space
-
IPAddr.new("127.0.0.0/8"), # Loopback
-
IPAddr.new("169.254.0.0/16"), # Link-local
-
IPAddr.new("172.16.0.0/12"), # Private network
-
IPAddr.new("192.0.0.0/24"), # IETF Protocol Assignments
-
IPAddr.new("192.0.2.0/24"), # TEST-NET-1, documentation and examples
-
IPAddr.new("192.88.99.0/24"), # IPv6 to IPv4 relay (includes 2002::/16)
-
IPAddr.new("192.168.0.0/16"), # Private network
-
IPAddr.new("198.18.0.0/15"), # Network benchmark tests
-
IPAddr.new("198.51.100.0/24"), # TEST-NET-2, documentation and examples
-
IPAddr.new("203.0.113.0/24"), # TEST-NET-3, documentation and examples
-
IPAddr.new("224.0.0.0/4"), # IP multicast (former Class D network)
-
IPAddr.new("240.0.0.0/4"), # Reserved (former Class E network)
-
IPAddr.new("255.255.255.255"), # Broadcast
-
].freeze
-
-
IPV6_BLACKLIST = ([
-
6
IPAddr.new("::1/128"), # Loopback
-
IPAddr.new("64:ff9b::/96"), # IPv4/IPv6 translation (RFC 6052)
-
IPAddr.new("100::/64"), # Discard prefix (RFC 6666)
-
IPAddr.new("2001::/32"), # Teredo tunneling
-
IPAddr.new("2001:10::/28"), # Deprecated (previously ORCHID)
-
IPAddr.new("2001:20::/28"), # ORCHIDv2
-
IPAddr.new("2001:db8::/32"), # Addresses used in documentation and example source code
-
IPAddr.new("2002::/16"), # 6to4
-
IPAddr.new("fc00::/7"), # Unique local address
-
IPAddr.new("fe80::/10"), # Link-local address
-
IPAddr.new("ff00::/8"), # Multicast
-
] + IPV4_BLACKLIST.flat_map do |ipaddr|
-
96
prefixlen = ipaddr.prefixlen
-
-
96
ipv4_compatible = ipaddr.ipv4_compat.mask(96 + prefixlen)
-
96
ipv4_mapped = ipaddr.ipv4_mapped.mask(80 + prefixlen)
-
-
96
[ipv4_compatible, ipv4_mapped]
-
end).freeze
-
-
6
class << self
-
6
def extra_options(options)
-
54
options.merge(allowed_schemes: %w[https http])
-
end
-
-
6
def unsafe_ip_address?(ipaddr)
-
96
range = ipaddr.to_range
-
96
return true if range.first != range.last
-
-
108
return IPV6_BLACKLIST.any? { |r| r.include?(ipaddr) } if ipaddr.ipv6?
-
-
1140
IPV4_BLACKLIST.any? { |r| r.include?(ipaddr) } # then it's IPv4
-
end
-
end
-
-
# adds support for the following options:
-
#
-
# :allowed_schemes :: list of URI schemes allowed (defaults to <tt>["https", "http"]</tt>)
-
6
module OptionsMethods
-
6
def option_allowed_schemes(value)
-
60
Array(value)
-
end
-
end
-
-
6
module InstanceMethods
-
6
def send_requests(*requests)
-
66
responses = requests.map do |request|
-
66
next if @options.allowed_schemes.include?(request.uri.scheme)
-
-
6
error = ServerSideRequestForgeryError.new("#{request.uri} URI scheme not allowed")
-
6
error.set_backtrace(caller)
-
6
response = ErrorResponse.new(request, error)
-
6
request.emit(:response, response)
-
6
response
-
end
-
132
allowed_requests = requests.select { |req| responses[requests.index(req)].nil? }
-
66
allowed_responses = super(*allowed_requests)
-
66
allowed_responses.each_with_index do |res, idx|
-
60
req = allowed_requests[idx]
-
60
responses[requests.index(req)] = res
-
end
-
-
66
responses
-
end
-
end
-
-
6
module ConnectionMethods
-
6
def initialize(*)
-
begin
-
60
super
-
8
rescue ServerSideRequestForgeryError => e
-
# may raise when IPs are passed as options via :addresses
-
12
throw(:resolve_error, e)
-
end
-
end
-
-
6
def addresses=(addrs)
-
156
addrs = addrs.map { |addr| addr.is_a?(IPAddr) ? addr : IPAddr.new(addr) }
-
-
60
addrs.reject!(&SsrfFilter.method(:unsafe_ip_address?))
-
-
60
raise ServerSideRequestForgeryError, "#{@origin.host} has no public IP addresses" if addrs.empty?
-
-
12
super
-
end
-
end
-
end
-
-
6
register_plugin :ssrf_filter, SsrfFilter
-
end
-
end
-
# frozen_string_literal: true
-
-
12
module HTTPX
-
12
class StreamResponse
-
12
attr_reader :request
-
-
12
def initialize(request, session)
-
150
@request = request
-
150
@options = @request.options
-
150
@session = session
-
150
@response_enum = nil
-
150
@buffered_chunks = []
-
end
-
-
12
def each(&block)
-
246
return enum_for(__method__) unless block
-
-
162
if (response_enum = @response_enum)
-
12
@response_enum = nil
-
# streaming already started, let's finish it
-
-
36
while (chunk = @buffered_chunks.shift)
-
12
block.call(chunk)
-
end
-
-
# consume enum til the end
-
begin
-
47
while (chunk = response_enum.next)
-
23
block.call(chunk)
-
end
-
rescue StopIteration
-
12
return
-
end
-
end
-
-
150
@request.stream = self
-
-
begin
-
150
@on_chunk = block
-
-
150
response = @session.request(@request)
-
-
138
response.raise_for_status
-
ensure
-
138
@on_chunk = nil
-
end
-
end
-
-
12
def each_line
-
84
return enum_for(__method__) unless block_given?
-
-
42
line = "".b
-
-
42
each do |chunk|
-
40
line << chunk
-
-
122
while (idx = line.index("\n"))
-
42
yield line.byteslice(0..idx - 1)
-
-
42
line = line.byteslice(idx + 1..-1)
-
end
-
end
-
-
18
yield line unless line.empty?
-
end
-
-
# This is a ghost method. It's to be used ONLY internally, when processing streams
-
12
def on_chunk(chunk)
-
293
raise NoMethodError unless @on_chunk
-
-
293
@on_chunk.call(chunk)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id}>"
-
skipped
end
-
skipped
# :nocov:
-
-
12
def to_s
-
12
if @request.response
-
@request.response.to_s
-
else
-
12
@buffered_chunks.join
-
end
-
end
-
-
12
private
-
-
12
def response
-
324
@request.response || begin
-
24
response_enum = each
-
48
while (chunk = response_enum.next)
-
24
@buffered_chunks << chunk
-
24
break if @request.response
-
end
-
24
@response_enum = response_enum
-
24
@request.response
-
end
-
end
-
-
12
def respond_to_missing?(meth, include_private)
-
12
if (response = @request.response)
-
response.respond_to_missing?(meth, include_private)
-
else
-
12
@options.response_class.method_defined?(meth) || (include_private && @options.response_class.private_method_defined?(meth))
-
end || super
-
end
-
-
12
def method_missing(meth, *args, **kwargs, &block)
-
162
return super unless response.respond_to?(meth)
-
-
162
response.__send__(meth, *args, **kwargs, &block)
-
end
-
end
-
-
12
module Plugins
-
#
-
# This plugin adds support for streaming a response (useful for i.e. "text/event-stream" payloads).
-
#
-
# https://gitlab.com/os85/httpx/wikis/Stream
-
#
-
12
module Stream
-
12
def self.extra_options(options)
-
276
options.merge(timeout: { read_timeout: Float::INFINITY, operation_timeout: 60 })
-
end
-
-
12
module InstanceMethods
-
12
def request(*args, stream: false, **options)
-
426
return super(*args, **options) unless stream
-
-
162
requests = args.first.is_a?(Request) ? args : build_requests(*args, options)
-
162
raise Error, "only 1 response at a time is supported for streaming requests" unless requests.size == 1
-
-
150
request = requests.first
-
-
150
StreamResponse.new(request, self)
-
end
-
end
-
-
12
module RequestMethods
-
12
attr_accessor :stream
-
end
-
-
12
module ResponseMethods
-
12
def stream
-
258
request = @request.root_request if @request.respond_to?(:root_request)
-
258
request ||= @request
-
-
258
request.stream
-
end
-
end
-
-
12
module ResponseBodyMethods
-
12
def initialize(*)
-
258
super
-
258
@stream = @response.stream
-
end
-
-
12
def write(chunk)
-
416
return super unless @stream
-
-
333
return 0 if chunk.empty?
-
-
293
chunk = decode_chunk(chunk)
-
-
293
@stream.on_chunk(chunk.dup)
-
-
281
chunk.size
-
end
-
-
12
private
-
-
12
def transition(*)
-
107
return if @stream
-
-
107
super
-
end
-
end
-
end
-
12
register_plugin :stream, Stream
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for bidirectional HTTP/2 streams.
-
#
-
# https://gitlab.com/os85/httpx/wikis/StreamBidi
-
#
-
# It is required that the request body allows chunk to be buffered, (i.e., responds to +#<<(chunk)+).
-
6
module StreamBidi
-
# Extension of the Connection::HTTP2 class, which adds functionality to
-
# deal with a request that can't be drained and must be interleaved with
-
# the response streams.
-
#
-
# The streams keeps send DATA frames while there's data; when they're ain't,
-
# the stream is kept open; it must be explicitly closed by the end user.
-
#
-
6
class HTTP2Bidi < Connection::HTTP2
-
6
def initialize(*)
-
12
super
-
12
@lock = Thread::Mutex.new
-
end
-
-
6
%i[close empty? exhausted? send <<].each do |lock_meth|
-
30
class_eval(<<-METH, __FILE__, __LINE__ + 1)
-
# lock.aware version of +#{lock_meth}+
-
def #{lock_meth}(*) # def close(*)
-
return super if @lock.owned?
-
-
# small race condition between
-
# checking for ownership and
-
# acquiring lock.
-
# TODO: fix this at the parser.
-
@lock.synchronize { super }
-
end
-
METH
-
end
-
-
6
private
-
-
6
%i[join_headers join_trailers join_body].each do |lock_meth|
-
18
class_eval(<<-METH, __FILE__, __LINE__ + 1)
-
# lock.aware version of +#{lock_meth}+
-
def #{lock_meth}(*) # def join_headers(*)
-
return super if @lock.owned?
-
-
# small race condition between
-
# checking for ownership and
-
# acquiring lock.
-
# TODO: fix this at the parser.
-
@lock.synchronize { super }
-
end
-
METH
-
end
-
-
6
def handle_stream(stream, request)
-
12
request.on(:body) do
-
72
next unless request.headers_sent
-
-
60
handle(request, stream)
-
-
60
emit(:flush_buffer)
-
end
-
12
super
-
end
-
-
# when there ain't more chunks, it makes the buffer as full.
-
6
def send_chunk(request, stream, chunk, next_chunk)
-
72
super
-
-
72
return if next_chunk
-
-
72
request.transition(:waiting_for_chunk)
-
72
throw(:buffer_full)
-
end
-
-
# sets end-stream flag when the request is closed.
-
6
def end_stream?(request, next_chunk)
-
72
request.closed? && next_chunk.nil?
-
end
-
end
-
-
# BidiBuffer is a Buffer which can be receive data from threads othr
-
# than the thread of the corresponding Connection/Session.
-
#
-
# It synchronizes access to a secondary internal +@oob_buffer+, which periodically
-
# is reconciled to the main internal +@buffer+.
-
6
class BidiBuffer < Buffer
-
6
def initialize(*)
-
12
super
-
12
@parent_thread = Thread.current
-
12
@oob_mutex = Thread::Mutex.new
-
12
@oob_buffer = "".b
-
end
-
-
# buffers the +chunk+ to be sent
-
6
def <<(chunk)
-
132
return super if Thread.current == @parent_thread
-
-
60
@oob_mutex.synchronize { @oob_buffer << chunk }
-
end
-
-
# reconciles the main and secondary buffer (which receives data from other threads).
-
6
def rebuffer
-
800
raise Error, "can only rebuffer while waiting on a response" unless Thread.current == @parent_thread
-
-
800
@oob_mutex.synchronize do
-
800
@buffer << @oob_buffer
-
800
@oob_buffer.clear
-
end
-
end
-
end
-
-
# Proxy to wake up the session main loop when one
-
# of the connections has buffered data to write. It abides by the HTTPX::_Selectable API,
-
# which allows it to be registered in the selector alongside actual HTTP-based
-
# HTTPX::Connection objects.
-
6
class Signal
-
6
def initialize
-
12
@closed = false
-
12
@pipe_read, @pipe_write = ::IO.pipe
-
end
-
-
6
def state
-
191
@closed ? :closed : :open
-
end
-
-
# noop
-
6
def log(**); end
-
-
6
def to_io
-
382
@pipe_read.to_io
-
end
-
-
6
def wakeup
-
60
return if @closed
-
-
60
@pipe_write.write("\0")
-
end
-
-
6
def call
-
57
return if @closed
-
-
57
@pipe_read.readpartial(1)
-
end
-
-
6
def interests
-
191
return if @closed
-
-
191
:r
-
end
-
-
6
def timeout; end
-
-
6
def terminate
-
12
@pipe_write.close
-
12
@pipe_read.close
-
12
@closed = true
-
end
-
-
# noop (the owner connection will take of it)
-
6
def handle_socket_timeout(interval); end
-
end
-
-
6
class << self
-
6
def load_dependencies(klass)
-
12
klass.plugin(:stream)
-
end
-
-
6
def extra_options(options)
-
12
options.merge(fallback_protocol: "h2")
-
end
-
end
-
-
6
module InstanceMethods
-
6
def initialize(*)
-
12
@signal = Signal.new
-
12
super
-
end
-
-
6
def close(selector = Selector.new)
-
12
@signal.terminate
-
12
selector.deregister(@signal)
-
12
super(selector)
-
end
-
-
6
def select_connection(connection, selector)
-
24
super
-
24
selector.register(@signal)
-
24
connection.signal = @signal
-
end
-
-
6
def deselect_connection(connection, *)
-
12
super
-
12
connection.signal = nil
-
end
-
end
-
-
# Adds synchronization to request operations which may buffer payloads from different
-
# threads.
-
6
module RequestMethods
-
6
attr_accessor :headers_sent
-
-
6
def initialize(*)
-
12
super
-
12
@headers_sent = false
-
12
@closed = false
-
12
@mutex = Thread::Mutex.new
-
end
-
-
6
def closed?
-
72
@closed
-
end
-
-
6
def can_buffer?
-
170
super && @state != :waiting_for_chunk
-
end
-
-
# overrides state management transitions to introduce an intermediate
-
# +:waiting_for_chunk+ state, which the request transitions to once payload
-
# is buffered.
-
6
def transition(nextstate)
-
276
headers_sent = @headers_sent
-
-
276
case nextstate
-
when :waiting_for_chunk
-
72
return unless @state == :body
-
when :body
-
132
case @state
-
when :headers
-
12
headers_sent = true
-
when :waiting_for_chunk
-
# HACK: to allow super to pass through
-
60
@state = :headers
-
end
-
end
-
-
276
super.tap do
-
# delay setting this up until after the first transition to :body
-
276
@headers_sent = headers_sent
-
end
-
end
-
-
6
def <<(chunk)
-
60
@mutex.synchronize do
-
60
if @drainer
-
60
@body.clear if @body.respond_to?(:clear)
-
60
@drainer = nil
-
end
-
60
@body << chunk
-
-
60
transition(:body)
-
end
-
end
-
-
6
def close
-
12
@mutex.synchronize do
-
12
return if @closed
-
-
12
@closed = true
-
end
-
-
# last chunk to send which ends the stream
-
12
self << ""
-
end
-
end
-
-
6
module RequestBodyMethods
-
6
def initialize(*, **)
-
12
super
-
12
@headers.delete("content-length")
-
end
-
-
6
def empty?
-
84
false
-
end
-
end
-
-
# overrides the declaration of +@write_buffer+, which is now a thread-safe buffer
-
# responding to the same API.
-
6
module ConnectionMethods
-
6
attr_writer :signal
-
-
6
def initialize(*)
-
12
super
-
12
@write_buffer = BidiBuffer.new(@options.buffer_size)
-
end
-
-
# rebuffers the +@write_buffer+ before calculating interests.
-
6
def interests
-
800
@write_buffer.rebuffer
-
-
800
super
-
end
-
-
6
private
-
-
6
def parser_type(protocol)
-
12
return HTTP2Bidi if protocol == "h2"
-
-
super
-
end
-
-
6
def set_parser_callbacks(parser)
-
12
super
-
12
parser.on(:flush_buffer) do
-
60
@signal.wakeup if @signal
-
end
-
end
-
end
-
end
-
6
register_plugin :stream_bidi, StreamBidi
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin helps negotiating a new protocol from an HTTP/1.1 connection, via the
-
# Upgrade header.
-
#
-
# https://gitlab.com/os85/httpx/wikis/Upgrade
-
#
-
6
module Upgrade
-
6
class << self
-
6
def configure(klass)
-
24
klass.plugin(:"upgrade/h2")
-
end
-
-
6
def extra_options(options)
-
24
options.merge(upgrade_handlers: {})
-
end
-
end
-
-
6
module OptionsMethods
-
6
def option_upgrade_handlers(value)
-
66
raise TypeError, ":upgrade_handlers must be a Hash" unless value.is_a?(Hash)
-
-
66
value
-
end
-
end
-
-
6
module InstanceMethods
-
6
def fetch_response(request, selector, options)
-
224
response = super
-
-
224
if response
-
73
return response unless response.is_a?(Response)
-
-
73
return response unless response.headers.key?("upgrade")
-
-
31
upgrade_protocol = response.headers["upgrade"].split(/ *, */).first
-
-
31
return response unless upgrade_protocol && options.upgrade_handlers.key?(upgrade_protocol)
-
-
31
protocol_handler = options.upgrade_handlers[upgrade_protocol]
-
-
31
return response unless protocol_handler
-
-
31
log { "upgrading to #{upgrade_protocol}..." }
-
31
connection = find_connection(request.uri, selector, options)
-
-
# do not upgrade already upgraded connections
-
31
return if connection.upgrade_protocol == upgrade_protocol
-
-
24
protocol_handler.call(connection, request, response)
-
-
# keep in the loop if the server is switching, unless
-
# the connection has been hijacked, in which case you want
-
# to terminante immediately
-
24
return if response.status == 101 && !connection.hijacked
-
end
-
-
163
response
-
end
-
end
-
-
6
module ConnectionMethods
-
6
attr_reader :upgrade_protocol, :hijacked
-
-
6
def hijack_io
-
6
@hijacked = true
-
-
# connection is taken away from selector and not given back to the pool.
-
6
@current_session.deselect_connection(self, @current_selector, true)
-
end
-
end
-
end
-
6
register_plugin(:upgrade, Upgrade)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin adds support for upgrading an HTTP/1.1 connection to HTTP/2
-
# via an Upgrade: h2 response declaration
-
#
-
# https://gitlab.com/os85/httpx/wikis/Connection-Upgrade#h2
-
#
-
6
module H2
-
6
class << self
-
6
def extra_options(options)
-
24
options.merge(upgrade_handlers: options.upgrade_handlers.merge("h2" => self))
-
end
-
-
6
def call(connection, _request, _response)
-
6
connection.upgrade_to_h2
-
end
-
end
-
-
6
module ConnectionMethods
-
6
using URIExtensions
-
-
6
def upgrade_to_h2
-
6
prev_parser = @parser
-
-
6
if prev_parser
-
6
prev_parser.reset
-
6
@inflight -= prev_parser.requests.size
-
end
-
-
6
@parser = Connection::HTTP2.new(@write_buffer, @options)
-
6
set_parser_callbacks(@parser)
-
6
@upgrade_protocol = "h2"
-
-
# what's happening here:
-
# a deviation from the state machine is done to perform the actions when a
-
# connection is closed, without transitioning, so the connection is kept in the pool.
-
# the state is reset to initial, so that the socket reconnect works out of the box,
-
# while the parser is already here.
-
6
purge_after_closed
-
6
transition(:idle)
-
-
6
prev_parser.requests.each do |req|
-
req.transition(:idle)
-
send(req)
-
end
-
end
-
end
-
end
-
6
register_plugin(:"upgrade/h2", H2)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin implements convenience methods for performing WEBDAV requests.
-
#
-
# https://gitlab.com/os85/httpx/wikis/WebDav
-
#
-
6
module WebDav
-
6
def self.configure(klass)
-
72
klass.plugin(:xml)
-
end
-
-
6
module InstanceMethods
-
6
def copy(src, dest)
-
12
request("COPY", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
6
def move(src, dest)
-
12
request("MOVE", src, headers: { "destination" => @options.origin.merge(dest) })
-
end
-
-
6
def lock(path, timeout: nil, &blk)
-
36
headers = {}
-
36
headers["timeout"] = if timeout && timeout.positive?
-
12
"Second-#{timeout}"
-
else
-
24
"Infinite, Second-4100000000"
-
end
-
36
xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" \
-
"<D:lockinfo xmlns:D=\"DAV:\">" \
-
"<D:lockscope><D:exclusive/></D:lockscope>" \
-
"<D:locktype><D:write/></D:locktype>" \
-
"<D:owner>null</D:owner>" \
-
"</D:lockinfo>"
-
36
response = request("LOCK", path, headers: headers, xml: xml)
-
-
36
return response unless response.is_a?(Response)
-
-
36
return response unless blk && response.status == 200
-
-
12
lock_token = response.headers["lock-token"]
-
-
begin
-
12
blk.call(response)
-
ensure
-
12
unlock(path, lock_token)
-
end
-
-
12
response
-
end
-
-
6
def unlock(path, lock_token)
-
24
request("UNLOCK", path, headers: { "lock-token" => lock_token })
-
end
-
-
6
def mkcol(dir)
-
12
request("MKCOL", dir)
-
end
-
-
6
def propfind(path, xml = nil)
-
48
body = case xml
-
when :acl
-
12
'<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:prop><D:owner/>' \
-
"<D:supported-privilege-set/><D:current-user-privilege-set/><D:acl/></D:prop></D:propfind>"
-
when nil
-
24
'<?xml version="1.0" encoding="utf-8"?><DAV:propfind xmlns:DAV="DAV:"><DAV:allprop/></DAV:propfind>'
-
else
-
12
xml
-
end
-
-
48
request("PROPFIND", path, headers: { "depth" => "1" }, xml: body)
-
end
-
-
6
def proppatch(path, xml)
-
2
body = "<?xml version=\"1.0\"?>" \
-
10
"<D:propertyupdate xmlns:D=\"DAV:\" xmlns:Z=\"http://ns.example.com/standards/z39.50/\">#{xml}</D:propertyupdate>"
-
12
request("PROPPATCH", path, xml: body)
-
end
-
# %i[ orderpatch acl report search]
-
end
-
end
-
6
register_plugin(:webdav, WebDav)
-
end
-
end
-
# frozen_string_literal: true
-
-
6
module HTTPX
-
6
module Plugins
-
#
-
# This plugin supports request XML encoding/response decoding using the nokogiri gem.
-
#
-
# https://gitlab.com/os85/httpx/wikis/XML
-
#
-
6
module XML
-
6
MIME_TYPES = %r{\b(application|text)/(.+\+)?xml\b}.freeze
-
6
module Transcoder
-
6
module_function
-
-
6
class Encoder
-
6
def initialize(xml)
-
120
@raw = xml
-
end
-
-
6
def content_type
-
120
charset = @raw.respond_to?(:encoding) && @raw.encoding ? @raw.encoding.to_s.downcase : "utf-8"
-
120
"application/xml; charset=#{charset}"
-
end
-
-
6
def bytesize
-
384
@raw.to_s.bytesize
-
end
-
-
6
def to_s
-
120
@raw.to_s
-
end
-
end
-
-
6
def encode(xml)
-
120
Encoder.new(xml)
-
end
-
-
6
def decode(response)
-
18
content_type = response.content_type.mime_type
-
-
18
raise HTTPX::Error, "invalid form mime type (#{content_type})" unless MIME_TYPES.match?(content_type)
-
-
18
Nokogiri::XML.method(:parse)
-
end
-
end
-
-
6
class << self
-
6
def load_dependencies(*)
-
108
require "nokogiri"
-
end
-
end
-
-
6
module ResponseMethods
-
# decodes the response payload into a Nokogiri::XML::Node object **if** the payload is valid
-
# "application/xml" (requires the "nokogiri" gem).
-
6
def xml
-
12
decode(Transcoder)
-
end
-
end
-
-
6
module RequestBodyClassMethods
-
# ..., xml: Nokogiri::XML::Node #=> xml encoder
-
6
def initialize_body(params)
-
444
if (xml = params.delete(:xml))
-
# @type var xml: Nokogiri::XML::Node | String
-
120
return Transcoder.encode(xml)
-
end
-
-
324
super
-
end
-
end
-
end
-
-
6
register_plugin(:xml, XML)
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module ResponsePatternMatchExtensions
-
25
def deconstruct
-
25
[@status, @headers, @body]
-
end
-
-
25
def deconstruct_keys(_keys)
-
50
{ status: @status, headers: @headers, body: @body }
-
end
-
end
-
-
25
module ErrorResponsePatternMatchExtensions
-
25
def deconstruct
-
5
[@error]
-
end
-
-
25
def deconstruct_keys(_keys)
-
25
{ error: @error }
-
end
-
end
-
-
25
module HeadersPatternMatchExtensions
-
25
def deconstruct
-
5
to_a
-
end
-
end
-
-
25
Headers.include HeadersPatternMatchExtensions
-
25
Response.include ResponsePatternMatchExtensions
-
25
ErrorResponse.include ErrorResponsePatternMatchExtensions
-
end
-
# frozen_string_literal: true
-
-
25
require "httpx/selector"
-
25
require "httpx/connection"
-
25
require "httpx/resolver"
-
-
25
module HTTPX
-
25
class Pool
-
25
using ArrayExtensions::FilterMap
-
25
using URIExtensions
-
-
25
POOL_TIMEOUT = 5
-
-
# Sets up the connection pool with the given +options+, which can be the following:
-
#
-
# :max_connections:: the maximum number of connections held in the pool.
-
# :max_connections_per_origin :: the maximum number of connections held in the pool pointing to a given origin.
-
# :pool_timeout :: the number of seconds to wait for a connection to a given origin (before raising HTTPX::PoolTimeoutError)
-
#
-
25
def initialize(options)
-
8873
@max_connections = options.fetch(:max_connections, Float::INFINITY)
-
8873
@max_connections_per_origin = options.fetch(:max_connections_per_origin, Float::INFINITY)
-
8873
@pool_timeout = options.fetch(:pool_timeout, POOL_TIMEOUT)
-
14233
@resolvers = Hash.new { |hs, resolver_type| hs[resolver_type] = [] }
-
8873
@resolver_mtx = Thread::Mutex.new
-
8873
@connections = []
-
8873
@connection_mtx = Thread::Mutex.new
-
8873
@connections_counter = 0
-
8873
@max_connections_cond = ConditionVariable.new
-
8873
@origin_counters = Hash.new(0)
-
13609
@origin_conds = Hash.new { |hs, orig| hs[orig] = ConditionVariable.new }
-
end
-
-
# connections returned by this function are not expected to return to the connection pool.
-
25
def pop_connection
-
8964
@connection_mtx.synchronize do
-
8964
drop_connection
-
end
-
end
-
-
# opens a connection to the IP reachable through +uri+.
-
# Many hostnames are reachable through the same IP, so we try to
-
# maximize pipelining by opening as few connections as possible.
-
#
-
25
def checkout_connection(uri, options)
-
6287
return checkout_new_connection(uri, options) if options.io
-
-
6233
@connection_mtx.synchronize do
-
6233
acquire_connection(uri, options) || begin
-
5751
if @connections_counter == @max_connections
-
# this takes precedence over per-origin
-
12
@max_connections_cond.wait(@connection_mtx, @pool_timeout)
-
-
12
acquire_connection(uri, options) || begin
-
8
if @connections_counter == @max_connections
-
# if no matching usable connection was found, the pool will make room and drop a closed connection. if none is found,
-
# this means that all of them are persistent or being used, so raise a timeout error.
-
6
conn = @connections.find { |c| c.state == :closed }
-
-
raise PoolTimeoutError.new(@pool_timeout,
-
6
"Timed out after #{@pool_timeout} seconds while waiting for a connection") unless conn
-
-
drop_connection(conn)
-
end
-
end
-
end
-
-
5745
if @origin_counters[uri.origin] == @max_connections_per_origin
-
-
12
@origin_conds[uri.origin].wait(@connection_mtx, @pool_timeout)
-
-
12
return acquire_connection(uri, options) ||
-
raise(PoolTimeoutError.new(@pool_timeout,
-
"Timed out after #{@pool_timeout} seconds while waiting for a connection to #{uri.origin}"))
-
end
-
-
5733
@connections_counter += 1
-
5733
@origin_counters[uri.origin] += 1
-
-
5733
checkout_new_connection(uri, options)
-
end
-
end
-
end
-
-
25
def checkin_connection(connection)
-
6155
return if connection.options.io
-
-
6101
@connection_mtx.synchronize do
-
6101
@connections << connection
-
-
6101
@max_connections_cond.signal
-
6101
@origin_conds[connection.origin.to_s].signal
-
end
-
end
-
-
25
def checkout_mergeable_connection(connection)
-
5733
return if connection.options.io
-
-
5733
@connection_mtx.synchronize do
-
5733
idx = @connections.find_index do |ch|
-
180
ch != connection && ch.mergeable?(connection)
-
end
-
5733
@connections.delete_at(idx) if idx
-
end
-
end
-
-
25
def reset_resolvers
-
11150
@resolver_mtx.synchronize { @resolvers.clear }
-
end
-
-
25
def checkout_resolver(options)
-
5555
resolver_type = options.resolver_class
-
5555
resolver_type = Resolver.resolver_for(resolver_type)
-
-
5555
@resolver_mtx.synchronize do
-
5555
resolvers = @resolvers[resolver_type]
-
-
5555
idx = resolvers.find_index do |res|
-
26
res.options == options
-
end
-
5555
resolvers.delete_at(idx) if idx
-
end || checkout_new_resolver(resolver_type, options)
-
end
-
-
25
def checkin_resolver(resolver)
-
308
@resolver_mtx.synchronize do
-
308
resolvers = @resolvers[resolver.class]
-
-
308
resolver = resolver.multi
-
-
308
resolvers << resolver unless resolvers.include?(resolver)
-
end
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"@max_connections_per_origin=#{@max_connections_per_origin} " \
-
skipped
"@pool_timeout=#{@pool_timeout} " \
-
skipped
"@connections=#{@connections.size}>"
-
skipped
end
-
skipped
# :nocov:
-
-
25
private
-
-
25
def acquire_connection(uri, options)
-
6257
idx = @connections.find_index do |connection|
-
654
connection.match?(uri, options)
-
end
-
-
6257
return unless idx
-
-
492
@connections.delete_at(idx)
-
end
-
-
25
def checkout_new_connection(uri, options)
-
5787
options.connection_class.new(uri, options)
-
end
-
-
25
def checkout_new_resolver(resolver_type, options)
-
5533
if resolver_type.multi?
-
5508
Resolver::Multi.new(resolver_type, options)
-
else
-
25
resolver_type.new(options)
-
end
-
end
-
-
# drops and returns the +connection+ from the connection pool; if +connection+ is <tt>nil</tt> (default),
-
# the first available connection from the pool will be dropped.
-
25
def drop_connection(connection = nil)
-
8964
if connection
-
@connections.delete(connection)
-
else
-
8964
connection = @connections.shift
-
-
8964
return unless connection
-
end
-
-
3389
@connections_counter -= 1
-
3389
@origin_conds.delete(connection.origin) if (@origin_counters[connection.origin.to_s] -= 1).zero?
-
-
3389
connection
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Punycode
-
25
module_function
-
-
begin
-
25
require "idnx"
-
-
24
def encode_hostname(hostname)
-
24
Idnx.to_punycode(hostname)
-
end
-
rescue LoadError
-
1
def encode_hostname(hostname)
-
1
warn "#{hostname} cannot be converted to punycode. Install the " \
-
"\"idnx\" gem: https://github.com/HoneyryderChuck/idnx"
-
-
1
hostname
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "delegate"
-
25
require "forwardable"
-
-
25
module HTTPX
-
# Defines how an HTTP request is handled internally, both in terms of making attributes accessible,
-
# as well as maintaining the state machine which manages streaming the request onto the wire.
-
25
class Request
-
25
extend Forwardable
-
25
include Callbacks
-
25
using URIExtensions
-
-
25
ALLOWED_URI_SCHEMES = %w[https http].freeze
-
-
# default value used for "user-agent" header, when not overridden.
-
25
USER_AGENT = "httpx.rb/#{VERSION}".freeze # rubocop:disable Style/RedundantFreeze
-
-
# the upcased string HTTP verb for this request.
-
25
attr_reader :verb
-
-
# the absolute URI object for this request.
-
25
attr_reader :uri
-
-
# an HTTPX::Headers object containing the request HTTP headers.
-
25
attr_reader :headers
-
-
# an HTTPX::Request::Body object containing the request body payload (or +nil+, whenn there is none).
-
25
attr_reader :body
-
-
# a symbol describing which frame is currently being flushed.
-
25
attr_reader :state
-
-
# an HTTPX::Options object containing request options.
-
25
attr_reader :options
-
-
# the corresponding HTTPX::Response object, when there is one.
-
25
attr_reader :response
-
-
# Exception raised during enumerable body writes.
-
25
attr_reader :drain_error
-
-
# The IP address from the peer server.
-
25
attr_accessor :peer_address
-
-
25
attr_writer :persistent
-
-
25
attr_reader :active_timeouts
-
-
# will be +true+ when request body has been completely flushed.
-
25
def_delegator :@body, :empty?
-
-
# closes the body
-
25
def_delegator :@body, :close
-
-
# initializes the instance with the given +verb+ (an upppercase String, ex. 'GEt'),
-
# an absolute or relative +uri+ (either as String or URI::HTTP object), the
-
# request +options+ (instance of HTTPX::Options) and an optional Hash of +params+.
-
#
-
# Besides any of the options documented in HTTPX::Options (which would override or merge with what
-
# +options+ sets), it accepts also the following:
-
#
-
# :params :: hash or array of key-values which will be encoded and set in the query string of request uris.
-
# :body :: to be encoded in the request body payload. can be a String, an IO object (i.e. a File), or an Enumerable.
-
# :form :: hash of array of key-values which will be form-urlencoded- or multipart-encoded in requests body payload.
-
# :json :: hash of array of key-values which will be JSON-encoded in requests body payload.
-
# :xml :: Nokogiri XML nodes which will be encoded in requests body payload.
-
#
-
# :body, :form, :json and :xml are all mutually exclusive, i.e. only one of them gets picked up.
-
25
def initialize(verb, uri, options, params = EMPTY_HASH)
-
8100
@verb = verb.to_s.upcase
-
8100
@uri = Utils.to_uri(uri)
-
-
8099
@headers = options.headers.dup
-
8099
merge_headers(params.delete(:headers)) if params.key?(:headers)
-
-
8099
@headers["user-agent"] ||= USER_AGENT
-
8099
@headers["accept"] ||= "*/*"
-
-
# forego compression in the Range request case
-
8099
if @headers.key?("range")
-
6
@headers.delete("accept-encoding")
-
else
-
8093
@headers["accept-encoding"] ||= options.supported_compression_formats
-
end
-
-
8099
@query_params = params.delete(:params) if params.key?(:params)
-
-
8099
@body = options.request_body_class.new(@headers, options, **params)
-
-
8093
@options = @body.options
-
-
8093
if @uri.relative? || @uri.host.nil?
-
456
origin = @options.origin
-
456
raise(Error, "invalid URI: #{@uri}") unless origin
-
-
432
base_path = @options.base_path
-
-
432
@uri = origin.merge("#{base_path}#{@uri}")
-
end
-
-
8069
raise UnsupportedSchemeError, "#{@uri}: #{@uri.scheme}: unsupported URI scheme" unless ALLOWED_URI_SCHEMES.include?(@uri.scheme)
-
-
8057
@state = :idle
-
8057
@response = nil
-
8057
@peer_address = nil
-
8057
@ping = false
-
8057
@persistent = @options.persistent
-
8057
@active_timeouts = []
-
end
-
-
# whether request has been buffered with a ping
-
25
def ping?
-
376
@ping
-
end
-
-
# marks the request as having been buffered with a ping
-
25
def ping!
-
16
@ping = true
-
end
-
-
# the read timeout defined for this request.
-
25
def read_timeout
-
17297
@options.timeout[:read_timeout]
-
end
-
-
# the write timeout defined for this request.
-
25
def write_timeout
-
17297
@options.timeout[:write_timeout]
-
end
-
-
# the request timeout defined for this request.
-
25
def request_timeout
-
17083
@options.timeout[:request_timeout]
-
end
-
-
25
def persistent?
-
3889
@persistent
-
end
-
-
# if the request contains trailer headers
-
25
def trailers?
-
2450
defined?(@trailers)
-
end
-
-
# returns an instance of HTTPX::Headers containing the trailer headers
-
25
def trailers
-
66
@trailers ||= @options.headers_class.new
-
end
-
-
# returns +:r+ or +:w+, depending on whether the request is waiting for a response or flushing.
-
25
def interests
-
21340
return :r if @state == :done || @state == :expect
-
-
2582
:w
-
end
-
-
25
def can_buffer?
-
21092
@state != :done
-
end
-
-
# merges +h+ into the instance of HTTPX::Headers of the request.
-
25
def merge_headers(h)
-
877
@headers = @headers.merge(h)
-
end
-
-
# the URI scheme of the request +uri+.
-
25
def scheme
-
2868
@uri.scheme
-
end
-
-
# sets the +response+ on this request.
-
25
def response=(response)
-
7581
return unless response
-
-
7581
if response.is_a?(Response) && response.status < 200
-
# deal with informational responses
-
-
120
if response.status == 100 && @headers.key?("expect")
-
102
@informational_status = response.status
-
102
return
-
end
-
-
# 103 Early Hints advertises resources in document to browsers.
-
# not very relevant for an HTTP client, discard.
-
18
return if response.status >= 103
-
end
-
-
7479
@response = response
-
-
7479
emit(:response_started, response)
-
end
-
-
# returnns the URI path of the request +uri+.
-
25
def path
-
6891
path = uri.path.dup
-
6891
path = +"" if path.nil?
-
6891
path << "/" if path.empty?
-
6891
path << "?#{query}" unless query.empty?
-
6891
path
-
end
-
-
# returs the URI authority of the request.
-
#
-
# session.build_request("GET", "https://google.com/query").authority #=> "google.com"
-
# session.build_request("GET", "http://internal:3182/a").authority #=> "internal:3182"
-
25
def authority
-
6937
@uri.authority
-
end
-
-
# returs the URI origin of the request.
-
#
-
# session.build_request("GET", "https://google.com/query").authority #=> "https://google.com"
-
# session.build_request("GET", "http://internal:3182/a").authority #=> "http://internal:3182"
-
25
def origin
-
3088
@uri.origin
-
end
-
-
# returs the URI query string of the request (when available).
-
#
-
# session.build_request("GET", "https://search.com").query #=> ""
-
# session.build_request("GET", "https://search.com?q=a").query #=> "q=a"
-
# session.build_request("GET", "https://search.com", params: { q: "a"}).query #=> "q=a"
-
# session.build_request("GET", "https://search.com?q=a", params: { foo: "bar"}).query #=> "q=a&foo&bar"
-
25
def query
-
7676
return @query if defined?(@query)
-
-
6461
query = []
-
6461
if (q = @query_params) && !q.empty?
-
120
query << Transcoder::Form.encode(q)
-
end
-
6461
query << @uri.query if @uri.query
-
6461
@query = query.join("&")
-
end
-
-
# consumes and returns the next available chunk of request body that can be sent
-
25
def drain_body
-
7104
return nil if @body.nil?
-
-
7104
@drainer ||= @body.each
-
7104
chunk = @drainer.next.dup
-
-
4655
emit(:body_chunk, chunk)
-
4655
chunk
-
rescue StopIteration
-
2425
nil
-
rescue StandardError => e
-
24
@drain_error = e
-
24
nil
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"#{@verb} " \
-
skipped
"#{uri} " \
-
skipped
"@headers=#{@headers} " \
-
skipped
"@body=#{@body}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# moves on to the +nextstate+ of the request state machine (when all preconditions are met)
-
25
def transition(nextstate)
-
32756
case nextstate
-
when :idle
-
570
@body.rewind
-
570
@ping = false
-
570
@response = nil
-
570
@drainer = nil
-
570
@active_timeouts.clear
-
when :headers
-
8845
return unless @state == :idle
-
-
when :body
-
8893
return unless @state == :headers ||
-
@state == :expect
-
-
7260
if @headers.key?("expect")
-
396
if @informational_status && @informational_status == 100
-
# check for 100 Continue response, and deallocate the var
-
# if @informational_status == 100
-
# @response = nil
-
# end
-
else
-
303
return if @state == :expect # do not re-set it
-
-
108
nextstate = :expect
-
end
-
end
-
when :trailers
-
7185
return unless @state == :body
-
when :done
-
7191
return if @state == :expect
-
-
end
-
28377
@state = nextstate
-
28377
emit(@state, self)
-
6878
nil
-
end
-
-
# whether the request supports the 100-continue handshake and already processed the 100 response.
-
25
def expects?
-
6494
@headers["expect"] == "100-continue" && @informational_status == 100 && !@response
-
end
-
-
25
def set_timeout_callback(event, &callback)
-
86732
clb = once(event, &callback)
-
-
# reset timeout callbacks when requests get rerouted to a different connection
-
86732
once(:idle) do
-
2710
callbacks(event).delete(clb)
-
end
-
end
-
end
-
end
-
-
25
require_relative "request/body"
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
# Implementation of the HTTP Request body as a delegator which iterates (responds to +each+) payload chunks.
-
25
class Request::Body < SimpleDelegator
-
25
class << self
-
25
def new(_, options, body: nil, **params)
-
8105
if body.is_a?(self)
-
# request derives its options from body
-
12
body.options = options.merge(params)
-
12
return body
-
end
-
-
8093
super
-
end
-
end
-
-
25
attr_accessor :options
-
-
# inits the instance with the request +headers+, +options+ and +params+, which contain the payload definition.
-
# it wraps the given body with the appropriate encoder on initialization.
-
#
-
# ..., json: { foo: "bar" }) #=> json encoder
-
# ..., form: { foo: "bar" }) #=> form urlencoded encoder
-
# ..., form: { foo: Pathname.open("path/to/file") }) #=> multipart urlencoded encoder
-
# ..., form: { foo: File.open("path/to/file") }) #=> multipart urlencoded encoder
-
# ..., form: { body: "bla") }) #=> raw data encoder
-
25
def initialize(h, options, **params)
-
8093
@headers = h
-
8093
@body = self.class.initialize_body(params)
-
8093
@options = options.merge(params)
-
-
8093
if @body
-
2464
if @options.compress_request_body && @headers.key?("content-encoding")
-
-
78
@headers.get("content-encoding").each do |encoding|
-
78
@body = self.class.initialize_deflater_body(@body, encoding)
-
end
-
end
-
-
2464
@headers["content-type"] ||= @body.content_type
-
2464
@headers["content-length"] = @body.bytesize unless unbounded_body?
-
end
-
-
8087
super(@body)
-
end
-
-
# consumes and yields the request payload in chunks.
-
25
def each(&block)
-
5084
return enum_for(__method__) unless block
-
2545
return if @body.nil?
-
-
2491
body = stream(@body)
-
2491
if body.respond_to?(:read)
-
4735
while (chunk = body.read(16_384))
-
2571
block.call(chunk)
-
end
-
# TODO: use copy_stream once bug is resolved: https://bugs.ruby-lang.org/issues/21131
-
# ::IO.copy_stream(body, ProcIO.new(block))
-
1406
elsif body.respond_to?(:each)
-
396
body.each(&block)
-
else
-
1010
block[body.to_s]
-
end
-
end
-
-
25
def close
-
362
@body.close if @body.respond_to?(:close)
-
end
-
-
# if the +@body+ is rewindable, it rewinnds it.
-
25
def rewind
-
618
return if empty?
-
-
132
@body.rewind if @body.respond_to?(:rewind)
-
end
-
-
# return +true+ if the +body+ has been fully drained (or does nnot exist).
-
25
def empty?
-
15176
return true if @body.nil?
-
6733
return false if chunked?
-
-
6661
@body.bytesize.zero?
-
end
-
-
# returns the +@body+ payload size in bytes.
-
25
def bytesize
-
2815
return 0 if @body.nil?
-
-
96
@body.bytesize
-
end
-
-
# sets the body to yield using chunked trannsfer encoding format.
-
25
def stream(body)
-
2491
return body unless chunked?
-
-
72
Transcoder::Chunker.encode(body.enum_for(:each))
-
end
-
-
# returns whether the body yields infinitely.
-
25
def unbounded_body?
-
2866
return @unbounded_body if defined?(@unbounded_body)
-
-
2518
@unbounded_body = !@body.nil? && (chunked? || @body.bytesize == Float::INFINITY)
-
end
-
-
# returns whether the chunked transfer encoding header is set.
-
25
def chunked?
-
15751
@headers["transfer-encoding"] == "chunked"
-
end
-
-
# sets the chunked transfer encoding header.
-
25
def chunk!
-
24
@headers.add("transfer-encoding", "chunked")
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"#{unbounded_body? ? "stream" : "@bytesize=#{bytesize}"}>"
-
skipped
end
-
skipped
# :nocov:
-
-
25
class << self
-
25
def initialize_body(params)
-
7973
if (body = params.delete(:body))
-
# @type var body: bodyIO
-
1142
Transcoder::Body.encode(body)
-
6831
elsif (form = params.delete(:form))
-
# @type var form: Transcoder::urlencoded_input
-
1139
Transcoder::Form.encode(form)
-
5692
elsif (json = params.delete(:json))
-
# @type var body: _ToJson
-
63
Transcoder::JSON.encode(json)
-
end
-
end
-
-
# returns the +body+ wrapped with the correct deflater accordinng to the given +encodisng+.
-
25
def initialize_deflater_body(body, encoding)
-
78
case encoding
-
when "gzip"
-
42
Transcoder::GZIP.encode(body)
-
when "deflate"
-
18
Transcoder::Deflate.encode(body)
-
when "identity"
-
12
body
-
else
-
6
body
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "resolv"
-
25
require "ipaddr"
-
-
25
module HTTPX
-
25
module Resolver
-
25
RESOLVE_TIMEOUT = [2, 3].freeze
-
-
25
require "httpx/resolver/resolver"
-
25
require "httpx/resolver/system"
-
25
require "httpx/resolver/native"
-
25
require "httpx/resolver/https"
-
25
require "httpx/resolver/multi"
-
-
25
@lookup_mutex = Thread::Mutex.new
-
179
@lookups = Hash.new { |h, k| h[k] = [] }
-
-
25
@identifier_mutex = Thread::Mutex.new
-
25
@identifier = 1
-
25
@system_resolver = Resolv::Hosts.new
-
-
25
module_function
-
-
25
def resolver_for(resolver_type)
-
5591
case resolver_type
-
5416
when :native then Native
-
31
when :system then System
-
72
when :https then HTTPS
-
else
-
72
return resolver_type if resolver_type.is_a?(Class) && resolver_type < Resolver
-
-
6
raise Error, "unsupported resolver type (#{resolver_type})"
-
end
-
end
-
-
25
def nolookup_resolve(hostname)
-
5400
ip_resolve(hostname) || cached_lookup(hostname) || system_resolve(hostname)
-
end
-
-
25
def ip_resolve(hostname)
-
5400
[IPAddr.new(hostname)]
-
rescue ArgumentError
-
end
-
-
25
def system_resolve(hostname)
-
512
ips = @system_resolver.getaddresses(hostname)
-
512
return if ips.empty?
-
-
714
ips.map { |ip| IPAddr.new(ip) }
-
rescue IOError
-
end
-
-
25
def cached_lookup(hostname)
-
4995
now = Utils.now
-
4995
lookup_synchronize do |lookups|
-
4995
lookup(hostname, lookups, now)
-
end
-
end
-
-
25
def cached_lookup_set(hostname, family, entries)
-
184
now = Utils.now
-
184
entries.each do |entry|
-
256
entry["TTL"] += now
-
end
-
184
lookup_synchronize do |lookups|
-
184
case family
-
when Socket::AF_INET6
-
30
lookups[hostname].concat(entries)
-
when Socket::AF_INET
-
154
lookups[hostname].unshift(*entries)
-
end
-
184
entries.each do |entry|
-
256
next unless entry["name"] != hostname
-
-
28
case family
-
when Socket::AF_INET6
-
6
lookups[entry["name"]] << entry
-
when Socket::AF_INET
-
22
lookups[entry["name"]].unshift(entry)
-
end
-
end
-
end
-
end
-
-
# do not use directly!
-
25
def lookup(hostname, lookups, ttl)
-
5001
return unless lookups.key?(hostname)
-
-
4487
entries = lookups[hostname] = lookups[hostname].select do |address|
-
10533
address["TTL"] > ttl
-
end
-
-
4487
ips = entries.flat_map do |address|
-
10511
if (als = address["alias"])
-
6
lookup(als, lookups, ttl)
-
else
-
10505
IPAddr.new(address["data"])
-
end
-
end.compact
-
-
4487
ips unless ips.empty?
-
end
-
-
25
def generate_id
-
1466
id_synchronize { @identifier = (@identifier + 1) & 0xFFFF }
-
end
-
-
25
def encode_dns_query(hostname, type: Resolv::DNS::Resource::IN::A, message_id: generate_id)
-
733
Resolv::DNS::Message.new(message_id).tap do |query|
-
733
query.rd = 1
-
733
query.add_question(hostname, type)
-
end.encode
-
end
-
-
25
def decode_dns_answer(payload)
-
begin
-
652
message = Resolv::DNS::Message.decode(payload)
-
rescue Resolv::DNS::DecodeError => e
-
6
return :decode_error, e
-
end
-
-
# no domain was found
-
646
return :no_domain_found if message.rcode == Resolv::DNS::RCode::NXDomain
-
-
226
return :message_truncated if message.tc == 1
-
-
214
return :dns_error, message.rcode if message.rcode != Resolv::DNS::RCode::NoError
-
-
208
addresses = []
-
-
208
message.each_answer do |question, _, value|
-
1000
case value
-
when Resolv::DNS::Resource::IN::CNAME
-
18
addresses << {
-
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"alias" => value.name.to_s,
-
}
-
when Resolv::DNS::Resource::IN::A,
-
Resolv::DNS::Resource::IN::AAAA
-
982
addresses << {
-
"name" => question.to_s,
-
"TTL" => value.ttl,
-
"data" => value.address.to_s,
-
}
-
end
-
end
-
-
208
[:ok, addresses]
-
end
-
-
25
def lookup_synchronize
-
10358
@lookup_mutex.synchronize { yield(@lookups) }
-
end
-
-
25
def id_synchronize(&block)
-
733
@identifier_mutex.synchronize(&block)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "resolv"
-
25
require "uri"
-
25
require "forwardable"
-
25
require "httpx/base64"
-
-
25
module HTTPX
-
# Implementation of a DoH name resolver (https://www.youtube.com/watch?v=unMXvnY2FNM).
-
# It wraps an HTTPX::Connection object which integrates with the main session in the
-
# same manner as other performed HTTP requests.
-
#
-
25
class Resolver::HTTPS < Resolver::Resolver
-
25
extend Forwardable
-
25
using URIExtensions
-
-
25
module DNSExtensions
-
25
refine Resolv::DNS do
-
25
def generate_candidates(name)
-
42
@config.generate_candidates(name)
-
end
-
end
-
end
-
25
using DNSExtensions
-
-
25
NAMESERVER = "https://1.1.1.1/dns-query"
-
-
DEFAULTS = {
-
25
uri: NAMESERVER,
-
use_get: false,
-
}.freeze
-
-
25
def_delegators :@resolver_connection, :state, :connecting?, :to_io, :call, :close, :terminate, :inflight?, :handle_socket_timeout
-
-
25
def initialize(_, options)
-
90
super
-
90
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
90
@queries = {}
-
90
@requests = {}
-
90
@uri = URI(@resolver_options[:uri])
-
90
@uri_addresses = nil
-
90
@resolver = Resolv::DNS.new
-
90
@resolver.timeouts = @resolver_options.fetch(:timeouts, Resolver::RESOLVE_TIMEOUT)
-
90
@resolver.lazy_initialize
-
end
-
-
25
def <<(connection)
-
90
return if @uri.origin == connection.peer.to_s
-
-
48
@uri_addresses ||= HTTPX::Resolver.nolookup_resolve(@uri.host) || @resolver.getaddresses(@uri.host)
-
-
48
if @uri_addresses.empty?
-
6
ex = ResolveError.new("Can't resolve DNS server #{@uri.host}")
-
6
ex.set_backtrace(caller)
-
6
connection.force_reset
-
6
throw(:resolve_error, ex)
-
end
-
-
42
resolve(connection)
-
end
-
-
25
def closed?
-
true
-
end
-
-
25
def empty?
-
84
true
-
end
-
-
25
def resolver_connection
-
# TODO: leaks connection object into the pool
-
66
@resolver_connection ||= @current_session.find_connection(@uri, @current_selector,
-
@options.merge(ssl: { alpn_protocols: %w[h2] })).tap do |conn|
-
42
emit_addresses(conn, @family, @uri_addresses) unless conn.addresses
-
end
-
end
-
-
25
private
-
-
25
def resolve(connection = nil, hostname = nil)
-
66
@connections.shift until @connections.empty? || @connections.first.state != :closed
-
-
66
connection ||= @connections.first
-
-
66
return unless connection
-
-
66
hostname ||= @queries.key(connection)
-
-
66
if hostname.nil?
-
42
hostname = connection.peer.host
-
log do
-
"resolver #{FAMILY_TYPES[@record_type]}: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
-
42
end if connection.peer.non_ascii_hostname
-
-
42
hostname = @resolver.generate_candidates(hostname).each do |name|
-
126
@queries[name.to_s] = connection
-
end.first.to_s
-
else
-
24
@queries[hostname] = connection
-
end
-
66
log { "resolver #{FAMILY_TYPES[@record_type]}: query for #{hostname}" }
-
-
begin
-
66
request = build_request(hostname)
-
66
request.on(:response, &method(:on_response).curry(2)[request])
-
66
request.on(:promise, &method(:on_promise))
-
66
@requests[request] = hostname
-
66
resolver_connection.send(request)
-
66
@connections << connection
-
rescue ResolveError, Resolv::DNS::EncodeError => e
-
reset_hostname(hostname)
-
emit_resolve_error(connection, connection.peer.host, e)
-
end
-
end
-
-
25
def on_response(request, response)
-
66
response.raise_for_status
-
rescue StandardError => e
-
6
hostname = @requests.delete(request)
-
6
connection = reset_hostname(hostname)
-
6
emit_resolve_error(connection, connection.peer.host, e)
-
else
-
# @type var response: HTTPX::Response
-
60
parse(request, response)
-
ensure
-
66
@requests.delete(request)
-
end
-
-
25
def on_promise(_, stream)
-
log(level: 2) { "#{stream.id}: refusing stream!" }
-
stream.refuse
-
end
-
-
25
def parse(request, response)
-
60
code, result = decode_response_body(response)
-
-
60
case code
-
when :ok
-
18
parse_addresses(result, request)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
-
36
host = @requests.delete(request)
-
36
connection = reset_hostname(host, reset_candidates: false)
-
-
36
unless @queries.value?(connection)
-
12
emit_resolve_error(connection)
-
12
return
-
end
-
-
24
resolve
-
when :dns_error
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
-
emit_resolve_error(connection)
-
when :decode_error
-
6
host = @requests.delete(request)
-
6
connection = reset_hostname(host)
-
6
emit_resolve_error(connection, connection.peer.host, result)
-
end
-
end
-
-
25
def parse_addresses(answers, request)
-
18
if answers.empty?
-
# no address found, eliminate candidates
-
host = @requests.delete(request)
-
connection = reset_hostname(host)
-
emit_resolve_error(connection)
-
return
-
-
else
-
42
answers = answers.group_by { |answer| answer["name"] }
-
18
answers.each do |hostname, addresses|
-
24
addresses = addresses.flat_map do |address|
-
24
if address.key?("alias")
-
6
alias_address = answers[address["alias"]]
-
6
if alias_address.nil?
-
reset_hostname(address["name"])
-
if early_resolve(connection, hostname: address["alias"])
-
@connections.delete(connection)
-
else
-
resolve(connection, address["alias"])
-
return # rubocop:disable Lint/NonLocalExitFromIterator
-
end
-
else
-
6
alias_address
-
end
-
else
-
18
address
-
end
-
end.compact
-
24
next if addresses.empty?
-
-
24
hostname.delete_suffix!(".") if hostname.end_with?(".")
-
24
connection = reset_hostname(hostname, reset_candidates: false)
-
24
next unless connection # probably a retried query for which there's an answer
-
-
18
@connections.delete(connection)
-
-
# eliminate other candidates
-
54
@queries.delete_if { |_, conn| connection == conn }
-
-
18
Resolver.cached_lookup_set(hostname, @family, addresses) if @resolver_options[:cache]
-
54
catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
-
end
-
end
-
18
return if @connections.empty?
-
-
resolve
-
end
-
-
25
def build_request(hostname)
-
60
uri = @uri.dup
-
60
rklass = @options.request_class
-
60
payload = Resolver.encode_dns_query(hostname, type: @record_type)
-
-
60
if @resolver_options[:use_get]
-
6
params = URI.decode_www_form(uri.query.to_s)
-
6
params << ["type", FAMILY_TYPES[@record_type]]
-
6
params << ["dns", Base64.urlsafe_encode64(payload, padding: false)]
-
6
uri.query = URI.encode_www_form(params)
-
6
request = rklass.new("GET", uri, @options)
-
else
-
54
request = rklass.new("POST", uri, @options, body: [payload])
-
54
request.headers["content-type"] = "application/dns-message"
-
end
-
60
request.headers["accept"] = "application/dns-message"
-
60
request
-
end
-
-
25
def decode_response_body(response)
-
54
case response.headers["content-type"]
-
when "application/dns-udpwireformat",
-
"application/dns-message"
-
54
Resolver.decode_dns_answer(response.to_s)
-
else
-
raise Error, "unsupported DNS mime-type (#{response.headers["content-type"]})"
-
end
-
end
-
-
25
def reset_hostname(hostname, reset_candidates: true)
-
72
connection = @queries.delete(hostname)
-
-
72
return connection unless connection && reset_candidates
-
-
# eliminate other candidates
-
36
candidates = @queries.select { |_, conn| connection == conn }.keys
-
36
@queries.delete_if { |h, _| candidates.include?(h) }
-
-
12
connection
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "forwardable"
-
25
require "resolv"
-
-
25
module HTTPX
-
25
class Resolver::Multi
-
25
include Callbacks
-
25
using ArrayExtensions::FilterMap
-
-
25
attr_reader :resolvers, :options
-
-
25
def initialize(resolver_type, options)
-
5508
@current_selector = nil
-
5508
@current_session = nil
-
5508
@options = options
-
5508
@resolver_options = @options.resolver_options
-
-
5508
@resolvers = options.ip_families.map do |ip_family|
-
5508
resolver = resolver_type.new(ip_family, options)
-
5508
resolver.multi = self
-
5508
resolver
-
end
-
-
5508
@errors = Hash.new { |hs, k| hs[k] = [] }
-
end
-
-
25
def current_selector=(s)
-
5530
@current_selector = s
-
11060
@resolvers.each { |r| r.__send__(__method__, s) }
-
end
-
-
25
def current_session=(s)
-
5530
@current_session = s
-
11060
@resolvers.each { |r| r.__send__(__method__, s) }
-
end
-
-
25
def closed?
-
@resolvers.all?(&:closed?)
-
end
-
-
25
def empty?
-
@resolvers.all?(&:empty?)
-
end
-
-
25
def inflight?
-
@resolvers.any(&:inflight?)
-
end
-
-
25
def timeout
-
@resolvers.filter_map(&:timeout).min
-
end
-
-
25
def close
-
@resolvers.each(&:close)
-
end
-
-
25
def connections
-
@resolvers.filter_map { |r| r.resolver_connection if r.respond_to?(:resolver_connection) }
-
end
-
-
25
def early_resolve(connection)
-
5532
hostname = connection.peer.host
-
5532
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
5532
return false unless addresses
-
-
5126
resolved = false
-
5364
addresses.group_by(&:family).sort { |(f1, _), (f2, _)| f2 <=> f1 }.each do |family, addrs|
-
# try to match the resolver by family. However, there are cases where that's not possible, as when
-
# the system does not have IPv6 connectivity, but it does support IPv6 via loopback/link-local.
-
10704
resolver = @resolvers.find { |r| r.family == family } || @resolvers.first
-
-
5352
next unless resolver # this should ever happen
-
-
# it does not matter which resolver it is, as early-resolve code is shared.
-
5352
resolver.emit_addresses(connection, family, addrs, true)
-
-
5322
resolved = true
-
end
-
-
5096
resolved
-
end
-
-
25
def lazy_resolve(connection)
-
406
@resolvers.each do |resolver|
-
406
resolver << @current_session.try_clone_connection(connection, @current_selector, resolver.family)
-
394
next if resolver.empty?
-
-
310
@current_session.select_resolver(resolver, @current_selector)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "forwardable"
-
25
require "resolv"
-
-
25
module HTTPX
-
# Implements a pure ruby name resolver, which abides by the Selectable API.
-
# It delegates DNS payload encoding/decoding to the +resolv+ stlid gem.
-
#
-
25
class Resolver::Native < Resolver::Resolver
-
25
extend Forwardable
-
25
using URIExtensions
-
-
15
DEFAULTS = {
-
10
nameserver: nil,
-
**Resolv::DNS::Config.default_config_hash,
-
packet_size: 512,
-
timeouts: Resolver::RESOLVE_TIMEOUT,
-
}.freeze
-
-
25
DNS_PORT = 53
-
-
25
def_delegator :@connections, :empty?
-
-
25
attr_reader :state
-
-
25
def initialize(family, options)
-
5418
super
-
5418
@ns_index = 0
-
5418
@resolver_options = DEFAULTS.merge(@options.resolver_options)
-
5418
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
5418
@nameserver = if (nameserver = @resolver_options[:nameserver])
-
5412
nameserver = nameserver[family] if nameserver.is_a?(Hash)
-
5412
Array(nameserver)
-
end
-
5418
@ndots = @resolver_options.fetch(:ndots, 1)
-
16254
@search = Array(@resolver_options[:search]).map { |srch| srch.scan(/[^.]+/) }
-
5418
@_timeouts = Array(@resolver_options[:timeouts])
-
6730
@timeouts = Hash.new { |timeouts, host| timeouts[host] = @_timeouts.dup }
-
5418
@name = nil
-
5418
@queries = {}
-
5418
@read_buffer = "".b
-
5418
@write_buffer = Buffer.new(@resolver_options[:packet_size])
-
5418
@state = :idle
-
end
-
-
25
def close
-
308
transition(:closed)
-
end
-
-
25
def terminate
-
12
emit(:close, self)
-
end
-
-
25
def closed?
-
646
@state == :closed
-
end
-
-
25
def to_io
-
1014
@io.to_io
-
end
-
-
25
def call
-
893
case @state
-
when :open
-
887
consume
-
end
-
end
-
-
25
def interests
-
11373
case @state
-
when :idle
-
10709
transition(:open)
-
when :closed
-
12
transition(:idle)
-
12
transition(:open)
-
end
-
-
11373
calculate_interests
-
end
-
-
25
def <<(connection)
-
316
if @nameserver.nil?
-
6
ex = ResolveError.new("No available nameserver")
-
6
ex.set_backtrace(caller)
-
6
connection.force_reset
-
6
throw(:resolve_error, ex)
-
else
-
310
@connections << connection
-
310
resolve
-
end
-
end
-
-
25
def timeout
-
11373
return if @connections.empty?
-
-
11373
@start_timeout = Utils.now
-
11373
hosts = @queries.keys
-
11373
@timeouts.values_at(*hosts).reject(&:empty?).map(&:first).min
-
end
-
-
25
def handle_socket_timeout(interval); end
-
-
25
private
-
-
25
def calculate_interests
-
15142
return :w unless @write_buffer.empty?
-
-
13673
return :r unless @queries.empty?
-
-
195
nil
-
end
-
-
25
def consume
-
899
loop do
-
1566
dread if calculate_interests == :r
-
-
1536
break unless calculate_interests == :w
-
-
# do_retry
-
685
dwrite
-
-
667
break unless calculate_interests == :r
-
end
-
rescue Errno::EHOSTUNREACH => e
-
18
@ns_index += 1
-
18
nameserver = @nameserver
-
18
if nameserver && @ns_index < nameserver.size
-
12
log { "resolver #{FAMILY_TYPES[@record_type]}: failed resolving on nameserver #{@nameserver[@ns_index - 1]} (#{e.message})" }
-
12
transition(:idle)
-
12
@timeouts.clear
-
12
retry
-
else
-
6
handle_error(e)
-
6
emit(:close, self)
-
end
-
rescue NativeResolveError => e
-
18
handle_error(e)
-
18
close_or_resolve
-
18
retry unless closed?
-
end
-
-
25
def schedule_retry
-
667
h = @name
-
-
667
return unless h
-
-
667
connection = @queries[h]
-
-
667
timeouts = @timeouts[h]
-
667
timeout = timeouts.shift
-
-
667
@timer = @current_selector.after(timeout) do
-
69
next unless @connections.include?(connection)
-
-
69
do_retry(h, connection, timeout)
-
end
-
end
-
-
25
def do_retry(h, connection, interval)
-
69
timeouts = @timeouts[h]
-
-
69
if !timeouts.empty?
-
39
log { "resolver #{FAMILY_TYPES[@record_type]}: timeout after #{interval}s, retry (with #{timeouts.first}s) #{h}..." }
-
# must downgrade to tcp AND retry on same host as last
-
39
downgrade_socket
-
39
resolve(connection, h)
-
30
elsif @ns_index + 1 < @nameserver.size
-
# try on the next nameserver
-
6
@ns_index += 1
-
6
log do
-
"resolver #{FAMILY_TYPES[@record_type]}: failed resolving #{h} on nameserver #{@nameserver[@ns_index - 1]} (timeout error)"
-
end
-
6
transition(:idle)
-
6
@timeouts.clear
-
6
resolve(connection, h)
-
else
-
-
24
@timeouts.delete(h)
-
24
reset_hostname(h, reset_candidates: false)
-
-
24
unless @queries.empty?
-
18
resolve(connection)
-
18
return
-
end
-
-
6
@connections.delete(connection)
-
-
6
host = connection.peer.host
-
-
# This loop_time passed to the exception is bogus. Ideally we would pass the total
-
# resolve timeout, including from the previous retries.
-
6
ex = ResolveTimeoutError.new(interval, "Timed out while resolving #{host}")
-
6
ex.set_backtrace(ex ? ex.backtrace : caller)
-
6
emit_resolve_error(connection, host, ex)
-
-
6
close_or_resolve
-
end
-
end
-
-
25
def dread(wsize = @resolver_options[:packet_size])
-
1171
loop do
-
1183
wsize = @large_packet.capacity if @large_packet
-
-
1183
siz = @io.read(wsize, @read_buffer)
-
-
1183
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
1183
return unless siz.positive?
-
-
610
if @socket_type == :tcp
-
# packet may be incomplete, need to keep draining from the socket
-
30
if @large_packet
-
# large packet buffer already exists, continue pumping
-
12
@large_packet << @read_buffer
-
-
12
next unless @large_packet.full?
-
-
12
parse(@large_packet.to_s)
-
12
@large_packet = nil
-
# downgrade to udp again
-
12
downgrade_socket
-
12
return
-
else
-
18
size = @read_buffer[0, 2].unpack1("n")
-
18
buffer = @read_buffer.byteslice(2..-1)
-
-
18
if size > @read_buffer.bytesize
-
# only do buffer logic if it's worth it, and the whole packet isn't here already
-
12
@large_packet = Buffer.new(size)
-
12
@large_packet << buffer
-
-
12
next
-
else
-
6
parse(buffer)
-
end
-
end
-
else # udp
-
580
parse(@read_buffer)
-
end
-
-
556
return if @state == :closed || !@write_buffer.empty?
-
end
-
end
-
-
25
def dwrite
-
667
loop do
-
1334
return if @write_buffer.empty?
-
-
667
siz = @io.write(@write_buffer)
-
-
667
unless siz
-
ex = EOFError.new("descriptor closed")
-
ex.set_backtrace(caller)
-
raise ex
-
end
-
-
667
return unless siz.positive?
-
-
667
schedule_retry if @write_buffer.empty?
-
-
667
return if @state == :closed
-
end
-
end
-
-
25
def parse(buffer)
-
598
@timer.cancel
-
-
598
code, result = Resolver.decode_dns_answer(buffer)
-
-
598
case code
-
when :ok
-
190
parse_addresses(result)
-
when :no_domain_found
-
# Indicates no such domain was found.
-
384
hostname, connection = @queries.first
-
384
reset_hostname(hostname, reset_candidates: false)
-
-
672
other_candidate, _ = @queries.find { |_, conn| conn == connection }
-
-
384
if other_candidate
-
288
resolve(connection, other_candidate)
-
else
-
96
@connections.delete(connection)
-
96
ex = NativeResolveError.new(connection, connection.peer.host, "name or service not known")
-
96
ex.set_backtrace(ex ? ex.backtrace : caller)
-
96
emit_resolve_error(connection, connection.peer.host, ex)
-
84
close_or_resolve
-
end
-
when :message_truncated
-
# TODO: what to do if it's already tcp??
-
12
return if @socket_type == :tcp
-
-
12
@socket_type = :tcp
-
-
12
hostname, _ = @queries.first
-
12
reset_hostname(hostname)
-
12
transition(:closed)
-
when :dns_error
-
6
hostname, connection = @queries.first
-
6
reset_hostname(hostname)
-
6
@connections.delete(connection)
-
6
ex = NativeResolveError.new(connection, connection.peer.host, "unknown DNS error (error code #{result})")
-
6
raise ex
-
when :decode_error
-
6
hostname, connection = @queries.first
-
6
reset_hostname(hostname)
-
6
@connections.delete(connection)
-
6
ex = NativeResolveError.new(connection, connection.peer.host, result.message)
-
6
ex.set_backtrace(result.backtrace)
-
6
raise ex
-
end
-
end
-
-
25
def parse_addresses(addresses)
-
190
if addresses.empty?
-
# no address found, eliminate candidates
-
6
hostname, connection = @queries.first
-
6
reset_hostname(hostname)
-
6
@connections.delete(connection)
-
6
raise NativeResolveError.new(connection, connection.peer.host)
-
else
-
184
address = addresses.first
-
184
name = address["name"]
-
-
184
connection = @queries.delete(name)
-
-
184
unless connection
-
orig_name = name
-
# absolute name
-
name_labels = Resolv::DNS::Name.create(name).to_a
-
name = @queries.each_key.first { |hname| name_labels == Resolv::DNS::Name.create(hname).to_a }
-
-
# probably a retried query for which there's an answer
-
unless name
-
@timeouts.delete(orig_name)
-
return
-
end
-
-
address["name"] = name
-
connection = @queries.delete(name)
-
end
-
-
1166
alias_addresses, addresses = addresses.partition { |addr| addr.key?("alias") }
-
-
184
if addresses.empty? && !alias_addresses.empty? # CNAME
-
hostname_alias = alias_addresses.first["alias"]
-
# clean up intermediate queries
-
@timeouts.delete(name) unless connection.peer.host == name
-
-
if early_resolve(connection, hostname: hostname_alias)
-
@connections.delete(connection)
-
else
-
if @socket_type == :tcp
-
# must downgrade to udp if tcp
-
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
transition(:idle)
-
transition(:open)
-
end
-
log { "resolver #{FAMILY_TYPES[@record_type]}: ALIAS #{hostname_alias} for #{name}" }
-
resolve(connection, hostname_alias)
-
return
-
end
-
else
-
184
reset_hostname(name, connection: connection)
-
184
@timeouts.delete(connection.peer.host)
-
184
@connections.delete(connection)
-
184
Resolver.cached_lookup_set(connection.peer.host, @family, addresses) if @resolver_options[:cache]
-
1332
catch(:coalesced) { emit_addresses(connection, @family, addresses.map { |addr| addr["data"] }) }
-
end
-
end
-
184
close_or_resolve
-
end
-
-
25
def resolve(connection = nil, hostname = nil)
-
675
@connections.shift until @connections.empty? || @connections.first.state != :closed
-
-
1001
connection ||= @connections.find { |c| !@queries.value?(c) }
-
-
675
raise Error, "no URI to resolve" unless connection
-
-
675
return unless @write_buffer.empty?
-
-
673
hostname ||= @queries.key(connection)
-
-
673
if hostname.nil?
-
322
hostname = connection.peer.host
-
322
if connection.peer.non_ascii_hostname
-
log { "resolver #{FAMILY_TYPES[@record_type]}: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}" }
-
end
-
-
322
hostname = generate_candidates(hostname).each do |name|
-
1288
@queries[name] = connection
-
end.first
-
else
-
351
@queries[hostname] = connection
-
end
-
-
673
@name = hostname
-
-
673
log { "resolver #{FAMILY_TYPES[@record_type]}: query for #{hostname}" }
-
begin
-
673
@write_buffer << encode_dns_query(hostname)
-
rescue Resolv::DNS::EncodeError => e
-
reset_hostname(hostname, connection: connection)
-
@connections.delete(connection)
-
emit_resolve_error(connection, hostname, e)
-
close_or_resolve
-
end
-
end
-
-
25
def encode_dns_query(hostname)
-
673
message_id = Resolver.generate_id
-
673
msg = Resolver.encode_dns_query(hostname, type: @record_type, message_id: message_id)
-
673
msg[0, 2] = [msg.size, message_id].pack("nn") if @socket_type == :tcp
-
673
msg
-
end
-
-
25
def generate_candidates(name)
-
322
return [name] if name.end_with?(".")
-
-
322
candidates = []
-
322
name_parts = name.scan(/[^.]+/)
-
322
candidates = [name] if @ndots <= name_parts.size - 1
-
966
candidates.concat(@search.map { |domain| [*name_parts, *domain].join(".") })
-
322
fname = "#{name}."
-
322
candidates << fname unless candidates.include?(fname)
-
-
322
candidates
-
end
-
-
25
def build_socket
-
338
ip, port = @nameserver[@ns_index]
-
338
port ||= DNS_PORT
-
-
338
case @socket_type
-
when :udp
-
320
log { "resolver #{FAMILY_TYPES[@record_type]}: server: udp://#{ip}:#{port}..." }
-
320
UDP.new(ip, port, @options)
-
when :tcp
-
18
log { "resolver #{FAMILY_TYPES[@record_type]}: server: tcp://#{ip}:#{port}..." }
-
18
origin = URI("tcp://#{ip}:#{port}")
-
18
TCP.new(origin, [ip], @options)
-
end
-
end
-
-
25
def downgrade_socket
-
51
return unless @socket_type == :tcp
-
-
12
@socket_type = @resolver_options.fetch(:socket_type, :udp)
-
12
transition(:idle)
-
12
transition(:open)
-
end
-
-
25
def transition(nextstate)
-
11095
case nextstate
-
when :idle
-
42
if @io
-
36
@io.close
-
36
@io = nil
-
end
-
when :open
-
10733
return unless @state == :idle
-
-
10733
@io ||= build_socket
-
-
10733
@io.connect
-
10733
return unless @io.connected?
-
-
338
resolve if @queries.empty? && !@connections.empty?
-
when :closed
-
320
return unless @state == :open
-
-
314
@io.close if @io
-
314
@start_timeout = nil
-
314
@write_buffer.clear
-
314
@read_buffer.clear
-
end
-
694
@state = nextstate
-
rescue Errno::ECONNREFUSED,
-
Errno::EADDRNOTAVAIL,
-
Errno::EHOSTUNREACH,
-
SocketError,
-
IOError,
-
ConnectTimeoutError => e
-
# these errors may happen during TCP handshake
-
# treat them as resolve errors.
-
handle_error(e)
-
emit(:close, self)
-
end
-
-
25
def handle_error(error)
-
24
if error.respond_to?(:connection) &&
-
error.respond_to?(:host)
-
18
reset_hostname(error.host, connection: error.connection)
-
18
@connections.delete(error.connection)
-
18
emit_resolve_error(error.connection, error.host, error)
-
else
-
6
@queries.each do |host, connection|
-
6
reset_hostname(host, connection: connection)
-
6
@connections.delete(connection)
-
6
emit_resolve_error(connection, host, error)
-
end
-
-
12
while (connection = @connections.shift)
-
emit_resolve_error(connection, connection.peer.host, error)
-
end
-
end
-
end
-
-
25
def reset_hostname(hostname, connection: @queries.delete(hostname), reset_candidates: true)
-
646
@timeouts.delete(hostname)
-
-
646
return unless connection && reset_candidates
-
-
# eliminate other candidates
-
904
candidates = @queries.select { |_, conn| connection == conn }.keys
-
904
@queries.delete_if { |h, _| candidates.include?(h) }
-
# reset timeouts
-
880
@timeouts.delete_if { |h, _| candidates.include?(h) }
-
end
-
-
25
def close_or_resolve
-
# drop already closed connections
-
292
@connections.shift until @connections.empty? || @connections.first.state != :closed
-
-
292
if (@connections - @queries.values).empty?
-
290
emit(:close, self)
-
else
-
2
resolve
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "resolv"
-
25
require "ipaddr"
-
-
25
module HTTPX
-
# Base class for all internal internet name resolvers. It handles basic blocks
-
# from the Selectable API.
-
#
-
25
class Resolver::Resolver
-
25
include Callbacks
-
25
include Loggable
-
-
25
using ArrayExtensions::Intersect
-
-
RECORD_TYPES = {
-
25
Socket::AF_INET6 => Resolv::DNS::Resource::IN::AAAA,
-
Socket::AF_INET => Resolv::DNS::Resource::IN::A,
-
}.freeze
-
-
FAMILY_TYPES = {
-
25
Resolv::DNS::Resource::IN::AAAA => "AAAA",
-
Resolv::DNS::Resource::IN::A => "A",
-
}.freeze
-
-
25
class << self
-
25
def multi?
-
5508
true
-
end
-
end
-
-
25
attr_reader :family, :options
-
-
25
attr_writer :current_selector, :current_session
-
-
25
attr_accessor :multi
-
-
25
def initialize(family, options)
-
5533
@family = family
-
5533
@record_type = RECORD_TYPES[family]
-
5533
@options = options
-
5533
@connections = []
-
-
5533
set_resolver_callbacks
-
end
-
-
25
def each_connection(&block)
-
199
enum_for(__method__) unless block
-
-
199
return unless @connections
-
-
199
@connections.each(&block)
-
end
-
-
25
def close; end
-
-
25
alias_method :terminate, :close
-
-
25
def closed?
-
true
-
end
-
-
25
def empty?
-
true
-
end
-
-
25
def inflight?
-
12
false
-
end
-
-
25
def emit_addresses(connection, family, addresses, early_resolve = false)
-
5608
addresses.map! do |address|
-
12392
address.is_a?(IPAddr) ? address : IPAddr.new(address.to_s)
-
end
-
-
# double emission check, but allow early resolution to work
-
5608
return if !early_resolve && connection.addresses && !addresses.intersect?(connection.addresses)
-
-
5608
log do
-
60
"resolver #{FAMILY_TYPES[RECORD_TYPES[family]]}: " \
-
"answer #{connection.peer.host}: #{addresses.inspect} (early resolve: #{early_resolve})"
-
end
-
-
5608
if !early_resolve && # do not apply resolution delay for non-dns name resolution
-
@current_selector && # just in case...
-
family == Socket::AF_INET && # resolution delay only applies to IPv4
-
!connection.io && # connection already has addresses and initiated/ended handshake
-
connection.options.ip_families.size > 1 && # no need to delay if not supporting dual stack IP
-
addresses.first.to_s != connection.peer.host.to_s # connection URL host is already the IP (early resolve included perhaps?)
-
log { "resolver #{FAMILY_TYPES[RECORD_TYPES[family]]}: applying resolution delay..." }
-
-
@current_selector.after(0.05) do
-
# double emission check
-
unless connection.addresses && addresses.intersect?(connection.addresses)
-
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
else
-
5608
emit_resolved_connection(connection, addresses, early_resolve)
-
end
-
end
-
-
25
private
-
-
25
def emit_resolved_connection(connection, addresses, early_resolve)
-
begin
-
5608
connection.addresses = addresses
-
-
5572
return if connection.state == :closed
-
-
5572
emit(:resolve, connection)
-
24
rescue StandardError => e
-
36
if early_resolve
-
30
connection.force_reset
-
30
throw(:resolve_error, e)
-
else
-
6
emit(:error, connection, e)
-
end
-
end
-
end
-
-
25
def early_resolve(connection, hostname: connection.peer.host)
-
addresses = @resolver_options[:cache] && (connection.addresses || HTTPX::Resolver.nolookup_resolve(hostname))
-
-
return false unless addresses
-
-
addresses = addresses.select { |addr| addr.family == @family }
-
-
return false if addresses.empty?
-
-
emit_addresses(connection, @family, addresses, true)
-
-
true
-
end
-
-
25
def emit_resolve_error(connection, hostname = connection.peer.host, ex = nil)
-
163
emit_connection_error(connection, resolve_error(hostname, ex))
-
end
-
-
25
def resolve_error(hostname, ex = nil)
-
163
return ex if ex.is_a?(ResolveError) || ex.is_a?(ResolveTimeoutError)
-
-
42
message = ex ? ex.message : "Can't resolve #{hostname}"
-
42
error = ResolveError.new(message)
-
42
error.set_backtrace(ex ? ex.backtrace : caller)
-
42
error
-
end
-
-
25
def set_resolver_callbacks
-
5533
on(:resolve, &method(:resolve_connection))
-
5533
on(:error, &method(:emit_connection_error))
-
5533
on(:close, &method(:close_resolver))
-
end
-
-
25
def resolve_connection(connection)
-
5572
@current_session.__send__(:on_resolver_connection, connection, @current_selector)
-
end
-
-
25
def emit_connection_error(connection, error)
-
156
return connection.handle_connect_error(error) if connection.connecting?
-
-
connection.emit(:error, error)
-
end
-
-
25
def close_resolver(resolver)
-
308
@current_session.__send__(:on_resolver_close, resolver, @current_selector)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "resolv"
-
-
25
module HTTPX
-
# Implementation of a synchronous name resolver which relies on the system resolver,
-
# which is lib'c getaddrinfo function (abstracted in ruby via Addrinfo.getaddrinfo).
-
#
-
# Its main advantage is relying on the reference implementation for name resolution
-
# across most/all OSs which deploy ruby (it's what TCPSocket also uses), its main
-
# disadvantage is the inability to set timeouts / check socket for readiness events,
-
# hence why it relies on using the Timeout module, which poses a lot of problems for
-
# the selector loop, specially when network is unstable.
-
#
-
25
class Resolver::System < Resolver::Resolver
-
25
using URIExtensions
-
-
25
RESOLV_ERRORS = [Resolv::ResolvError,
-
Resolv::DNS::Requester::RequestError,
-
Resolv::DNS::EncodeError,
-
Resolv::DNS::DecodeError].freeze
-
-
25
DONE = 1
-
25
ERROR = 2
-
-
25
class << self
-
25
def multi?
-
25
false
-
end
-
end
-
-
25
attr_reader :state
-
-
25
def initialize(options)
-
25
super(0, options)
-
25
@resolver_options = @options.resolver_options
-
25
resolv_options = @resolver_options.dup
-
25
timeouts = resolv_options.delete(:timeouts) || Resolver::RESOLVE_TIMEOUT
-
25
@_timeouts = Array(timeouts)
-
50
@timeouts = Hash.new { |tims, host| tims[host] = @_timeouts.dup }
-
25
resolv_options.delete(:cache)
-
25
@queries = []
-
25
@ips = []
-
25
@pipe_mutex = Thread::Mutex.new
-
25
@state = :idle
-
end
-
-
25
def resolvers
-
return enum_for(__method__) unless block_given?
-
-
yield self
-
end
-
-
25
def multi
-
self
-
end
-
-
25
def empty?
-
true
-
end
-
-
25
def close
-
transition(:closed)
-
end
-
-
25
def closed?
-
@state == :closed
-
end
-
-
25
def to_io
-
@pipe_read.to_io
-
end
-
-
25
def call
-
case @state
-
when :open
-
consume
-
end
-
nil
-
end
-
-
25
def interests
-
return if @queries.empty?
-
-
:r
-
end
-
-
25
def timeout
-
return unless @queries.empty?
-
-
_, connection = @queries.first
-
-
return unless connection
-
-
@timeouts[connection.peer.host].first
-
end
-
-
25
def <<(connection)
-
25
@connections << connection
-
25
resolve
-
end
-
-
25
def early_resolve(connection, **)
-
25
self << connection
-
12
true
-
end
-
-
25
def handle_socket_timeout(interval)
-
error = HTTPX::ResolveTimeoutError.new(interval, "timed out while waiting on select")
-
error.set_backtrace(caller)
-
@queries.each do |host, connection|
-
@connections.delete(connection)
-
emit_resolve_error(connection, host, error)
-
end
-
-
while (connection = @connections.shift)
-
emit_resolve_error(connection, connection.peer.host, error)
-
end
-
end
-
-
25
private
-
-
25
def transition(nextstate)
-
25
case nextstate
-
when :idle
-
@timeouts.clear
-
when :open
-
25
return unless @state == :idle
-
-
25
@pipe_read, @pipe_write = ::IO.pipe
-
when :closed
-
return unless @state == :open
-
-
@pipe_write.close
-
@pipe_read.close
-
end
-
25
@state = nextstate
-
end
-
-
25
def consume
-
25
return if @connections.empty?
-
-
25
if @pipe_read.wait_readable
-
25
event = @pipe_read.getbyte
-
-
25
case event
-
when DONE
-
24
*pair, addrs = @pipe_mutex.synchronize { @ips.pop }
-
12
if pair
-
12
@queries.delete(pair)
-
12
family, connection = pair
-
12
@connections.delete(connection)
-
-
24
catch(:coalesced) { emit_addresses(connection, family, addrs) }
-
end
-
when ERROR
-
26
*pair, error = @pipe_mutex.synchronize { @ips.pop }
-
13
if pair && error
-
13
@queries.delete(pair)
-
13
@connections.delete(connection)
-
-
13
_, connection = pair
-
13
emit_resolve_error(connection, connection.peer.host, error)
-
end
-
end
-
end
-
-
12
return emit(:close, self) if @connections.empty?
-
-
resolve
-
end
-
-
25
def resolve(connection = nil, hostname = nil)
-
25
@connections.shift until @connections.empty? || @connections.first.state != :closed
-
-
25
connection ||= @connections.first
-
-
25
raise Error, "no URI to resolve" unless connection
-
-
25
return unless @queries.empty?
-
-
25
hostname ||= connection.peer.host
-
25
scheme = connection.origin.scheme
-
log do
-
"resolver: resolve IDN #{connection.peer.non_ascii_hostname} as #{hostname}"
-
25
end if connection.peer.non_ascii_hostname
-
-
25
transition(:open)
-
-
25
connection.options.ip_families.each do |family|
-
25
@queries << [family, connection]
-
end
-
25
async_resolve(connection, hostname, scheme)
-
25
consume
-
end
-
-
25
def async_resolve(connection, hostname, scheme)
-
25
families = connection.options.ip_families
-
25
log { "resolver: query for #{hostname}" }
-
25
timeouts = @timeouts[connection.peer.host]
-
25
resolve_timeout = timeouts.first
-
-
25
Thread.start do
-
25
Thread.current.report_on_exception = false
-
begin
-
25
addrs = if resolve_timeout
-
-
25
Timeout.timeout(resolve_timeout) do
-
25
__addrinfo_resolve(hostname, scheme)
-
end
-
else
-
__addrinfo_resolve(hostname, scheme)
-
end
-
12
addrs = addrs.sort_by(&:afamily).group_by(&:afamily)
-
12
families.each do |family|
-
12
addresses = addrs[family]
-
12
next unless addresses
-
-
12
addresses.map!(&:ip_address)
-
12
addresses.uniq!
-
12
@pipe_mutex.synchronize do
-
12
@ips.unshift([family, connection, addresses])
-
12
@pipe_write.putc(DONE) unless @pipe_write.closed?
-
end
-
end
-
rescue StandardError => e
-
13
if e.is_a?(Timeout::Error)
-
1
timeouts.shift
-
1
retry unless timeouts.empty?
-
1
e = ResolveTimeoutError.new(resolve_timeout, e.message)
-
1
e.set_backtrace(e.backtrace)
-
end
-
13
@pipe_mutex.synchronize do
-
13
families.each do |family|
-
13
@ips.unshift([family, connection, e])
-
13
@pipe_write.putc(ERROR) unless @pipe_write.closed?
-
end
-
end
-
end
-
end
-
end
-
-
25
def __addrinfo_resolve(host, scheme)
-
25
Addrinfo.getaddrinfo(host, scheme, Socket::AF_UNSPEC, Socket::SOCK_STREAM)
-
end
-
-
25
def emit_connection_error(_, error)
-
13
throw(:resolve_error, error)
-
end
-
-
25
def close_resolver(resolver); end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "objspace"
-
25
require "stringio"
-
25
require "tempfile"
-
25
require "fileutils"
-
25
require "forwardable"
-
-
25
module HTTPX
-
# Defines a HTTP response is handled internally, with a few properties exposed as attributes.
-
#
-
# It delegates the following methods to the corresponding HTTPX::Request:
-
#
-
# * HTTPX::Request#uri
-
# * HTTPX::Request#peer_address
-
#
-
# It implements (indirectly, via the +body+) the IO write protocol to internally buffer payloads.
-
#
-
# It implements the IO reader protocol in order for users to buffer/stream it, acts as an enumerable
-
# (of payload chunks).
-
#
-
25
class Response
-
25
extend Forwardable
-
25
include Callbacks
-
-
# the HTTP response status code
-
25
attr_reader :status
-
-
# an HTTPX::Headers object containing the response HTTP headers.
-
25
attr_reader :headers
-
-
# a HTTPX::Response::Body object wrapping the response body. The following methods are delegated to it:
-
#
-
# * HTTPX::Response::Body#to_s
-
# * HTTPX::Response::Body#to_str
-
# * HTTPX::Response::Body#read
-
# * HTTPX::Response::Body#copy_to
-
# * HTTPX::Response::Body#close
-
25
attr_reader :body
-
-
# The HTTP protocol version used to fetch the response.
-
25
attr_reader :version
-
-
# returns the response body buffered in a string.
-
25
def_delegator :@body, :to_s
-
-
25
def_delegator :@body, :to_str
-
-
# implements the IO reader +#read+ interface.
-
25
def_delegator :@body, :read
-
-
# copies the response body to a different location.
-
25
def_delegator :@body, :copy_to
-
-
# the corresponding request uri.
-
25
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
25
def_delegator :@request, :peer_address
-
-
# inits the instance with the corresponding +request+ to this response, an the
-
# response HTTP +status+, +version+ and HTTPX::Headers instance of +headers+.
-
25
def initialize(request, status, version, headers)
-
7338
@request = request
-
7338
@options = request.options
-
7338
@version = version
-
7338
@status = Integer(status)
-
7338
@headers = @options.headers_class.new(headers)
-
7338
@body = @options.response_body_class.new(self, @options)
-
7338
@finished = complete?
-
7338
@content_type = nil
-
end
-
-
# dupped initialization
-
25
def initialize_dup(orig)
-
48
super
-
# if a response gets dupped, the body handle must also get dupped to prevent
-
# two responses from using the same file handle to read.
-
48
@body = orig.body.dup
-
end
-
-
# closes the respective +@request+ and +@body+.
-
25
def close
-
362
@request.close
-
362
@body.close
-
end
-
-
# merges headers defined in +h+ into the response headers.
-
25
def merge_headers(h)
-
173
@headers = @headers.merge(h)
-
end
-
-
# writes +data+ chunk into the response body.
-
25
def <<(data)
-
9574
@body.write(data)
-
end
-
-
# returns the HTTPX::ContentType for the response, as per what's declared in the content-type header.
-
#
-
# response.content_type #=> #<HTTPX::ContentType:xxx @header_value="text/plain">
-
# response.content_type.mime_type #=> "text/plain"
-
25
def content_type
-
7617
@content_type ||= ContentType.new(@headers["content-type"])
-
end
-
-
# returns whether the response has been fully fetched.
-
25
def finished?
-
11592
@finished
-
end
-
-
# marks the response as finished, freezes the headers.
-
25
def finish!
-
6531
@finished = true
-
6531
@headers.freeze
-
end
-
-
# returns whether the response contains body payload.
-
25
def bodyless?
-
7338
@request.verb == "HEAD" ||
-
@status < 200 || # informational response
-
@status == 204 ||
-
@status == 205 ||
-
@status == 304 || begin
-
6990
content_length = @headers["content-length"]
-
6990
return false if content_length.nil?
-
-
5903
content_length == "0"
-
end
-
end
-
-
25
def complete?
-
7338
bodyless? || (@request.verb == "CONNECT" && @status == 200)
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"HTTP/#{version} " \
-
skipped
"@status=#{@status} " \
-
skipped
"@headers=#{@headers} " \
-
skipped
"@body=#{@body.bytesize}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# returns an instance of HTTPX::HTTPError if the response has a 4xx or 5xx
-
# status code, or nothing.
-
#
-
# ok_response.error #=> nil
-
# not_found_response.error #=> HTTPX::HTTPError instance, status 404
-
25
def error
-
512
return if @status < 400
-
-
42
HTTPError.new(self)
-
end
-
-
# it raises the exception returned by +error+, or itself otherwise.
-
#
-
# ok_response.raise_for_status #=> ok_response
-
# not_found_response.raise_for_status #=> raises HTTPX::HTTPError exception
-
25
def raise_for_status
-
482
return self unless (err = error)
-
-
30
raise err
-
end
-
-
# decodes the response payload into a ruby object **if** the payload is valid json.
-
#
-
# response.json #≈> { "foo" => "bar" } for "{\"foo\":\"bar\"}" payload
-
# response.json(symbolize_names: true) #≈> { foo: "bar" } for "{\"foo\":\"bar\"}" payload
-
25
def json(*args)
-
99
decode(Transcoder::JSON, *args)
-
end
-
-
# decodes the response payload into a ruby object **if** the payload is valid
-
# "application/x-www-urlencoded" or "multipart/form-data".
-
25
def form
-
48
decode(Transcoder::Form)
-
end
-
-
25
def xml
-
# TODO: remove at next major version.
-
6
warn "DEPRECATION WARNING: calling `.#{__method__}` on plain HTTPX responses is deprecated. " \
-
"Use HTTPX.plugin(:xml) sessions and call `.#{__method__}` in its responses instead."
-
6
require "httpx/plugins/xml"
-
6
decode(Plugins::XML::Transcoder)
-
end
-
-
25
private
-
-
# decodes the response payload using the given +transcoder+, which implements the decoding logic.
-
#
-
# +transcoder+ must implement the internal transcoder API, i.e. respond to <tt>decode(HTTPX::Response response)</tt>,
-
# which returns a decoder which responds to <tt>call(HTTPX::Response response, **kwargs)</tt>
-
25
def decode(transcoder, *args)
-
# TODO: check if content-type is a valid format, i.e. "application/json" for json parsing
-
-
165
decoder = transcoder.decode(self)
-
-
147
raise Error, "no decoder available for \"#{transcoder}\"" unless decoder
-
-
147
@body.rewind
-
-
147
decoder.call(self, *args)
-
end
-
end
-
-
# Helper class which decodes the HTTP "content-type" header.
-
25
class ContentType
-
25
MIME_TYPE_RE = %r{^([^/]+/[^;]+)(?:$|;)}.freeze
-
25
CHARSET_RE = /;\s*charset=([^;]+)/i.freeze
-
-
25
def initialize(header_value)
-
7587
@header_value = header_value
-
end
-
-
# returns the mime type declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").mime_type #=> "application/json"
-
25
def mime_type
-
165
return @mime_type if defined?(@mime_type)
-
-
135
m = @header_value.to_s[MIME_TYPE_RE, 1]
-
135
m && @mime_type = m.strip.downcase
-
end
-
-
# returns the charset declared in the header.
-
#
-
# ContentType.new("application/json; charset=utf-8").charset #=> "utf-8"
-
# ContentType.new("text/plain").charset #=> nil
-
25
def charset
-
7452
return @charset if defined?(@charset)
-
-
7452
m = @header_value.to_s[CHARSET_RE, 1]
-
7452
m && @charset = m.strip.delete('"')
-
end
-
end
-
-
# Wraps an error which has happened while processing an HTTP Request. It has partial
-
# public API parity with HTTPX::Response, so users should rely on it to infer whether
-
# the returned response is one or the other.
-
#
-
# response = HTTPX.get("https://some-domain/path") #=> response is HTTPX::Response or HTTPX::ErrorResponse
-
# response.raise_for_status #=> raises if it wraps an error
-
25
class ErrorResponse
-
25
include Loggable
-
25
extend Forwardable
-
-
# the corresponding HTTPX::Request instance.
-
25
attr_reader :request
-
-
# the HTTPX::Response instance, when there is one (i.e. error happens fetching the response).
-
25
attr_reader :response
-
-
# the wrapped exception.
-
25
attr_reader :error
-
-
# the request uri
-
25
def_delegator :@request, :uri
-
-
# the IP address of the peer server.
-
25
def_delegator :@request, :peer_address
-
-
25
def initialize(request, error)
-
962
@request = request
-
962
@response = request.response if request.response.is_a?(Response)
-
962
@error = error
-
962
@options = request.options
-
962
log_exception(@error)
-
end
-
-
# returns the exception full message.
-
25
def to_s
-
8
@error.full_message(highlight: false)
-
end
-
-
# closes the error resources.
-
25
def close
-
30
@response.close if @response
-
end
-
-
# always true for error responses.
-
25
def finished?
-
862
true
-
end
-
-
25
def finish!; end
-
-
# raises the wrapped exception.
-
25
def raise_for_status
-
66
raise @error
-
end
-
-
# buffers lost chunks to error response
-
25
def <<(data)
-
6
return unless @response
-
-
6
@response << data
-
end
-
end
-
end
-
-
25
require_relative "response/body"
-
25
require_relative "response/buffer"
-
25
require_relative "pmatch_extensions" if RUBY_VERSION >= "2.7.0"
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
# Implementation of the HTTP Response body as a buffer which implements the IO writer protocol
-
# (for buffering the response payload), the IO reader protocol (for consuming the response payload),
-
# and can be iterated over (via #each, which yields the payload in chunks).
-
25
class Response::Body
-
# the payload encoding (i.e. "utf-8", "ASCII-8BIT")
-
25
attr_reader :encoding
-
-
# Array of encodings contained in the response "content-encoding" header.
-
25
attr_reader :encodings
-
-
25
attr_reader :buffer
-
25
protected :buffer
-
-
# initialized with the corresponding HTTPX::Response +response+ and HTTPX::Options +options+.
-
25
def initialize(response, options)
-
7452
@response = response
-
7452
@headers = response.headers
-
7452
@options = options
-
7452
@window_size = options.window_size
-
7452
@encodings = []
-
7452
@length = 0
-
7452
@buffer = nil
-
7452
@reader = nil
-
7452
@state = :idle
-
-
# initialize response encoding
-
7452
@encoding = if (enc = response.content_type.charset)
-
begin
-
1248
Encoding.find(enc)
-
rescue ArgumentError
-
24
Encoding::BINARY
-
end
-
else
-
6204
Encoding::BINARY
-
end
-
-
7452
initialize_inflaters
-
end
-
-
25
def initialize_dup(other)
-
72
super
-
-
72
@buffer = other.instance_variable_get(:@buffer).dup
-
end
-
-
25
def closed?
-
30
@state == :closed
-
end
-
-
# write the response payload +chunk+ into the buffer. Inflates the chunk when required
-
# and supported.
-
25
def write(chunk)
-
9544
return if @state == :closed
-
-
9544
return 0 if chunk.empty?
-
-
9202
chunk = decode_chunk(chunk)
-
-
9202
size = chunk.bytesize
-
9202
@length += size
-
9202
transition(:open)
-
9202
@buffer.write(chunk)
-
-
9202
@response.emit(:chunk_received, chunk)
-
9190
size
-
end
-
-
# reads a chunk from the payload (implementation of the IO reader protocol).
-
25
def read(*args)
-
243
return unless @buffer
-
-
243
unless @reader
-
141
rewind
-
141
@reader = @buffer
-
end
-
-
243
@reader.read(*args)
-
end
-
-
# size of the decoded response payload. May differ from "content-length" header if
-
# response was encoded over-the-wire.
-
25
def bytesize
-
174
@length
-
end
-
-
# yields the payload in chunks.
-
25
def each
-
36
return enum_for(__method__) unless block_given?
-
-
begin
-
24
if @buffer
-
24
rewind
-
72
while (chunk = @buffer.read(@window_size))
-
24
yield(chunk.force_encoding(@encoding))
-
end
-
end
-
ensure
-
24
close
-
end
-
end
-
-
# returns the declared filename in the "contennt-disposition" header, when present.
-
25
def filename
-
36
return unless @headers.key?("content-disposition")
-
-
30
Utils.get_filename(@headers["content-disposition"])
-
end
-
-
# returns the full response payload as a string.
-
25
def to_s
-
3587
return "".b unless @buffer
-
-
3309
@buffer.to_s
-
end
-
-
25
alias_method :to_str, :to_s
-
-
# whether the payload is empty.
-
25
def empty?
-
24
@length.zero?
-
end
-
-
# copies the payload to +dest+.
-
#
-
# body.copy_to("path/to/file")
-
# body.copy_to(Pathname.new("path/to/file"))
-
# body.copy_to(File.new("path/to/file"))
-
25
def copy_to(dest)
-
36
return unless @buffer
-
-
36
rewind
-
-
36
if dest.respond_to?(:path) && @buffer.respond_to?(:path)
-
6
FileUtils.mv(@buffer.path, dest.path)
-
else
-
30
::IO.copy_stream(@buffer, dest)
-
end
-
end
-
-
# closes/cleans the buffer, resets everything
-
25
def close
-
559
if @buffer
-
413
@buffer.close
-
413
@buffer = nil
-
end
-
559
@length = 0
-
559
transition(:closed)
-
end
-
-
25
def ==(other)
-
220
super || case other
-
when Response::Body
-
114
@buffer == other.buffer
-
else
-
64
@buffer = other
-
end
-
end
-
-
skipped
# :nocov:
-
skipped
def inspect
-
skipped
"#<#{self.class}:#{object_id} " \
-
skipped
"@state=#{@state} " \
-
skipped
"@length=#{@length}>"
-
skipped
end
-
skipped
# :nocov:
-
-
# rewinds the response payload buffer.
-
25
def rewind
-
678
return unless @buffer
-
-
# in case there's some reading going on
-
678
@reader = nil
-
-
678
@buffer.rewind
-
end
-
-
25
private
-
-
# prepares inflaters for the advertised encodings in "content-encoding" header.
-
25
def initialize_inflaters
-
7452
@inflaters = nil
-
-
7452
return unless @headers.key?("content-encoding")
-
-
143
return unless @options.decompress_response_body
-
-
131
@inflaters = @headers.get("content-encoding").filter_map do |encoding|
-
131
next if encoding == "identity"
-
-
131
inflater = self.class.initialize_inflater_by_encoding(encoding, @response)
-
-
# do not uncompress if there is no decoder available. In fact, we can't reliably
-
# continue decompressing beyond that, so ignore.
-
131
break unless inflater
-
-
131
@encodings << encoding
-
131
inflater
-
end
-
end
-
-
# passes the +chunk+ through all inflaters to decode it.
-
25
def decode_chunk(chunk)
-
@inflaters.reverse_each do |inflater|
-
348
chunk = inflater.call(chunk)
-
9441
end if @inflaters
-
-
9441
chunk
-
end
-
-
# tries transitioning the body STM to the +nextstate+.
-
25
def transition(nextstate)
-
9761
case nextstate
-
when :open
-
9202
return unless @state == :idle
-
-
5894
@buffer = Response::Buffer.new(
-
threshold_size: @options.body_threshold_size,
-
bytesize: @length,
-
encoding: @encoding
-
)
-
when :closed
-
559
return if @state == :closed
-
end
-
-
6453
@state = nextstate
-
end
-
-
25
class << self
-
25
def initialize_inflater_by_encoding(encoding, response, **kwargs) # :nodoc:
-
131
case encoding
-
when "gzip"
-
119
Transcoder::GZIP.decode(response, **kwargs)
-
when "deflate"
-
12
Transcoder::Deflate.decode(response, **kwargs)
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "delegate"
-
25
require "stringio"
-
25
require "tempfile"
-
-
25
module HTTPX
-
# wraps and delegates to an internal buffer, which can be a StringIO or a Tempfile.
-
25
class Response::Buffer < SimpleDelegator
-
25
attr_reader :buffer
-
25
protected :buffer
-
-
# initializes buffer with the +threshold_size+ over which the payload gets buffer to a tempfile,
-
# the initial +bytesize+, and the +encoding+.
-
25
def initialize(threshold_size:, bytesize: 0, encoding: Encoding::BINARY)
-
6050
@threshold_size = threshold_size
-
6050
@bytesize = bytesize
-
6050
@encoding = encoding
-
6050
@buffer = StringIO.new("".b)
-
6050
super(@buffer)
-
end
-
-
25
def initialize_dup(other)
-
72
super
-
-
# create new descriptor in READ-ONLY mode
-
@buffer =
-
72
case other.buffer
-
when StringIO
-
72
StringIO.new(other.buffer.string, mode: File::RDONLY)
-
else
-
other.buffer.class.new(other.buffer.path, encoding: Encoding::BINARY, mode: File::RDONLY)
-
end
-
end
-
-
# size in bytes of the buffered content.
-
25
def size
-
276
@bytesize
-
end
-
-
# writes the +chunk+ into the buffer.
-
25
def write(chunk)
-
9502
@bytesize += chunk.bytesize
-
9502
try_upgrade_buffer
-
9502
@buffer.write(chunk)
-
end
-
-
# returns the buffered content as a string.
-
25
def to_s
-
3375
case @buffer
-
when StringIO
-
begin
-
3321
@buffer.string.force_encoding(@encoding)
-
rescue ArgumentError
-
@buffer.string
-
end
-
when Tempfile
-
54
rewind
-
54
content = @buffer.read
-
begin
-
54
content.force_encoding(@encoding)
-
rescue ArgumentError # ex: unknown encoding name - utf
-
content
-
end
-
end
-
end
-
-
# closes the buffer.
-
25
def close
-
497
@buffer.close
-
497
@buffer.unlink if @buffer.respond_to?(:unlink)
-
end
-
-
25
def ==(other)
-
114
super || begin
-
114
return false unless other.is_a?(Response::Buffer)
-
-
114
if @buffer.nil?
-
other.buffer.nil?
-
114
elsif @buffer.respond_to?(:read) &&
-
other.respond_to?(:read)
-
114
buffer_pos = @buffer.pos
-
114
other_pos = other.buffer.pos
-
114
@buffer.rewind
-
114
other.buffer.rewind
-
begin
-
114
FileUtils.compare_stream(@buffer, other.buffer)
-
ensure
-
114
@buffer.pos = buffer_pos
-
114
other.buffer.pos = other_pos
-
end
-
else
-
to_s == other.to_s
-
end
-
end
-
end
-
-
25
private
-
-
# initializes the buffer into a StringIO, or turns it into a Tempfile when the threshold
-
# has been reached.
-
25
def try_upgrade_buffer
-
9502
return unless @bytesize > @threshold_size
-
-
359
return if @buffer.is_a?(Tempfile)
-
-
123
aux = @buffer
-
-
123
@buffer = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
-
123
if aux
-
123
aux.rewind
-
123
::IO.copy_stream(aux, @buffer)
-
123
aux.close
-
end
-
-
123
__setobj__(@buffer)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "io/wait"
-
-
25
module HTTPX
-
25
class Selector
-
25
extend Forwardable
-
-
25
READABLE = %i[rw r].freeze
-
25
WRITABLE = %i[rw w].freeze
-
-
25
private_constant :READABLE
-
25
private_constant :WRITABLE
-
-
25
def_delegator :@timers, :after
-
-
25
def_delegator :@selectables, :empty?
-
-
25
def initialize
-
5993
@timers = Timers.new
-
5993
@selectables = []
-
5993
@is_timer_interval = false
-
end
-
-
25
def each(&blk)
-
@selectables.each(&blk)
-
end
-
-
25
def next_tick
-
9695806
catch(:jump_tick) do
-
9695806
timeout = next_timeout
-
9695806
if timeout && timeout.negative?
-
@timers.fire
-
throw(:jump_tick)
-
end
-
-
begin
-
9695806
select(timeout) do |c|
-
19167
c.log(level: 2) { "[#{c.state}] selected#{" after #{timeout} secs" unless timeout.nil?}..." }
-
-
19071
c.call
-
end
-
-
9695686
@timers.fire
-
rescue TimeoutError => e
-
@timers.fire(e)
-
end
-
end
-
rescue StandardError => e
-
18
each_connection do |c|
-
c.emit(:error, e)
-
end
-
rescue Exception # rubocop:disable Lint/RescueException
-
90
each_connection do |conn|
-
72
conn.force_reset
-
72
conn.disconnect
-
end
-
-
90
raise
-
end
-
-
25
def terminate
-
# array may change during iteration
-
5575
selectables = @selectables.reject(&:inflight?)
-
-
5575
selectables.each(&:terminate)
-
-
5569
until selectables.empty?
-
2246
next_tick
-
-
2246
selectables &= @selectables
-
end
-
end
-
-
25
def find_resolver(options)
-
5557
res = @selectables.find do |c|
-
49
c.is_a?(Resolver::Resolver) && options == c.options
-
end
-
-
5557
res.multi if res
-
end
-
-
25
def each_connection(&block)
-
26728
return enum_for(__method__) unless block
-
-
13627
@selectables.each do |c|
-
1978
case c
-
when Resolver::Resolver
-
199
c.each_connection(&block)
-
when Connection
-
1767
yield c
-
end
-
end
-
end
-
-
25
def find_connection(request_uri, options)
-
7341
each_connection.find do |connection|
-
1104
connection.match?(request_uri, options)
-
end
-
end
-
-
25
def find_mergeable_connection(connection)
-
5760
each_connection.find do |ch|
-
301
ch != connection && ch.mergeable?(connection)
-
end
-
end
-
-
# deregisters +io+ from selectables.
-
25
def deregister(io)
-
6511
@selectables.delete(io)
-
end
-
-
# register +io+.
-
25
def register(io)
-
6917
return if @selectables.include?(io)
-
-
6542
@selectables << io
-
end
-
-
25
private
-
-
25
def select(interval, &block)
-
# do not cause an infinite loop here.
-
#
-
# this may happen if timeout calculation actually triggered an error which causes
-
# the connections to be reaped (such as the total timeout error) before #select
-
# gets called.
-
9695806
return if interval.nil? && @selectables.empty?
-
-
9693577
return select_one(interval, &block) if @selectables.size == 1
-
-
463
select_many(interval, &block)
-
end
-
-
25
def select_many(interval, &block)
-
463
r, w = nil
-
-
# first, we group IOs based on interest type. On call to #interests however,
-
# things might already happen, and new IOs might be registered, so we might
-
# have to start all over again. We do this until we group all selectables
-
463
@selectables.delete_if do |io|
-
743
interests = io.interests
-
-
743
io.log(level: 2) { "[#{io.state}] registering for select (#{interests})#{" for #{interval} seconds" unless interval.nil?}" }
-
-
743
(r ||= []) << io if READABLE.include?(interests)
-
743
(w ||= []) << io if WRITABLE.include?(interests)
-
-
743
io.state == :closed
-
end
-
-
# TODO: what to do if there are no selectables?
-
-
463
readers, writers = IO.select(r, w, nil, interval)
-
-
463
if readers.nil? && writers.nil? && interval
-
100
[*r, *w].each { |io| io.handle_socket_timeout(interval) }
-
100
return
-
end
-
-
363
if writers
-
readers.each do |io|
-
247
yield io
-
-
# so that we don't yield 2 times
-
247
writers.delete(io)
-
363
end if readers
-
-
363
writers.each(&block)
-
else
-
readers.each(&block) if readers
-
end
-
end
-
-
25
def select_one(interval)
-
9693114
io = @selectables.first
-
-
9693114
return unless io
-
-
9693114
interests = io.interests
-
-
9693221
io.log(level: 2) { "[#{io.state}] registering for select (#{interests})#{" for #{interval} seconds" unless interval.nil?}" }
-
-
9693113
result = case interests
-
11297
when :r then io.to_io.wait_readable(interval)
-
7829
when :w then io.to_io.wait_writable(interval)
-
when :rw then io.to_io.wait(interval, :read_write)
-
9673987
when nil then return
-
end
-
-
19126
unless result || interval.nil?
-
424
io.handle_socket_timeout(interval) unless @is_timer_interval
-
424
return
-
end
-
# raise TimeoutError.new(interval, "timed out while waiting on select")
-
-
18702
yield io
-
# rescue IOError, SystemCallError
-
# @selectables.reject!(&:closed?)
-
# raise unless @selectables.empty?
-
end
-
-
25
def next_timeout
-
9695806
@is_timer_interval = false
-
-
9695806
timer_interval = @timers.wait_interval
-
-
9695806
connection_interval = @selectables.filter_map(&:timeout).min
-
-
9695806
return connection_interval unless timer_interval
-
-
9672367
if connection_interval.nil? || timer_interval <= connection_interval
-
9672332
@is_timer_interval = true
-
-
9672332
return timer_interval
-
end
-
-
35
connection_interval
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
# Class implementing the APIs being used publicly.
-
#
-
# HTTPX.get(..) #=> delegating to an internal HTTPX::Session object.
-
# HTTPX.plugin(..).get(..) #=> creating an intermediate HTTPX::Session with plugin, then sending the GET request
-
25
class Session
-
25
include Loggable
-
25
include Chainable
-
-
# initializes the session with a set of +options+, which will be shared by all
-
# requests sent from it.
-
#
-
# When pass a block, it'll yield itself to it, then closes after the block is evaluated.
-
25
def initialize(options = EMPTY_HASH, &blk)
-
8849
@options = self.class.default_options.merge(options)
-
8849
@persistent = @options.persistent
-
8849
@pool = @options.pool_class.new(@options.pool_options)
-
8849
@wrapped = false
-
8849
@closing = false
-
8849
INSTANCES[self] = self if @persistent && @options.close_on_fork && INSTANCES
-
8849
wrap(&blk) if blk
-
end
-
-
# Yields itself the block, then closes it after the block is evaluated.
-
#
-
# session.wrap do |http|
-
# http.get("https://wikipedia.com")
-
# end # wikipedia connection closes here
-
25
def wrap
-
458
prev_wrapped = @wrapped
-
458
@wrapped = true
-
458
was_initialized = false
-
458
current_selector = get_current_selector do
-
458
selector = Selector.new
-
-
458
set_current_selector(selector)
-
-
458
was_initialized = true
-
-
458
selector
-
end
-
begin
-
458
yield self
-
ensure
-
458
unless prev_wrapped
-
458
if @persistent
-
1
deactivate(current_selector)
-
else
-
457
close(current_selector)
-
end
-
end
-
458
@wrapped = prev_wrapped
-
458
set_current_selector(nil) if was_initialized
-
end
-
end
-
-
# closes all the active connections from the session.
-
#
-
# when called directly without specifying +selector+, all available connections
-
# will be picked up from the connection pool and closed. Connections in use
-
# by other sessions, or same session in a different thread, will not be reaped.
-
25
def close(selector = Selector.new)
-
# throw resolvers away from the pool
-
5575
@pool.reset_resolvers
-
-
# preparing to throw away connections
-
14539
while (connection = @pool.pop_connection)
-
3389
next if connection.state == :closed
-
-
159
select_connection(connection, selector)
-
end
-
begin
-
5575
@closing = true
-
5575
selector.terminate
-
ensure
-
5575
@closing = false
-
end
-
end
-
-
# performs one, or multple requests; it accepts:
-
#
-
# 1. one or multiple HTTPX::Request objects;
-
# 2. an HTTP verb, then a sequence of URIs or URI/options tuples;
-
# 3. one or multiple HTTP verb / uri / (optional) options tuples;
-
#
-
# when present, the set of +options+ kwargs is applied to all of the
-
# sent requests.
-
#
-
# respectively returns a single HTTPX::Response response, or all of them in an Array, in the same order.
-
#
-
# resp1 = session.request(req1)
-
# resp1, resp2 = session.request(req1, req2)
-
# resp1 = session.request("GET", "https://server.org/a")
-
# resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"])
-
# resp1, resp2 = session.request(["GET", "https://server.org/a"], ["GET", "https://server.org/b"])
-
# resp1 = session.request("POST", "https://server.org/a", form: { "foo" => "bar" })
-
# resp1, resp2 = session.request(["POST", "https://server.org/a", form: { "foo" => "bar" }], ["GET", "https://server.org/b"])
-
# resp1, resp2 = session.request("GET", ["https://server.org/a", "https://server.org/b"], headers: { "x-api-token" => "TOKEN" })
-
#
-
25
def request(*args, **params)
-
5845
raise ArgumentError, "must perform at least one request" if args.empty?
-
-
5845
requests = args.first.is_a?(Request) ? args : build_requests(*args, params)
-
5808
responses = send_requests(*requests)
-
5694
return responses.first if responses.size == 1
-
-
156
responses
-
end
-
-
# returns a HTTP::Request instance built from the HTTP +verb+, the request +uri+, and
-
# the optional set of request-specific +options+. This request **must** be sent through
-
# the same session it was built from.
-
#
-
# req = session.build_request("GET", "https://server.com")
-
# resp = session.request(req)
-
25
def build_request(verb, uri, params = EMPTY_HASH, options = @options)
-
7274
rklass = options.request_class
-
7274
request = rklass.new(verb, uri, options, params)
-
7237
request.persistent = @persistent
-
7237
set_request_callbacks(request)
-
7237
request
-
end
-
-
25
def select_connection(connection, selector)
-
6893
pin_connection(connection, selector)
-
6893
selector.register(connection)
-
end
-
-
25
def pin_connection(connection, selector)
-
6909
connection.current_session = self
-
6909
connection.current_selector = selector
-
end
-
-
25
alias_method :select_resolver, :select_connection
-
-
25
def deselect_connection(connection, selector, cloned = false)
-
6191
selector.deregister(connection)
-
-
# when connections coalesce
-
6191
return if connection.state == :idle
-
-
6167
return if cloned
-
-
6161
return if @closing && connection.state == :closed
-
-
6155
@pool.checkin_connection(connection)
-
end
-
-
25
def deselect_resolver(resolver, selector)
-
308
selector.deregister(resolver)
-
-
308
return if @closing && resolver.closed?
-
-
308
@pool.checkin_resolver(resolver)
-
end
-
-
25
def try_clone_connection(connection, selector, family)
-
406
connection.family ||= family
-
-
406
return connection if connection.family == family
-
-
new_connection = connection.class.new(connection.origin, connection.options)
-
-
new_connection.family = family
-
-
connection.sibling = new_connection
-
-
do_init_connection(new_connection, selector)
-
new_connection
-
end
-
-
# returns the HTTPX::Connection through which the +request+ should be sent through.
-
25
def find_connection(request_uri, selector, options)
-
7341
if (connection = selector.find_connection(request_uri, options))
-
1054
connection.idling if connection.state == :closed
-
1054
connection.log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in selector##{selector.object_id}" }
-
1054
return connection
-
end
-
-
6287
connection = @pool.checkout_connection(request_uri, options)
-
-
6311
connection.log(level: 2) { "found connection##{connection.object_id}(#{connection.state}) in pool##{@pool.object_id}" }
-
-
6263
case connection.state
-
when :idle
-
5721
do_init_connection(connection, selector)
-
when :open
-
54
if options.io
-
54
select_connection(connection, selector)
-
else
-
pin_connection(connection, selector)
-
end
-
when :closing, :closed
-
472
connection.idling
-
472
select_connection(connection, selector)
-
else
-
16
pin_connection(connection, selector)
-
end
-
-
6208
connection
-
end
-
-
25
private
-
-
25
def deactivate(selector)
-
418
selector.each_connection do |connection|
-
310
connection.deactivate
-
310
deselect_connection(connection, selector) if connection.state == :inactive
-
end
-
end
-
-
# callback executed when an HTTP/2 promise frame has been received.
-
25
def on_promise(_, stream)
-
6
log(level: 2) { "#{stream.id}: refusing stream!" }
-
6
stream.refuse
-
end
-
-
# returns the corresponding HTTP::Response to the given +request+ if it has been received.
-
25
def fetch_response(request, _selector, _options)
-
9700106
response = request.response
-
-
9700106
response if response && response.finished?
-
end
-
-
# sends the +request+ to the corresponding HTTPX::Connection
-
25
def send_request(request, selector, options = request.options)
-
error = begin
-
7268
catch(:resolve_error) do
-
7268
connection = find_connection(request.uri, selector, options)
-
7171
connection.send(request)
-
end
-
rescue StandardError => e
-
30
e
-
end
-
7262
return unless error && error.is_a?(Exception)
-
-
97
raise error unless error.is_a?(Error)
-
-
97
response = ErrorResponse.new(request, error)
-
97
request.response = response
-
97
request.emit(:response, response)
-
end
-
-
# returns a set of HTTPX::Request objects built from the given +args+ and +options+.
-
25
def build_requests(*args, params)
-
5351
requests = if args.size == 1
-
60
reqs = args.first
-
60
reqs.map do |verb, uri, ps = EMPTY_HASH|
-
120
request_params = params
-
120
request_params = request_params.merge(ps) unless ps.empty?
-
120
build_request(verb, uri, request_params)
-
end
-
else
-
5291
verb, uris = args
-
5291
if uris.respond_to?(:each)
-
5111
uris.enum_for(:each).map do |uri, ps = EMPTY_HASH|
-
5834
request_params = params
-
5834
request_params = request_params.merge(ps) unless ps.empty?
-
5834
build_request(verb, uri, request_params)
-
end
-
else
-
180
[build_request(verb, uris, params)]
-
end
-
end
-
5314
raise ArgumentError, "wrong number of URIs (given 0, expect 1..+1)" if requests.empty?
-
-
5314
requests
-
end
-
-
25
def set_request_callbacks(request)
-
7142
request.on(:promise, &method(:on_promise))
-
end
-
-
25
def do_init_connection(connection, selector)
-
5721
resolve_connection(connection, selector) unless connection.family
-
end
-
-
# sends an array of HTTPX::Request +requests+, returns the respective array of HTTPX::Response objects.
-
25
def send_requests(*requests)
-
11192
selector = get_current_selector { Selector.new }
-
begin
-
5882
_send_requests(requests, selector)
-
5876
receive_requests(requests, selector)
-
ensure
-
5870
unless @wrapped
-
5310
if @persistent
-
417
deactivate(selector)
-
else
-
4893
close(selector)
-
end
-
end
-
end
-
end
-
-
# sends an array of HTTPX::Request objects
-
25
def _send_requests(requests, selector)
-
5882
requests.each do |request|
-
6654
send_request(request, selector)
-
end
-
end
-
-
# returns the array of HTTPX::Response objects corresponding to the array of HTTPX::Request +requests+.
-
25
def receive_requests(requests, selector)
-
# @type var responses: Array[response]
-
5876
responses = []
-
-
# guarantee ordered responses
-
5876
loop do
-
6654
request = requests.first
-
-
6654
return responses unless request
-
-
9699203
catch(:coalesced) { selector.next_tick } until (response = fetch_response(request, selector, request.options))
-
6546
request.emit(:complete, response)
-
-
6546
responses << response
-
6546
requests.shift
-
-
6546
break if requests.empty?
-
-
778
next unless selector.empty?
-
-
# in some cases, the pool of connections might have been drained because there was some
-
# handshake error, and the error responses have already been emitted, but there was no
-
# opportunity to traverse the requests, hence we're returning only a fraction of the errors
-
# we were supposed to. This effectively fetches the existing responses and return them.
-
while (request = requests.shift)
-
response = fetch_response(request, selector, request.options)
-
request.emit(:complete, response) if response
-
responses << response
-
end
-
break
-
end
-
5768
responses
-
end
-
-
25
def resolve_connection(connection, selector)
-
5745
if connection.addresses || connection.open?
-
#
-
# there are two cases in which we want to activate initialization of
-
# connection immediately:
-
#
-
# 1. when the connection already has addresses, i.e. it doesn't need to
-
# resolve a name (not the same as name being an IP, yet)
-
# 2. when the connection is initialized with an external already open IO.
-
#
-
188
on_resolver_connection(connection, selector)
-
188
return
-
end
-
-
5557
resolver = find_resolver_for(connection, selector)
-
-
5557
resolver.early_resolve(connection) || resolver.lazy_resolve(connection)
-
end
-
-
25
def on_resolver_connection(connection, selector)
-
5760
from_pool = false
-
5760
found_connection = selector.find_mergeable_connection(connection) || begin
-
5733
from_pool = true
-
5733
@pool.checkout_mergeable_connection(connection)
-
end
-
-
5760
return select_connection(connection, selector) unless found_connection
-
-
27
connection.log(level: 2) do
-
"try coalescing from #{from_pool ? "pool##{@pool.object_id}" : "selector##{selector.object_id}"} " \
-
"(conn##{found_connection.object_id}[#{found_connection.origin}])"
-
end
-
-
27
coalesce_connections(found_connection, connection, selector, from_pool)
-
end
-
-
25
def on_resolver_close(resolver, selector)
-
308
return if resolver.closed?
-
-
308
deselect_resolver(resolver, selector)
-
308
resolver.close unless resolver.closed?
-
end
-
-
25
def find_resolver_for(connection, selector)
-
5557
resolver = selector.find_resolver(connection.options)
-
-
5557
unless resolver
-
5555
resolver = @pool.checkout_resolver(connection.options)
-
5555
resolver.current_session = self
-
5555
resolver.current_selector = selector
-
end
-
-
5557
resolver
-
end
-
-
# coalesces +conn2+ into +conn1+. if +conn1+ was loaded from the connection pool
-
# (it is known via +from_pool+), then it adds its to the +selector+.
-
25
def coalesce_connections(conn1, conn2, selector, from_pool)
-
27
unless conn1.coalescable?(conn2)
-
14
conn2.log(level: 2) { "not coalescing with conn##{conn1.object_id}[#{conn1.origin}])" }
-
14
select_connection(conn2, selector)
-
14
@pool.checkin_connection(conn1) if from_pool
-
14
return false
-
end
-
-
13
conn2.log(level: 2) { "coalescing with conn##{conn1.object_id}[#{conn1.origin}])" }
-
13
conn2.coalesce!(conn1)
-
13
select_connection(conn1, selector) if from_pool
-
13
conn2.disconnect
-
13
true
-
end
-
-
25
def get_current_selector
-
6340
selector_store[self] || (yield if block_given?)
-
end
-
-
25
def set_current_selector(selector)
-
1320
if selector
-
862
selector_store[self] = selector
-
else
-
458
selector_store.delete(self)
-
end
-
end
-
-
25
def selector_store
-
7660
th_current = Thread.current
-
7660
th_current.thread_variable_get(:httpx_persistent_selector_store) || begin
-
127
{}.compare_by_identity.tap do |store|
-
127
th_current.thread_variable_set(:httpx_persistent_selector_store, store)
-
end
-
end
-
end
-
-
25
@default_options = Options.new
-
25
@default_options.freeze
-
25
@plugins = []
-
-
25
class << self
-
25
attr_reader :default_options
-
-
25
def inherited(klass)
-
4539
super
-
4539
klass.instance_variable_set(:@default_options, @default_options)
-
4539
klass.instance_variable_set(:@plugins, @plugins.dup)
-
4539
klass.instance_variable_set(:@callbacks, @callbacks.dup)
-
end
-
-
# returns a new HTTPX::Session instance, with the plugin pointed by +pl+ loaded.
-
#
-
# session_with_retries = session.plugin(:retries)
-
# session_with_custom = session.plugin(CustomPlugin)
-
#
-
25
def plugin(pl, options = nil, &block)
-
6106
label = pl
-
# raise Error, "Cannot add a plugin to a frozen config" if frozen?
-
6106
pl = Plugins.load_plugin(pl) if pl.is_a?(Symbol)
-
6106
if !@plugins.include?(pl)
-
5882
@plugins << pl
-
5882
pl.load_dependencies(self, &block) if pl.respond_to?(:load_dependencies)
-
-
5882
@default_options = @default_options.dup
-
-
5882
include(pl::InstanceMethods) if defined?(pl::InstanceMethods)
-
5882
extend(pl::ClassMethods) if defined?(pl::ClassMethods)
-
-
5882
opts = @default_options
-
5882
opts.extend_with_plugin_classes(pl)
-
5882
if defined?(pl::OptionsMethods)
-
-
2344
(pl::OptionsMethods.instance_methods - Object.instance_methods).each do |meth|
-
7136
opts.options_class.method_added(meth)
-
end
-
2344
@default_options = opts.options_class.new(opts)
-
end
-
-
5882
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
5882
@default_options = @default_options.merge(options) if options
-
-
5882
if pl.respond_to?(:subplugins)
-
24
pl.subplugins.transform_keys(&Plugins.method(:load_plugin)).each do |main_pl, sub_pl|
-
# in case the main plugin has already been loaded, then apply subplugin functionality
-
# immediately
-
24
next unless @plugins.include?(main_pl)
-
-
6
plugin(sub_pl, options, &block)
-
end
-
end
-
-
5882
pl.configure(self, &block) if pl.respond_to?(:configure)
-
-
5882
if label.is_a?(Symbol)
-
# in case an already-loaded plugin complements functionality of
-
# the plugin currently being loaded, loaded it now
-
4440
@plugins.each do |registered_pl|
-
10893
next if registered_pl == pl
-
-
6453
next unless registered_pl.respond_to?(:subplugins)
-
-
12
sub_pl = registered_pl.subplugins[label]
-
-
12
next unless sub_pl
-
-
12
plugin(sub_pl, options, &block)
-
end
-
end
-
-
5882
@default_options.freeze
-
5882
set_temporary_name("#{superclass}/#{pl}") if respond_to?(:set_temporary_name) # ruby 3.4 only
-
224
elsif options
-
# this can happen when two plugins are loaded, an one of them calls the other under the hood,
-
# albeit changing some default.
-
12
@default_options = pl.extra_options(@default_options) if pl.respond_to?(:extra_options)
-
12
@default_options = @default_options.merge(options) if options
-
-
12
@default_options.freeze
-
end
-
-
6106
self
-
end
-
end
-
-
# setup of the support for close_on_fork sessions.
-
# adapted from https://github.com/mperham/connection_pool/blob/main/lib/connection_pool.rb#L48
-
25
if Process.respond_to?(:fork)
-
25
INSTANCES = ObjectSpace::WeakMap.new
-
25
private_constant :INSTANCES
-
-
25
def self.after_fork
-
1
INSTANCES.each_value(&:close)
-
1
nil
-
end
-
-
25
if ::Process.respond_to?(:_fork)
-
21
module ForkTracker
-
21
def _fork
-
1
pid = super
-
1
Session.after_fork if pid.zero?
-
1
pid
-
end
-
end
-
21
Process.singleton_class.prepend(ForkTracker)
-
end
-
else
-
INSTANCES = nil
-
private_constant :INSTANCES
-
-
def self.after_fork
-
# noop
-
end
-
end
-
end
-
-
# session may be overridden by certain adapters.
-
25
S = Session
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
unless ENV.keys.grep(/\Ahttps?_proxy\z/i).empty?
-
1
proxy_session = plugin(:proxy)
-
1
remove_const(:Session)
-
1
const_set(:Session, proxy_session.class)
-
-
# redefine the default options static var, which needs to
-
# refresh options_class
-
1
options = proxy_session.class.default_options.to_hash
-
1
original_verbosity = $VERBOSE
-
1
$VERBOSE = nil
-
1
const_set(:Options, proxy_session.class.default_options.options_class)
-
1
options[:options_class] = Class.new(options[:options_class])
-
1
options.freeze
-
1
Options.send(:const_set, :DEFAULT_OPTIONS, options)
-
1
Session.instance_variable_set(:@default_options, Options.new(options))
-
1
$VERBOSE = original_verbosity
-
end
-
-
skipped
# :nocov:
-
skipped
if Session.default_options.debug_level > 2
-
skipped
proxy_session = plugin(:internal_telemetry)
-
skipped
remove_const(:Session)
-
skipped
const_set(:Session, proxy_session.class)
-
skipped
end
-
skipped
# :nocov:
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
class Timers
-
25
def initialize
-
5993
@intervals = []
-
end
-
-
25
def after(interval_in_secs, cb = nil, &blk)
-
35407
callback = cb || blk
-
-
35407
raise Error, "timer must have a callback" unless callback
-
-
# I'm assuming here that most requests will have the same
-
# request timeout, as in most cases they share common set of
-
# options. A user setting different request timeouts for 100s of
-
# requests will already have a hard time dealing with that.
-
64530
unless (interval = @intervals.bsearch { |t| t.interval == interval_in_secs })
-
7446
interval = Interval.new(interval_in_secs)
-
7446
@intervals << interval
-
7446
@intervals.sort!
-
end
-
-
35407
interval << callback
-
-
35407
@next_interval_at = nil
-
-
35407
Timer.new(interval, callback)
-
end
-
-
25
def wait_interval
-
9695806
drop_elapsed!
-
-
9695806
return if @intervals.empty?
-
-
9672367
@next_interval_at = Utils.now
-
-
9672367
@intervals.first.interval
-
end
-
-
25
def fire(error = nil)
-
9695686
raise error if error && error.timeout != @intervals.first
-
9695686
return if @intervals.empty? || !@next_interval_at
-
-
9671806
elapsed_time = Utils.elapsed_time(@next_interval_at)
-
-
9671806
drop_elapsed!(elapsed_time)
-
-
19337345
@intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
-
-
9671806
@next_interval_at = nil if @intervals.empty?
-
end
-
-
25
private
-
-
25
def drop_elapsed!(elapsed_time = 0)
-
# check first, if not elapsed, then return
-
19367612
first_interval = @intervals.first
-
-
19367612
return unless first_interval && first_interval.elapsed?(elapsed_time)
-
-
# TODO: would be nice to have a drop_while!
-
14036
@intervals = @intervals.drop_while { |interval| interval.elapse(elapsed_time) <= 0 }
-
end
-
-
25
class Timer
-
25
def initialize(interval, callback)
-
35407
@interval = interval
-
35407
@callback = callback
-
end
-
-
25
def cancel
-
52183
@interval.delete(@callback)
-
end
-
end
-
-
25
class Interval
-
25
include Comparable
-
-
25
attr_reader :interval
-
-
25
def initialize(interval)
-
7446
@interval = interval
-
7446
@callbacks = []
-
end
-
-
25
def <=>(other)
-
601
@interval <=> other.interval
-
end
-
-
25
def ==(other)
-
return @interval == other if other.is_a?(Numeric)
-
-
@interval == other.to_f # rubocop:disable Lint/FloatComparison
-
end
-
-
25
def to_f
-
Float(@interval)
-
end
-
-
25
def <<(callback)
-
35407
@callbacks << callback
-
end
-
-
25
def delete(callback)
-
52183
@callbacks.delete(callback)
-
end
-
-
25
def no_callbacks?
-
@callbacks.empty?
-
end
-
-
25
def elapsed?(elapsed = 0)
-
19344577
(@interval - elapsed) <= 0 || @callbacks.empty?
-
end
-
-
25
def elapse(elapsed)
-
# same as elapsing
-
9672794
return 0 if @callbacks.empty?
-
-
9666151
@interval -= elapsed
-
-
9666151
if @interval <= 0
-
511
cb = @callbacks.dup
-
511
cb.each(&:call)
-
end
-
-
9666151
@interval
-
end
-
end
-
25
private_constant :Interval
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Transcoder
-
25
module_function
-
-
25
def normalize_keys(key, value, cond = nil, &block)
-
2585
if cond && cond.call(value)
-
809
block.call(key.to_s, value)
-
1776
elsif value.respond_to?(:to_ary)
-
342
if value.empty?
-
96
block.call("#{key}[]")
-
else
-
246
value.to_ary.each do |element|
-
396
normalize_keys("#{key}[]", element, cond, &block)
-
end
-
end
-
1434
elsif value.respond_to?(:to_hash)
-
384
value.to_hash.each do |child_key, child_value|
-
384
normalize_keys("#{key}[#{child_key}]", child_value, cond, &block)
-
end
-
else
-
1050
block.call(key.to_s, value)
-
end
-
end
-
-
# based on https://github.com/rack/rack/blob/d15dd728440710cfc35ed155d66a98dc2c07ae42/lib/rack/query_parser.rb#L82
-
25
def normalize_query(params, name, v, depth)
-
138
raise Error, "params depth surpasses what's supported" if depth <= 0
-
-
138
name =~ /\A[\[\]]*([^\[\]]+)\]*/
-
138
k = Regexp.last_match(1) || ""
-
138
after = Regexp.last_match ? Regexp.last_match.post_match : ""
-
-
138
if k.empty?
-
12
return Array(v) if !v.empty? && name == "[]"
-
-
6
return
-
end
-
-
126
case after
-
when ""
-
42
params[k] = v
-
when "["
-
6
params[name] = v
-
when "[]"
-
12
params[k] ||= []
-
12
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
12
params[k] << v
-
when /^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/
-
24
child_key = Regexp.last_match(1)
-
24
params[k] ||= []
-
24
raise Error, "expected Array (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Array)
-
-
24
if params[k].last.is_a?(Hash) && !params_hash_has_key?(params[k].last, child_key)
-
6
normalize_query(params[k].last, child_key, v, depth - 1)
-
else
-
18
params[k] << normalize_query({}, child_key, v, depth - 1)
-
end
-
else
-
42
params[k] ||= {}
-
42
raise Error, "expected Hash (got #{params[k].class}) for param '#{k}'" unless params[k].is_a?(Hash)
-
-
42
params[k] = normalize_query(params[k], after, v, depth - 1)
-
end
-
-
126
params
-
end
-
-
25
def params_hash_has_key?(hash, key)
-
12
return false if key.include?("[]")
-
-
12
key.split(/[\[\]]+/).inject(hash) do |h, part|
-
12
next h if part == ""
-
12
return false unless h.is_a?(Hash) && h.key?(part)
-
-
6
h[part]
-
end
-
-
6
true
-
end
-
end
-
end
-
-
25
require "httpx/transcoder/body"
-
25
require "httpx/transcoder/form"
-
25
require "httpx/transcoder/json"
-
25
require "httpx/transcoder/chunker"
-
25
require "httpx/transcoder/deflate"
-
25
require "httpx/transcoder/gzip"
-
# frozen_string_literal: true
-
-
25
require "delegate"
-
-
25
module HTTPX::Transcoder
-
25
module Body
-
25
class Error < HTTPX::Error; end
-
-
25
module_function
-
-
25
class Encoder < SimpleDelegator
-
25
def initialize(body)
-
1142
body = body.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && body.is_a?(Pathname)
-
1142
@body = body
-
1142
super(body)
-
end
-
-
25
def bytesize
-
4414
if @body.respond_to?(:bytesize)
-
1972
@body.bytesize
-
2442
elsif @body.respond_to?(:to_ary)
-
816
@body.sum(&:bytesize)
-
1626
elsif @body.respond_to?(:size)
-
1134
@body.size || Float::INFINITY
-
492
elsif @body.respond_to?(:length)
-
270
@body.length || Float::INFINITY
-
222
elsif @body.respond_to?(:each)
-
216
Float::INFINITY
-
else
-
6
raise Error, "cannot determine size of body: #{@body.inspect}"
-
end
-
end
-
-
25
def content_type
-
1082
"application/octet-stream"
-
end
-
end
-
-
25
def encode(body)
-
1142
Encoder.new(body)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "forwardable"
-
-
25
module HTTPX::Transcoder
-
25
module Chunker
-
25
class Error < HTTPX::Error; end
-
-
25
CRLF = "\r\n".b
-
-
25
class Encoder
-
25
extend Forwardable
-
-
25
def initialize(body)
-
72
@raw = body
-
end
-
-
25
def each
-
72
return enum_for(__method__) unless block_given?
-
-
72
@raw.each do |chunk|
-
336
yield "#{chunk.bytesize.to_s(16)}#{CRLF}#{chunk}#{CRLF}"
-
end
-
72
yield "0#{CRLF}"
-
end
-
-
25
def respond_to_missing?(meth, *args)
-
84
@raw.respond_to?(meth, *args) || super
-
end
-
end
-
-
25
class Decoder
-
25
extend Forwardable
-
-
25
def_delegator :@buffer, :empty?
-
-
25
def_delegator :@buffer, :<<
-
-
25
def_delegator :@buffer, :clear
-
-
25
def initialize(buffer, trailers = false)
-
86
@buffer = buffer
-
86
@chunk_buffer = "".b
-
86
@finished = false
-
86
@state = :length
-
86
@trailers = trailers
-
end
-
-
25
def to_s
-
80
@buffer
-
end
-
-
25
def each
-
153
loop do
-
896
case @state
-
when :length
-
256
index = @buffer.index(CRLF)
-
256
return unless index && index.positive?
-
-
# Read hex-length
-
256
hexlen = @buffer.byteslice(0, index)
-
256
@buffer = @buffer.byteslice(index..-1) || "".b
-
256
hexlen[/\h/] || raise(Error, "wrong chunk size line: #{hexlen}")
-
256
@chunk_length = hexlen.hex
-
# check if is last chunk
-
256
@finished = @chunk_length.zero?
-
256
nextstate(:crlf)
-
when :crlf
-
426
crlf_size = @finished && !@trailers ? 4 : 2
-
# consume CRLF
-
426
return if @buffer.bytesize < crlf_size
-
426
raise Error, "wrong chunked encoding format" unless @buffer.start_with?(CRLF * (crlf_size / 2))
-
-
426
@buffer = @buffer.byteslice(crlf_size..-1)
-
426
if @chunk_length.nil?
-
170
nextstate(:length)
-
else
-
256
return if @finished
-
-
176
nextstate(:data)
-
end
-
when :data
-
214
chunk = @buffer.byteslice(0, @chunk_length)
-
214
@buffer = @buffer.byteslice(@chunk_length..-1) || "".b
-
214
@chunk_buffer << chunk
-
214
@chunk_length -= chunk.bytesize
-
214
if @chunk_length.zero?
-
176
yield @chunk_buffer unless @chunk_buffer.empty?
-
170
@chunk_buffer.clear
-
170
@chunk_length = nil
-
170
nextstate(:crlf)
-
end
-
end
-
810
break if @buffer.empty?
-
end
-
end
-
-
25
def finished?
-
147
@finished
-
end
-
-
25
private
-
-
25
def nextstate(state)
-
772
@state = state
-
end
-
end
-
-
25
module_function
-
-
25
def encode(chunks)
-
72
Encoder.new(chunks)
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "zlib"
-
25
require_relative "utils/deflater"
-
-
25
module HTTPX
-
25
module Transcoder
-
25
module Deflate
-
25
class Deflater < Transcoder::Deflater
-
25
def deflate(chunk)
-
54
@deflater ||= Zlib::Deflate.new
-
-
54
if chunk.nil?
-
36
unless @deflater.closed?
-
18
last = @deflater.finish
-
18
@deflater.close
-
18
last.empty? ? nil : last
-
end
-
else
-
18
@deflater.deflate(chunk)
-
end
-
end
-
end
-
-
25
module_function
-
-
25
def encode(body)
-
18
Deflater.new(body)
-
end
-
-
25
def decode(response, bytesize: nil)
-
12
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
12
GZIP::Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "forwardable"
-
25
require "uri"
-
25
require_relative "multipart"
-
-
25
module HTTPX
-
25
module Transcoder
-
25
module Form
-
25
module_function
-
-
25
PARAM_DEPTH_LIMIT = 32
-
-
25
class Encoder
-
25
extend Forwardable
-
-
25
def_delegator :@raw, :to_s
-
-
25
def_delegator :@raw, :to_str
-
-
25
def_delegator :@raw, :bytesize
-
-
25
def_delegator :@raw, :==
-
-
25
def initialize(form)
-
540
@raw = form.each_with_object("".b) do |(key, val), buf|
-
900
HTTPX::Transcoder.normalize_keys(key, val) do |k, v|
-
1050
buf << "&" unless buf.empty?
-
1050
buf << URI.encode_www_form_component(k)
-
1050
buf << "=#{URI.encode_www_form_component(v.to_s)}" unless v.nil?
-
end
-
end
-
end
-
-
25
def content_type
-
420
"application/x-www-form-urlencoded"
-
end
-
end
-
-
25
module Decoder
-
25
module_function
-
-
25
def call(response, *)
-
30
URI.decode_www_form(response.to_s).each_with_object({}) do |(field, value), params|
-
72
HTTPX::Transcoder.normalize_query(params, field, value, PARAM_DEPTH_LIMIT)
-
end
-
end
-
end
-
-
25
def encode(form)
-
1259
if multipart?(form)
-
719
Multipart::Encoder.new(form)
-
else
-
540
Encoder.new(form)
-
end
-
end
-
-
25
def decode(response)
-
48
content_type = response.content_type.mime_type
-
-
48
case content_type
-
when "application/x-www-form-urlencoded"
-
30
Decoder
-
when "multipart/form-data"
-
12
Multipart::Decoder.new(response)
-
else
-
6
raise Error, "invalid form mime type (#{content_type})"
-
end
-
end
-
-
25
def multipart?(data)
-
1259
data.any? do |_, v|
-
1667
Multipart::MULTIPART_VALUE_COND.call(v) ||
-
1284
(v.respond_to?(:to_ary) && v.to_ary.any?(&Multipart::MULTIPART_VALUE_COND)) ||
-
1572
(v.respond_to?(:to_hash) && v.to_hash.any? { |_, e| Multipart::MULTIPART_VALUE_COND.call(e) })
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "zlib"
-
-
25
module HTTPX
-
25
module Transcoder
-
25
module GZIP
-
25
class Deflater < Transcoder::Deflater
-
25
def initialize(body)
-
42
@compressed_chunk = "".b
-
42
super
-
end
-
-
25
def deflate(chunk)
-
84
@deflater ||= Zlib::GzipWriter.new(self)
-
-
84
if chunk.nil?
-
42
unless @deflater.closed?
-
42
@deflater.flush
-
42
@deflater.close
-
42
compressed_chunk
-
end
-
else
-
42
@deflater.write(chunk)
-
42
compressed_chunk
-
end
-
end
-
-
25
private
-
-
25
def write(chunk)
-
126
@compressed_chunk << chunk
-
end
-
-
25
def compressed_chunk
-
84
@compressed_chunk.dup
-
ensure
-
84
@compressed_chunk.clear
-
end
-
end
-
-
25
class Inflater
-
25
def initialize(bytesize)
-
131
@inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32)
-
131
@bytesize = bytesize
-
end
-
-
25
def call(chunk)
-
348
buffer = @inflater.inflate(chunk)
-
348
@bytesize -= chunk.bytesize
-
348
if @bytesize <= 0
-
88
buffer << @inflater.finish
-
88
@inflater.close
-
end
-
348
buffer
-
end
-
end
-
-
25
module_function
-
-
25
def encode(body)
-
42
Deflater.new(body)
-
end
-
-
25
def decode(response, bytesize: nil)
-
119
bytesize ||= response.headers.key?("content-length") ? response.headers["content-length"].to_i : Float::INFINITY
-
119
Inflater.new(bytesize)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "forwardable"
-
-
25
module HTTPX::Transcoder
-
25
module JSON
-
25
module_function
-
-
25
JSON_REGEX = %r{
-
\b
-
application/
-
# optional vendor specific type
-
(?:
-
# token as per https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6
-
[!#$%&'*+\-.^_`|~0-9a-z]+
-
# literal plus sign
-
\+
-
)?
-
json
-
\b
-
}ix.freeze
-
-
25
class Encoder
-
25
extend Forwardable
-
-
25
def_delegator :@raw, :to_s
-
-
25
def_delegator :@raw, :bytesize
-
-
25
def_delegator :@raw, :==
-
-
25
def initialize(json)
-
63
@raw = JSON.json_dump(json)
-
63
@charset = @raw.encoding.name.downcase
-
end
-
-
25
def content_type
-
63
"application/json; charset=#{@charset}"
-
end
-
end
-
-
25
def encode(json)
-
63
Encoder.new(json)
-
end
-
-
25
def decode(response)
-
99
content_type = response.content_type.mime_type
-
-
99
raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)
-
-
87
method(:json_load)
-
end
-
-
# rubocop:disable Style/SingleLineMethods
-
25
if defined?(MultiJson)
-
4
def json_load(*args); MultiJson.load(*args); end
-
2
def json_dump(*args); MultiJson.dump(*args); end
-
24
elsif defined?(Oj)
-
5
def json_load(response, *args); Oj.load(response.to_s, *args); end
-
3
def json_dump(obj, options = {}); Oj.dump(obj, { mode: :compat }.merge(options)); end
-
22
elsif defined?(Yajl)
-
4
def json_load(response, *args); Yajl::Parser.new(*args).parse(response.to_s); end
-
2
def json_dump(*args); Yajl::Encoder.encode(*args); end
-
else
-
21
require "json"
-
99
def json_load(*args); ::JSON.parse(*args); end
-
81
def json_dump(*args); ::JSON.dump(*args); end
-
end
-
# rubocop:enable Style/SingleLineMethods
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require_relative "multipart/encoder"
-
25
require_relative "multipart/decoder"
-
25
require_relative "multipart/part"
-
25
require_relative "multipart/mime_type_detector"
-
-
25
module HTTPX::Transcoder
-
25
module Multipart
-
25
MULTIPART_VALUE_COND = lambda do |value|
-
3688
value.respond_to?(:read) ||
-
2644
(value.respond_to?(:to_hash) &&
-
value.key?(:body) &&
-
484
(value.key?(:filename) || value.key?(:content_type)))
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "tempfile"
-
25
require "delegate"
-
-
25
module HTTPX
-
25
module Transcoder
-
25
module Multipart
-
25
class FilePart < SimpleDelegator
-
25
attr_reader :original_filename, :content_type
-
-
25
def initialize(filename, content_type)
-
24
@original_filename = filename
-
24
@content_type = content_type
-
24
@current = nil
-
24
@file = Tempfile.new("httpx", encoding: Encoding::BINARY, mode: File::RDWR)
-
24
super(@file)
-
end
-
end
-
-
25
class Decoder
-
25
include HTTPX::Utils
-
-
25
CRLF = "\r\n"
-
25
BOUNDARY_RE = /;\s*boundary=([^;]+)/i.freeze
-
25
MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{CRLF}/ni.freeze
-
25
MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*;\s*name=(#{VALUE})/ni.freeze
-
25
MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{CRLF}]*)/ni.freeze
-
25
WINDOW_SIZE = 2 << 14
-
-
25
def initialize(response)
-
@boundary = begin
-
12
m = response.headers["content-type"].to_s[BOUNDARY_RE, 1]
-
12
raise Error, "no boundary declared in content-type header" unless m
-
-
12
m.strip
-
end
-
12
@buffer = "".b
-
12
@parts = {}
-
12
@intermediate_boundary = "--#{@boundary}"
-
12
@state = :idle
-
end
-
-
25
def call(response, *)
-
12
response.body.each do |chunk|
-
12
@buffer << chunk
-
-
12
parse
-
end
-
-
12
raise Error, "invalid or unsupported multipart format" unless @buffer.empty?
-
-
12
@parts
-
end
-
-
25
private
-
-
25
def parse
-
12
case @state
-
when :idle
-
12
raise Error, "payload does not start with boundary" unless @buffer.start_with?("#{@intermediate_boundary}#{CRLF}")
-
-
12
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize + 2..-1)
-
-
12
@state = :part_header
-
when :part_header
-
36
idx = @buffer.index("#{CRLF}#{CRLF}")
-
-
# raise Error, "couldn't parse part headers" unless idx
-
36
return unless idx
-
-
# @type var head: String
-
36
head = @buffer.byteslice(0..idx + 4 - 1)
-
-
36
@buffer = @buffer.byteslice(head.bytesize..-1)
-
-
36
content_type = head[MULTIPART_CONTENT_TYPE, 1] || "text/plain"
-
72
if (name = head[MULTIPART_CONTENT_DISPOSITION, 1])
-
36
name = /\A"(.*)"\Z/ =~ name ? Regexp.last_match(1) : name.dup
-
36
name.gsub!(/\\(.)/, "\\1")
-
name
-
else
-
name = head[MULTIPART_CONTENT_ID, 1]
-
end
-
-
36
filename = HTTPX::Utils.get_filename(head)
-
-
36
name = filename || +"#{content_type}[]" if name.nil? || name.empty?
-
-
36
@current = name
-
-
36
@parts[name] = if filename
-
24
FilePart.new(filename, content_type)
-
else
-
12
"".b
-
end
-
-
36
@state = :part_body
-
when :part_body
-
36
part = @parts[@current]
-
-
36
body_separator = if part.is_a?(FilePart)
-
24
"#{CRLF}#{CRLF}"
-
else
-
12
CRLF
-
end
-
36
idx = @buffer.index(body_separator)
-
-
36
if idx
-
36
payload = @buffer.byteslice(0..idx - 1)
-
36
@buffer = @buffer.byteslice(idx + body_separator.bytesize..-1)
-
36
part << payload
-
36
part.rewind if part.respond_to?(:rewind)
-
36
@state = :parse_boundary
-
else
-
part << @buffer
-
@buffer.clear
-
end
-
when :parse_boundary
-
36
raise Error, "payload does not start with boundary" unless @buffer.start_with?(@intermediate_boundary)
-
-
36
@buffer = @buffer.byteslice(@intermediate_boundary.bytesize..-1)
-
-
36
if @buffer == "--"
-
12
@buffer.clear
-
12
@state = :done
-
12
return
-
24
elsif @buffer.start_with?(CRLF)
-
24
@buffer = @buffer.byteslice(2..-1)
-
24
@state = :part_header
-
else
-
return
-
end
-
when :done
-
raise Error, "parsing should have been over by now"
-
end until @buffer.empty?
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Transcoder::Multipart
-
25
class Encoder
-
25
attr_reader :bytesize
-
-
25
def initialize(form)
-
719
@boundary = ("-" * 21) << SecureRandom.hex(21)
-
719
@part_index = 0
-
719
@buffer = "".b
-
-
719
@form = form
-
719
@bytesize = 0
-
719
@parts = to_parts(form)
-
end
-
-
25
def content_type
-
719
"multipart/form-data; boundary=#{@boundary}"
-
end
-
-
25
def to_s
-
18
read || ""
-
ensure
-
18
rewind
-
end
-
-
25
def read(length = nil, outbuf = nil)
-
2654
data = String(outbuf).clear.force_encoding(Encoding::BINARY) if outbuf
-
2654
data ||= "".b
-
-
2654
read_chunks(data, length)
-
-
2654
data unless length && data.empty?
-
end
-
-
25
def rewind
-
42
form = @form.each_with_object([]) do |(key, val), aux|
-
42
if val.respond_to?(:path) && val.respond_to?(:reopen) && val.respond_to?(:closed?) && val.closed?
-
# @type var val: File
-
42
val = val.reopen(val.path, File::RDONLY)
-
end
-
42
val.rewind if val.respond_to?(:rewind)
-
42
aux << [key, val]
-
end
-
42
@form = form
-
42
@bytesize = 0
-
42
@parts = to_parts(form)
-
42
@part_index = 0
-
end
-
-
25
private
-
-
25
def to_parts(form)
-
761
params = form.each_with_object([]) do |(key, val), aux|
-
905
Transcoder.normalize_keys(key, val, MULTIPART_VALUE_COND) do |k, v|
-
905
next if v.nil?
-
-
905
value, content_type, filename = Part.call(v)
-
-
905
header = header_part(k, content_type, filename)
-
905
@bytesize += header.size
-
905
aux << header
-
-
905
@bytesize += value.size
-
905
aux << value
-
-
905
delimiter = StringIO.new("\r\n")
-
905
@bytesize += delimiter.size
-
905
aux << delimiter
-
end
-
end
-
761
final_delimiter = StringIO.new("--#{@boundary}--\r\n")
-
761
@bytesize += final_delimiter.size
-
761
params << final_delimiter
-
-
761
params
-
end
-
-
25
def header_part(key, content_type, filename)
-
905
header = "--#{@boundary}\r\n".b
-
905
header << "Content-Disposition: form-data; name=#{key.inspect}".b
-
905
header << "; filename=#{filename.inspect}" if filename
-
905
header << "\r\nContent-Type: #{content_type}\r\n\r\n"
-
905
StringIO.new(header)
-
end
-
-
25
def read_chunks(buffer, length = nil)
-
2654
while @part_index < @parts.size
-
8000
chunk = read_from_part(length)
-
-
8000
next unless chunk
-
-
4572
buffer << chunk.force_encoding(Encoding::BINARY)
-
-
4572
next unless length
-
-
4506
length -= chunk.bytesize
-
-
4506
break if length.zero?
-
end
-
end
-
-
# if there's a current part to read from, tries to read a chunk.
-
25
def read_from_part(max_length = nil)
-
8000
part = @parts[@part_index]
-
-
8000
chunk = part.read(max_length, @buffer)
-
-
8000
return chunk if chunk && !chunk.empty?
-
-
3428
part.close if part.respond_to?(:close)
-
-
3428
@part_index += 1
-
-
588
nil
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Transcoder::Multipart
-
25
module MimeTypeDetector
-
25
module_function
-
-
25
DEFAULT_MIMETYPE = "application/octet-stream"
-
-
# inspired by https://github.com/shrinerb/shrine/blob/master/lib/shrine/plugins/determine_mime_type.rb
-
25
if defined?(FileMagic)
-
1
MAGIC_NUMBER = 256 * 1024
-
-
1
def call(file, _)
-
1
return nil if file.eof? # FileMagic returns "application/x-empty" for empty files
-
-
1
mime = FileMagic.open(FileMagic::MAGIC_MIME_TYPE) do |filemagic|
-
1
filemagic.buffer(file.read(MAGIC_NUMBER))
-
end
-
-
1
file.rewind
-
-
1
mime
-
end
-
24
elsif defined?(Marcel)
-
1
def call(file, filename)
-
1
return nil if file.eof? # marcel returns "application/octet-stream" for empty files
-
-
1
Marcel::MimeType.for(file, name: filename)
-
end
-
-
23
elsif defined?(MimeMagic)
-
-
1
def call(file, _)
-
1
mime = MimeMagic.by_magic(file)
-
1
mime.type if mime
-
end
-
-
22
elsif system("which file", out: File::NULL)
-
22
require "open3"
-
-
22
def call(file, _)
-
517
return if file.eof? # file command returns "application/x-empty" for empty files
-
-
481
Open3.popen3(*%w[file --mime-type --brief -]) do |stdin, stdout, stderr, thread|
-
begin
-
481
::IO.copy_stream(file, stdin.binmode)
-
rescue Errno::EPIPE
-
end
-
481
file.rewind
-
481
stdin.close
-
-
481
status = thread.value
-
-
# call to file command failed
-
481
if status.nil? || !status.success?
-
$stderr.print(stderr.read)
-
else
-
-
481
output = stdout.read.strip
-
-
481
if output.include?("cannot open")
-
$stderr.print(output)
-
else
-
481
output
-
end
-
end
-
end
-
end
-
-
else
-
-
def call(_, _); end
-
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Transcoder::Multipart
-
25
module Part
-
25
module_function
-
-
25
def call(value)
-
# take out specialized objects of the way
-
905
if value.respond_to?(:filename) && value.respond_to?(:content_type) && value.respond_to?(:read)
-
96
return value, value.content_type, value.filename
-
end
-
-
809
content_type = filename = nil
-
-
809
if value.is_a?(Hash)
-
242
content_type = value[:content_type]
-
242
filename = value[:filename]
-
242
value = value[:body]
-
end
-
-
809
value = value.open(File::RDONLY, encoding: Encoding::BINARY) if Object.const_defined?(:Pathname) && value.is_a?(Pathname)
-
-
809
if value.respond_to?(:path) && value.respond_to?(:read)
-
# either a File, a Tempfile, or something else which has to quack like a file
-
521
filename ||= File.basename(value.path)
-
521
content_type ||= MimeTypeDetector.call(value, filename) || "application/octet-stream"
-
521
[value, content_type, filename]
-
else
-
288
[StringIO.new(value.to_s), content_type || "text/plain", filename]
-
end
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require "stringio"
-
-
25
module HTTPX
-
25
module Transcoder
-
25
class BodyReader
-
25
def initialize(body)
-
198
@body = if body.respond_to?(:read)
-
18
body.rewind if body.respond_to?(:rewind)
-
18
body
-
180
elsif body.respond_to?(:each)
-
36
body.enum_for(:each)
-
else
-
144
StringIO.new(body.to_s)
-
end
-
end
-
-
25
def bytesize
-
450
return @body.bytesize if @body.respond_to?(:bytesize)
-
-
414
Float::INFINITY
-
end
-
-
25
def read(length = nil, outbuf = nil)
-
438
return @body.read(length, outbuf) if @body.respond_to?(:read)
-
-
begin
-
96
chunk = @body.next
-
48
if outbuf
-
outbuf.clear.force_encoding(Encoding::BINARY)
-
outbuf << chunk
-
else
-
48
outbuf = chunk
-
end
-
48
outbuf unless length && outbuf.empty?
-
32
rescue StopIteration
-
end
-
end
-
-
25
def close
-
42
@body.close if @body.respond_to?(:close)
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
require_relative "body_reader"
-
-
25
module HTTPX
-
25
module Transcoder
-
25
class Deflater
-
25
attr_reader :content_type
-
-
25
def initialize(body)
-
72
@content_type = body.content_type
-
72
@body = BodyReader.new(body)
-
72
@closed = false
-
end
-
-
25
def bytesize
-
276
buffer_deflate!
-
-
276
@buffer.size
-
end
-
-
25
def read(length = nil, outbuf = nil)
-
354
return @buffer.read(length, outbuf) if @buffer
-
-
204
return if @closed
-
-
162
chunk = @body.read(length)
-
-
162
compressed_chunk = deflate(chunk)
-
-
162
return unless compressed_chunk
-
-
132
if outbuf
-
132
outbuf.clear.force_encoding(Encoding::BINARY)
-
132
outbuf << compressed_chunk
-
else
-
compressed_chunk
-
end
-
end
-
-
25
def close
-
42
return if @closed
-
-
42
@buffer.close if @buffer
-
-
42
@body.close
-
-
42
@closed = true
-
end
-
-
25
def rewind
-
24
return unless @buffer
-
-
12
@buffer.rewind
-
end
-
-
25
private
-
-
# rubocop:disable Naming/MemoizedInstanceVariableName
-
25
def buffer_deflate!
-
276
return @buffer if defined?(@buffer)
-
-
72
buffer = Response::Buffer.new(
-
threshold_size: Options::MAX_BODY_THRESHOLD_SIZE
-
)
-
72
::IO.copy_stream(self, buffer)
-
-
72
buffer.rewind if buffer.respond_to?(:rewind)
-
-
72
@buffer = buffer
-
end
-
# rubocop:enable Naming/MemoizedInstanceVariableName
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
25
module HTTPX
-
25
module Utils
-
25
using URIExtensions
-
-
25
TOKEN = %r{[^\s()<>,;:\\"/\[\]?=]+}.freeze
-
25
VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/.freeze
-
25
FILENAME_REGEX = /\s*filename=(#{VALUE})/.freeze
-
25
FILENAME_EXTENSION_REGEX = /\s*filename\*=(#{VALUE})/.freeze
-
-
25
module_function
-
-
25
def now
-
9701295
Process.clock_gettime(Process::CLOCK_MONOTONIC)
-
end
-
-
25
def elapsed_time(monotonic_timestamp)
-
9672180
Process.clock_gettime(Process::CLOCK_MONOTONIC) - monotonic_timestamp
-
end
-
-
# The value of this field can be either an HTTP-date or a number of
-
# seconds to delay after the response is received.
-
25
def parse_retry_after(retry_after)
-
# first: bet on it being an integer
-
47
Integer(retry_after)
-
rescue ArgumentError
-
# Then it's a datetime
-
12
time = Time.httpdate(retry_after)
-
12
time - Time.now
-
end
-
-
25
def get_filename(header, _prefix_regex = nil)
-
66
filename = nil
-
66
case header
-
when FILENAME_REGEX
-
42
filename = Regexp.last_match(1)
-
42
filename = Regexp.last_match(1) if filename =~ /^"(.*)"$/
-
when FILENAME_EXTENSION_REGEX
-
12
filename = Regexp.last_match(1)
-
12
encoding, _, filename = filename.split("'", 3)
-
end
-
-
66
return unless filename
-
-
102
filename = URI::DEFAULT_PARSER.unescape(filename) if filename.scan(/%.?.?/).all? { |s| /%[0-9a-fA-F]{2}/.match?(s) }
-
-
54
filename.scrub!
-
-
54
filename = filename.gsub(/\\(.)/, '\1') unless /\\[^\\"]/.match?(filename)
-
-
54
filename.force_encoding ::Encoding.find(encoding) if encoding
-
-
54
filename
-
end
-
-
25
URIParser = URI::RFC2396_Parser.new
-
-
25
def to_uri(uri)
-
14124
return URI(uri) unless uri.is_a?(String) && !uri.ascii_only?
-
-
25
uri = URI(URIParser.escape(uri))
-
-
25
non_ascii_hostname = URIParser.unescape(uri.host)
-
-
25
non_ascii_hostname.force_encoding(Encoding::UTF_8)
-
-
25
idna_hostname = Punycode.encode_hostname(non_ascii_hostname)
-
-
25
uri.host = idna_hostname
-
24
uri.non_ascii_hostname = non_ascii_hostname
-
24
uri
-
end
-
end
-
end