SpoofDPI/dns/dns.go

93 lines
2.0 KiB
Go
Raw Normal View History

2024-07-21 07:57:47 +00:00
package dns
import (
"context"
"fmt"
"net"
"strconv"
"time"
2024-07-21 07:57:47 +00:00
2024-08-18 06:55:47 +00:00
"github.com/miekg/dns"
log "github.com/sirupsen/logrus"
2024-08-18 07:11:04 +00:00
"github.com/xvzc/SpoofDPI/dns/resolver"
2024-08-18 06:55:47 +00:00
"github.com/xvzc/SpoofDPI/util"
)
2024-07-21 07:57:47 +00:00
type Resolver interface {
Resolve(ctx context.Context, host string, qTypes []uint16) ([]net.IPAddr, error)
String() string
}
2024-08-18 06:55:47 +00:00
type Dns struct {
host string
port string
systemClient Resolver
generalClient Resolver
dohClient Resolver
2024-07-21 07:57:47 +00:00
}
2024-08-18 06:55:47 +00:00
func NewResolver(config *util.Config) *Dns {
addr := *config.DnsAddr
port := strconv.Itoa(*config.DnsPort)
2024-07-21 07:57:47 +00:00
2024-08-18 06:55:47 +00:00
return &Dns{
host: *config.DnsAddr,
port: port,
systemClient: client.NewSystemResolver(),
generalClient: client.NewGeneralResolver(net.JoinHostPort(addr, port)),
dohClient: client.NewDOHResolver(addr),
}
}
2024-08-18 06:55:47 +00:00
func (d *Dns) ResolveHost(host string, enableDoh bool, useSystemDns bool) (string, error) {
if ip, err := parseIpAddr(host); err == nil {
return ip.String(), nil
}
2024-08-18 06:55:47 +00:00
clt := d.clientFactory(enableDoh, useSystemDns)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
2024-08-18 06:55:47 +00:00
log.Debugf("[DNS] resolving %s using %s", host, clt)
t := time.Now()
2024-07-21 07:57:47 +00:00
2024-08-18 06:55:47 +00:00
addrs, err := clt.Resolve(ctx, host, []uint16{dns.TypeAAAA, dns.TypeA})
// addrs, err := clt.Resolve(ctx, host, []uint16{dns.TypeAAAA})
2024-07-21 07:57:47 +00:00
if err != nil {
2024-08-18 06:55:47 +00:00
return "", fmt.Errorf("%s: %w", clt, err)
}
2024-08-18 06:55:47 +00:00
if len(addrs) > 0 {
d := time.Since(t).Milliseconds()
log.Debugf("[DNS] resolved %s from %s in %d ms", addrs[0].String(), host, d)
return addrs[0].String(), nil
}
2024-08-12 22:37:20 +00:00
2024-08-18 06:55:47 +00:00
return "", fmt.Errorf("could not resolve %s using %s", host, clt)
}
func (d *Dns) clientFactory(enableDoh bool, useSystemDns bool) Resolver {
2024-08-18 06:55:47 +00:00
if useSystemDns {
return d.systemClient
2024-07-21 07:57:47 +00:00
}
2024-08-18 06:55:47 +00:00
if enableDoh {
return d.dohClient
}
2024-08-18 06:55:47 +00:00
return d.generalClient
}
2024-08-18 06:55:47 +00:00
func parseIpAddr(addr string) (*net.IPAddr, error) {
ip := net.ParseIP(addr)
if ip == nil {
return nil, fmt.Errorf("%s is not an ip address", addr)
2024-08-12 22:37:20 +00:00
}
2024-08-18 06:55:47 +00:00
ipAddr := &net.IPAddr{
IP: ip,
}
2024-08-12 22:37:20 +00:00
2024-08-18 06:55:47 +00:00
return ipAddr, nil
2024-07-21 07:57:47 +00:00
}