|
|
@ -2,11 +2,14 @@ package fakedns |
|
|
|
|
|
|
|
import ( |
|
|
|
"errors" |
|
|
|
"fmt" |
|
|
|
"net" |
|
|
|
"strings" |
|
|
|
|
|
|
|
D "github.com/miekg/dns" |
|
|
|
trie "github.com/xjasonlyu/tun2socks/common/domain-trie" |
|
|
|
"github.com/xjasonlyu/tun2socks/common/fakeip" |
|
|
|
"github.com/xjasonlyu/tun2socks/log" |
|
|
|
|
|
|
|
D "github.com/miekg/dns" |
|
|
|
) |
|
|
|
|
|
|
|
const ( |
|
|
@ -33,7 +36,6 @@ func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) { |
|
|
|
} |
|
|
|
|
|
|
|
func (s *Server) Start() error { |
|
|
|
log.Debugf("Start fake DNS server") |
|
|
|
_, port, err := net.SplitHostPort(ServeAddr) |
|
|
|
if port == "0" || port == "" || err != nil { |
|
|
|
return errors.New("address format error") |
|
|
@ -44,18 +46,20 @@ func (s *Server) Start() error { |
|
|
|
return err |
|
|
|
} |
|
|
|
|
|
|
|
p, err := net.ListenUDP("udp", udpAddr) |
|
|
|
pc, err := net.ListenUDP("udp", udpAddr) |
|
|
|
if err != nil { |
|
|
|
return err |
|
|
|
} |
|
|
|
|
|
|
|
s.Server = &D.Server{Addr: ServeAddr, PacketConn: p, Handler: s} |
|
|
|
go s.ActivateAndServe() |
|
|
|
s.Server = &D.Server{Addr: ServeAddr, PacketConn: pc, Handler: s} |
|
|
|
go func() { |
|
|
|
s.ActivateAndServe() |
|
|
|
}() |
|
|
|
|
|
|
|
return nil |
|
|
|
} |
|
|
|
|
|
|
|
func (s *Server) Stop() error { |
|
|
|
log.Debugf("Stop fake DNS server") |
|
|
|
return s.Shutdown() |
|
|
|
} |
|
|
|
|
|
|
@ -63,7 +67,7 @@ func (s *Server) IPToHost(ip net.IP) (string, bool) { |
|
|
|
return s.p.LookBack(ip) |
|
|
|
} |
|
|
|
|
|
|
|
func NewServer(fakeIPRange, hostsLine string, size int) (*Server, error) { |
|
|
|
func NewServer(fakeIPRange, hosts string, size int) (*Server, error) { |
|
|
|
_, ipnet, err := net.ParseCIDR(fakeIPRange) |
|
|
|
if err != nil { |
|
|
|
return nil, err |
|
|
@ -73,8 +77,29 @@ func NewServer(fakeIPRange, hostsLine string, size int) (*Server, error) { |
|
|
|
return nil, err |
|
|
|
} |
|
|
|
|
|
|
|
hosts := lineToHosts(hostsLine) |
|
|
|
handler := newHandler(hosts, pool) |
|
|
|
hostsTree := func(str string) *trie.Trie { |
|
|
|
// trim `'` `"` ` ` char
|
|
|
|
str = strings.Trim(str, "' \"") |
|
|
|
if str == "" { |
|
|
|
return nil |
|
|
|
} |
|
|
|
tree := trie.New() |
|
|
|
s := strings.Split(str, ",") |
|
|
|
for _, host := range s { |
|
|
|
m := strings.Split(host, "=") |
|
|
|
if len(m) != 2 { |
|
|
|
continue |
|
|
|
} |
|
|
|
domain := strings.TrimSpace(m[0]) |
|
|
|
target := strings.TrimSpace(m[1]) |
|
|
|
if err := tree.Insert(domain, net.ParseIP(target)); err != nil { |
|
|
|
panic(fmt.Sprintf("add hosts error: %v", err)) |
|
|
|
} |
|
|
|
} |
|
|
|
return tree |
|
|
|
}(hosts) |
|
|
|
|
|
|
|
handler := newHandler(hostsTree, pool) |
|
|
|
|
|
|
|
return &Server{ |
|
|
|
p: pool, |
|
|
|