godns/hosts/hosts_redis.go

94 lines
1.8 KiB
Go
Raw Normal View History

2020-01-25 17:43:02 +00:00
package hosts
import (
"github.com/go-redis/redis/v7"
"github.com/miekg/dns"
2019-09-26 04:43:17 +00:00
"github.com/ryanuber/go-glob"
2020-01-25 17:43:02 +00:00
"meow.tf/joker/godns/log"
"strings"
2019-09-26 04:43:17 +00:00
"sync"
"time"
)
type RedisHosts struct {
Provider
redis *redis.Client
key string
hosts map[string]string
mu sync.RWMutex
ttl time.Duration
}
func NewRedisProvider(rc *redis.Client, key string, ttl time.Duration) Provider {
rh := &RedisHosts{
redis: rc,
2019-09-26 04:43:17 +00:00
key: key,
hosts: make(map[string]string),
ttl: ttl,
}
2018-08-05 08:48:26 +00:00
// Force an initial refresh
rh.Refresh()
return rh
}
func (r *RedisHosts) Get(queryType uint16, domain string) ([]string, time.Duration, bool) {
2020-01-25 17:43:02 +00:00
log.Debug("Checking redis provider for %s", domain)
2018-08-05 04:16:15 +00:00
// Don't support queries other than A/AAAA for now
if queryType != dns.TypeA || queryType != dns.TypeAAAA {
return nil, zeroDuration, false
}
r.mu.RLock()
defer r.mu.RUnlock()
domain = strings.ToLower(domain)
2018-09-01 01:27:26 +00:00
if ip, ok := r.hosts[domain]; ok {
return strings.Split(ip, ","), r.ttl, true
}
2018-09-01 01:27:26 +00:00
if idx := strings.Index(domain, "."); idx != -1 {
2019-09-26 04:43:17 +00:00
wildcard := "*." + domain[strings.Index(domain, ".")+1:]
2018-09-01 01:27:26 +00:00
if ip, ok := r.hosts[wildcard]; ok {
return strings.Split(ip, ","), r.ttl, true
2018-09-01 01:27:26 +00:00
}
}
for host, ip := range r.hosts {
2018-09-01 01:27:26 +00:00
if glob.Glob(host, domain) {
return strings.Split(ip, ","), r.ttl, true
}
}
2018-09-01 01:27:26 +00:00
return nil, time.Duration(0), false
}
func (r *RedisHosts) Set(t, domain, ip string) (bool, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.redis.HSet(r.key, strings.ToLower(domain), []byte(ip)).Result()
}
func (r *RedisHosts) Refresh() {
r.mu.Lock()
defer r.mu.Unlock()
r.clear()
var err error
r.hosts, err = r.redis.HGetAll(r.key).Result()
if err != nil {
2020-01-25 17:43:02 +00:00
log.Warn("Update hosts records from redis failed %s", err)
} else {
2020-01-25 17:43:02 +00:00
log.Debug("Update hosts records from redis")
}
}
func (r *RedisHosts) clear() {
r.hosts = make(map[string]string)
}