godns/hosts/hosts.go

71 lines
1.1 KiB
Go
Raw Normal View History

2020-01-25 17:43:02 +00:00
package hosts
2013-07-26 04:06:16 +00:00
import (
2015-02-03 12:32:18 +00:00
"net"
"time"
2019-09-26 04:43:17 +00:00
)
2013-07-26 04:06:16 +00:00
2020-01-25 17:43:02 +00:00
const (
notIPQuery = 0
_IP4Query = 4
_IP6Query = 6
)
var (
zeroDuration = time.Duration(0)
)
2020-01-25 17:43:02 +00:00
type Hosts interface {
Get(domain string, family int) ([]net.IP, time.Duration, bool)
2020-01-25 17:43:02 +00:00
}
type ProviderList struct {
providers []Provider
2013-07-26 04:06:16 +00:00
}
type Provider interface {
Get(domain string) ([]string, time.Duration, bool)
2018-07-01 03:08:29 +00:00
}
func NewHosts(providers []Provider) Hosts {
return &ProviderList{providers}
2013-07-26 10:54:19 +00:00
}
/*
2015-10-14 04:41:08 +00:00
Match local /etc/hosts file first, remote redis records second
2013-07-26 10:54:19 +00:00
*/
func (h *ProviderList) Get(domain string, family int) ([]net.IP, time.Duration, bool) {
2015-10-14 17:08:25 +00:00
var sips []string
2018-07-01 03:08:29 +00:00
var ok bool
2015-10-14 17:08:25 +00:00
var ip net.IP
var ips []net.IP
var ttl time.Duration
2015-02-12 06:54:02 +00:00
2018-07-01 03:08:29 +00:00
for _, provider := range h.providers {
sips, ttl, ok = provider.Get(domain)
2018-07-01 03:08:29 +00:00
if ok {
break
2015-02-12 06:54:02 +00:00
}
2013-07-26 10:54:19 +00:00
}
2015-02-03 12:32:18 +00:00
2015-10-14 17:08:25 +00:00
if sips == nil {
return nil, zeroDuration, false
2013-07-26 10:54:19 +00:00
}
2015-10-14 17:08:25 +00:00
for _, sip := range sips {
switch family {
case _IP4Query:
ip = net.ParseIP(sip).To4()
case _IP6Query:
ip = net.ParseIP(sip).To16()
default:
continue
}
if ip != nil {
ips = append(ips, ip)
}
2015-02-12 06:54:02 +00:00
}
2015-10-14 17:08:25 +00:00
return ips, ttl, ips != nil
2020-01-25 17:43:02 +00:00
}