Skip to content

Commit

Permalink
DRY up connection handling logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeremy Bopp committed Sep 28, 2015
1 parent cede61d commit 085a622
Showing 1 changed file with 26 additions and 33 deletions.
59 changes: 26 additions & 33 deletions lib/net/ldap/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,56 +8,49 @@ class Net::LDAP::Connection #:nodoc:

def initialize(server)
@instrumentation_service = server[:instrumentation_service]
server[:hosts] = [[server[:host], server[:port]]] if server[:hosts].nil?

if server[:socket]
prepare_socket(server)
prepare_socket(server[:socket], server[:encryption])
else
open_connection(server)
hosts = server[:hosts]
hosts = [[server[:host], server[:port]]] if hosts.nil?
open_connection(hosts, server[:encryption])
end

yield self if block_given?
end

def prepare_socket(server)
@conn = server[:socket]

if server[:encryption]
setup_encryption server[:encryption]
end
def prepare_socket(socket, encryption, close = false)
@conn = socket
setup_encryption encryption if encryption
rescue
# Ensure the connection is closed when requested in the event of an SSL
# setup failure.
@conn.close if close
@conn = nil
raise
end

def open_connection(server)
def open_connection(hosts, encryption)
errors = []
server[:hosts].each do |host, port|
hosts.each do |host, port|
begin
return connect_to_host(host, port, server)
rescue Net::LDAP::Error
errors << $!
prepare_socket(TCPSocket.new(host, port), encryption, true)
return
rescue Net::LDAP::Error, SocketError, SystemCallError,
OpenSSL::SSL::SSLError
errors << [$!, host, port]
end
end

raise errors.first if errors.size == 1
raise Net::LDAP::Error,
"Unable to connect to any given server: \n #{errors.join("\n ")}"
end

def connect_to_host(host, port, server)
begin
@conn = TCPSocket.new(host, port)
rescue SocketError
raise Net::LDAP::Error, "No such address or other socket error."
rescue Errno::ECONNREFUSED
raise Net::LDAP::ConnectionRefusedError, "Server #{host} refused connection on port #{port}."
rescue Errno::EHOSTUNREACH => error
raise Net::LDAP::Error, "Host #{host} was unreachable (#{error.message})"
rescue Errno::ETIMEDOUT
raise Net::LDAP::Error, "Connection to #{host} timed out."
if errors.size == 1
error = errors.first.first
raise Net::LDAP::ConnectionRefusedError, error.message if error.kind_of? Errno::ECONNREFUSED
raise Net::LDAP::Error, error.message
end

if server[:encryption]
setup_encryption server[:encryption]
end
raise Net::LDAP::Error,
"Unable to connect to any given server: \n #{errors.map { |e, h, p| "#{e.class}: #{e.message} (#{h}:#{p})" }.join("\n ")}"
end

module GetbyteForSSLSocket
Expand Down

0 comments on commit 085a622

Please sign in to comment.