read local hosts file

This commit is contained in:
kenshin 2013-07-26 12:06:16 +08:00
parent 2b4e076674
commit d22885557f
4 changed files with 76 additions and 2 deletions

View File

@ -32,3 +32,8 @@ file = ""
backend = "memory"
expire = 600 # 10 minutes
maxcount = 100000
[hosts]
host-file = "/etc/hosts"
redis-key = "godns:hosts"

View File

@ -71,7 +71,7 @@ func (h *GODNSHandler) do(net string, w dns.ResponseWriter, req *dns.Msg) {
key := KeyGen(Q)
// Only query cache when qtype == 'A' , qclass == 'IN'
if q.Qtype == dns.TypeA && q.Qclass == dns.ClassINET {
if h.isIPQuery(q) {
mesg, err := h.cache.Get(key)
if err != nil {
Debug("%s didn't hit cache: %s", Q.String(), err)
@ -94,7 +94,7 @@ func (h *GODNSHandler) do(net string, w dns.ResponseWriter, req *dns.Msg) {
w.WriteMsg(mesg)
if q.Qtype == dns.TypeA && q.Qclass == dns.ClassINET {
if h.isIPQuery(q) {
err = h.cache.Set(key, mesg)
if err != nil {
@ -113,3 +113,7 @@ func (h *GODNSHandler) DoTCP(w dns.ResponseWriter, req *dns.Msg) {
func (h *GODNSHandler) DoUDP(w dns.ResponseWriter, req *dns.Msg) {
h.do("udp", w, req)
}
func (h *GODNSHandler) isIPQuery(q dns.Question) bool {
return q.Qtype == dns.TypeA && q.Qclass == dns.ClassINET
}

59
hosts.go Normal file
View File

@ -0,0 +1,59 @@
package main
import (
"github.com/hoisie/redis"
// "github.com/miekg/dns"
"fmt"
"io/ioutil"
)
type HostsQueryFaild struct {
domain string
}
func (e HostsQueryFaild) Error() string {
return e.domain + " hosts match failed"
}
func readLocalHostsFile(file string) map[string]string {
var hosts = make(map[string]string)
f, _ := os.Open(file)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") || line == "" {
continue
}
sli := strings.Split(line, " ")
if len(sli) == 1 {
sli = strings.Split(line, "\t")
}
if len(sli) < 2 {
continue
}
domain := sli[len(sli)-1]
ip := sli[0]
if !isDomain(domain) || !isIP(ip) {
continue
}
hosts[domain] = ip
}
return hosts
}
func isDomain(domain string) bool {
match, _ := regexp.MatchString("^[a-z]", domain)
return match
}
func isIP(ip string) bool {
match, _ := regexp.MatchString("^[1-9]", ip)
return match
}

View File

@ -19,6 +19,7 @@ type Settings struct {
Redis RedisSettings `toml:"redis"`
Log LogSettings `toml:"log"`
Cache CacheSettings `toml:"cache"`
Hosts HostsSettings `toml:"hosts"`
}
type ResolvSettings struct {
@ -48,6 +49,11 @@ type CacheSettings struct {
Maxcount int
}
type HostsSettings struct {
HostsFile string `toml:"host-file"`
RedisKey string `toml:"redis-key"`
}
func init() {
var configFile string