111 lines
1.8 KiB
Go
111 lines
1.8 KiB
Go
package hosts
|
|
|
|
import (
|
|
"meow.tf/joker/godns/log"
|
|
"meow.tf/joker/godns/settings"
|
|
"net"
|
|
"time"
|
|
|
|
"github.com/hoisie/redis"
|
|
)
|
|
|
|
const (
|
|
notIPQuery = 0
|
|
_IP4Query = 4
|
|
_IP6Query = 6
|
|
)
|
|
|
|
type Hosts interface {
|
|
Get(domain string, family int) ([]net.IP, bool)
|
|
TTL() uint32
|
|
}
|
|
|
|
type ProviderList struct {
|
|
settings settings.HostsSettings
|
|
providers []HostProvider
|
|
refreshInterval time.Duration
|
|
}
|
|
|
|
type HostProvider interface {
|
|
Get(domain string) ([]string, bool)
|
|
Refresh()
|
|
}
|
|
|
|
func NewHosts(hs settings.HostsSettings, rs settings.RedisSettings) Hosts {
|
|
providers := []HostProvider{
|
|
NewFileProvider(hs.HostsFile),
|
|
}
|
|
|
|
if hs.RedisEnable {
|
|
log.Info("Redis is enabled: %s", rs.Addr())
|
|
|
|
rc := &redis.Client{Addr: rs.Addr(), Db: rs.DB, Password: rs.Password}
|
|
|
|
providers = append(providers, NewRedisProvider(rc, hs.RedisKey))
|
|
}
|
|
|
|
h := &ProviderList{hs, providers, time.Second * time.Duration(hs.RefreshInterval)}
|
|
|
|
if h.refreshInterval > 0 {
|
|
h.refresh()
|
|
}
|
|
|
|
return h
|
|
}
|
|
|
|
func (h *ProviderList) refresh() {
|
|
ticker := time.NewTicker(h.refreshInterval)
|
|
|
|
go func() {
|
|
for {
|
|
// Force a refresh every refreshInterval
|
|
for _, provider := range h.providers {
|
|
provider.Refresh()
|
|
}
|
|
|
|
<-ticker.C
|
|
}
|
|
}()
|
|
}
|
|
|
|
/*
|
|
Match local /etc/hosts file first, remote redis records second
|
|
*/
|
|
func (h *ProviderList) Get(domain string, family int) ([]net.IP, bool) {
|
|
var sips []string
|
|
var ok bool
|
|
var ip net.IP
|
|
var ips []net.IP
|
|
|
|
for _, provider := range h.providers {
|
|
sips, ok = provider.Get(domain)
|
|
|
|
if ok {
|
|
break
|
|
}
|
|
}
|
|
|
|
if sips == nil {
|
|
return nil, false
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
return ips, ips != nil
|
|
}
|
|
|
|
func (h *ProviderList) TTL() uint32 {
|
|
return h.settings.TTL
|
|
} |