Skip to content

Commit

Permalink
Merge branch 'feature/dhcp'
Browse files Browse the repository at this point in the history
  • Loading branch information
wweir committed Mar 20, 2019
2 parents 45ca063 + eb8080d commit 559c5fd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 17 deletions.
4 changes: 2 additions & 2 deletions dns/dhcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ func GetDefaultDNSServer() (string, error) {

var conn net.PacketConn
if runtime.GOOS == "windows" {
if conn, err = reuseport.ListenPacket("udp", iface.IP.String()+":68"); err != nil {
if conn, err = reuseport.ListenPacket("udp4", iface.IP.String()+":68"); err != nil {
return "", errors.Wrap(err, "listen dhcp")
}
} else {
if conn, err = reuseport.ListenPacket("udp", "0.0.0.0:68"); err != nil {
if conn, err = reuseport.ListenPacket("udp4", "0.0.0.0:68"); err != nil {
return "", errors.Wrap(err, "listen dhcp")
}
}
Expand Down
45 changes: 30 additions & 15 deletions dns/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,7 @@ func StartDNS(dnsServer, listenIP string, suggestCh chan<- string, suggestLevel
if dnsServer != "" {
dnsServer = net.JoinHostPort(dnsServer, "53")
} else {
go func() {
for {
<-dhcpCh
host, err := GetDefaultDNSServer()
if err != nil {
glog.Errorln(err)
continue
}
// atomic action
dnsServer = net.JoinHostPort(host, "53")
glog.Infoln("set dns server to", host)
}
}()
go dynamicSetUpstreamDNS(listenIP, &dnsServer, dhcpCh)
dhcpCh <- struct{}{}
}

Expand Down Expand Up @@ -64,6 +52,33 @@ func StartDNS(dnsServer, listenIP string, suggestCh chan<- string, suggestLevel
glog.Fatalln(server.ListenAndServe())
}

func dynamicSetUpstreamDNS(listenIP string, dnsServer *string, dhcpCh <-chan struct{}) {
addr, _ := dns.ReverseAddr(listenIP)
msg := &dns.Msg{
MsgHdr: dns.MsgHdr{
Id: dns.Id(),
RecursionDesired: false,
},
Question: []dns.Question{{addr, dns.TypeA, dns.ClassINET}},
}

for {
<-dhcpCh
if _, err := dns.Exchange(msg, *dnsServer); err == nil {
continue
}

host, err := GetDefaultDNSServer()
if err != nil {
glog.Errorln(err)
continue
}

// atomic action
*dnsServer = net.JoinHostPort(host, "53")
glog.Infoln("set dns server to", host)
}
}
func matchAndServe(w dns.ResponseWriter, r *dns.Msg, domain, listenIP, dnsServer string,
dhcpCh chan struct{}, ipNet net.IP, suggest *intelliSuggest) {

Expand All @@ -85,10 +100,10 @@ func matchAndServe(w dns.ResponseWriter, r *dns.Msg, domain, listenIP, dnsServer
default:
}
}
glog.V(1).Infof("get dns of %s fail: %s", domain, err)
glog.V(1).Infof("get dns of %s from %s fail: %s", domain, dnsServer, err)
return
} else if msg == nil { // expose any response except nil
glog.V(1).Infof("get dns of %s return empty", domain)
glog.V(1).Infof("get dns of %s from %s return empty", domain, dnsServer)
return
}

Expand Down

0 comments on commit 559c5fd

Please sign in to comment.