Skip to content

Commit

Permalink
Merge pull request #739 from carlhoerberg/resolv
Browse files Browse the repository at this point in the history
Use Ruby Resolv instead of LibC for hostname lookup
  • Loading branch information
geemus committed Mar 21, 2021
2 parents 0c64ef1 + b3d3f89 commit bbb5bd7
Showing 1 changed file with 13 additions and 12 deletions.
25 changes: 13 additions & 12 deletions lib/excon/socket.rb
@@ -1,4 +1,6 @@
# frozen_string_literal: true
require 'resolv'

module Excon
class Socket
include Utils
Expand Down Expand Up @@ -95,20 +97,17 @@ def local_port
def connect
@socket = nil
exception = nil
hostname = @data[:hostname]
port = @port
family = @data[:family]

if @data[:proxy]
family = @data[:proxy][:family] || ::Socket::Constants::AF_UNSPEC
args = [@data[:proxy][:hostname], @data[:proxy][:port], family, ::Socket::Constants::SOCK_STREAM]
else
family = @data[:family] || ::Socket::Constants::AF_UNSPEC
args = [@data[:hostname], @port, family, ::Socket::Constants::SOCK_STREAM]
end
if RUBY_VERSION >= '1.9.2' && defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ruby'
args << nil << nil << false # no reverse lookup
hostname = @data[:proxy][:hostname]
port = @data[:proxy][:port]
family = @data[:proxy][:family]
end
addrinfo = ::Socket.getaddrinfo(*args)

addrinfo.each do |_, port, _, ip, a_family, s_type|
Resolv.each_address(hostname) do |ip|
# already succeeded on previous addrinfo
if @socket
break
Expand All @@ -120,8 +119,8 @@ def connect
# nonblocking connect
begin
sockaddr = ::Socket.sockaddr_in(port, ip)

socket = ::Socket.new(a_family, s_type, 0)
addrinfo = Addrinfo.getaddrinfo(ip, port, family, :STREAM).first
socket = ::Socket.new(addrinfo.pfamily, addrinfo.socktype, addrinfo.protocol)

if @data[:reuseaddr]
socket.setsockopt(::Socket::Constants::SOL_SOCKET, ::Socket::Constants::SO_REUSEADDR, true)
Expand Down Expand Up @@ -151,6 +150,8 @@ def connect
end
end

exception ||= Resolv::ResolvError.new("no address for #{hostname}")

# this will be our last encountered exception
fail exception unless @socket

Expand Down

0 comments on commit bbb5bd7

Please sign in to comment.