2013-07-23 11:10:38 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-02-07 05:07:58 +00:00
|
|
|
"net"
|
2013-07-23 11:10:38 +00:00
|
|
|
"strconv"
|
|
|
|
"time"
|
2015-02-10 09:00:59 +00:00
|
|
|
|
|
|
|
"github.com/miekg/dns"
|
2019-09-26 04:43:17 +00:00
|
|
|
)
|
2013-07-23 11:10:38 +00:00
|
|
|
|
|
|
|
type Server struct {
|
|
|
|
host string
|
|
|
|
port int
|
|
|
|
rTimeout time.Duration
|
|
|
|
wTimeout time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Addr() string {
|
2017-02-07 05:07:58 +00:00
|
|
|
return net.JoinHostPort(s.host, strconv.Itoa(s.port))
|
2013-07-23 11:10:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Run() {
|
2018-07-03 05:35:20 +00:00
|
|
|
handler := NewHandler()
|
2013-07-23 11:10:38 +00:00
|
|
|
|
|
|
|
tcpHandler := dns.NewServeMux()
|
2018-07-03 05:35:20 +00:00
|
|
|
tcpHandler.HandleFunc(".", handler.DoTCP)
|
2013-07-23 11:10:38 +00:00
|
|
|
|
|
|
|
udpHandler := dns.NewServeMux()
|
2018-07-03 05:35:20 +00:00
|
|
|
udpHandler.HandleFunc(".", handler.DoUDP)
|
2013-07-23 11:10:38 +00:00
|
|
|
|
2018-07-03 05:35:20 +00:00
|
|
|
tcpServer := &dns.Server{
|
2019-09-26 04:43:17 +00:00
|
|
|
Addr: s.Addr(),
|
|
|
|
Net: "tcp",
|
|
|
|
Handler: tcpHandler,
|
|
|
|
ReadTimeout: s.rTimeout,
|
2018-07-03 05:35:20 +00:00
|
|
|
WriteTimeout: s.wTimeout,
|
|
|
|
}
|
2013-07-23 11:10:38 +00:00
|
|
|
|
2018-07-03 05:35:20 +00:00
|
|
|
udpServer := &dns.Server{
|
2019-09-26 04:43:17 +00:00
|
|
|
Addr: s.Addr(),
|
|
|
|
Net: "udp",
|
|
|
|
Handler: udpHandler,
|
|
|
|
UDPSize: 65535,
|
|
|
|
ReadTimeout: s.rTimeout,
|
2018-07-03 05:35:20 +00:00
|
|
|
WriteTimeout: s.wTimeout,
|
|
|
|
}
|
2013-07-23 11:10:38 +00:00
|
|
|
|
|
|
|
go s.start(udpServer)
|
|
|
|
go s.start(tcpServer)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) start(ds *dns.Server) {
|
2015-10-15 03:00:09 +00:00
|
|
|
logger.Info("Start %s listener on %s", ds.Net, s.Addr())
|
2018-07-03 05:35:20 +00:00
|
|
|
|
2013-07-23 11:10:38 +00:00
|
|
|
err := ds.ListenAndServe()
|
|
|
|
if err != nil {
|
2015-10-13 11:33:51 +00:00
|
|
|
logger.Error("Start %s listener on %s failed:%s", ds.Net, s.Addr(), err.Error())
|
2013-07-23 11:10:38 +00:00
|
|
|
}
|
|
|
|
}
|