diff options
author | Phil Dibowitz <phil@ipom.com> | 2021-04-15 19:28:58 -0700 |
---|---|---|
committer | Phil Dibowitz <phil@ipom.com> | 2021-04-15 20:14:44 -0700 |
commit | db08809916c84e74ec914bab3d313ec9dfc10195 (patch) | |
tree | 817e672e910558f0d45465c7b4d1a908f6e6c4ad | |
parent | c19e4a094f06d08c3331ba402709dff7020c155b (diff) | |
download | ohai-db08809916c84e74ec914bab3d313ec9dfc10195.tar.gz |
Fall back to v4-only getaddrinfo if we get socket errors
Handle the case where we have either v4- or v6-specific configuration
or network issues that causes gethostaddr() to fail
Note this was found due to a specific case: On OSX - and possibly others
(freebsd), if you have a linklocal address for your hostname in
/etc/hosts then `getaddrinfo` for your hostname will raise an exception.
Signed-off-by: Phil Dibowitz <phil@ipom.com>
-rw-r--r-- | lib/ohai/plugins/hostname.rb | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/lib/ohai/plugins/hostname.rb b/lib/ohai/plugins/hostname.rb index 7940ada2..abc37996 100644 --- a/lib/ohai/plugins/hostname.rb +++ b/lib/ohai/plugins/hostname.rb @@ -48,7 +48,28 @@ Ohai.plugin(:Hostname) do require "ipaddr" unless defined?(IPAddr) hostname = from_cmd("hostname") - addrinfo = Socket.getaddrinfo(hostname, nil).first + begin + addrinfo = Socket.getaddrinfo(hostname, nil).first + rescue SocketError + # In the event that we got an exception from Socket, it's possible + # that it will work if we restrict it to IPv4 only either because of + # IPv6 misconfiguration or other bugs. + # + # Specifically it's worth noting that on macOS, getaddrinfo() will choke + # if it gets back a link-local address (say if you have 'fe80::1 myhost' + # in /etc/hosts). This will raise: + # SocketError (getnameinfo: Non-recoverable failure in name resolution) + # + # But general misconfiguration could cause similar issues, so attempt to + # fall back to v4-only + begin + addrinfo = Socket.getaddrinfo(hostname, nil, :INET).first + rescue + # and if *that* fails, then try v6-only, in case we're in a v6-only + # environment with v4 config issues + addrinfo = Socket.getaddrinfo(hostname, nil, :INET6).first + end + end iaddr = IPAddr.new(addrinfo[3]) Socket.gethostbyaddr(iaddr.hton)[0] rescue |