Merge pull request #129 from ohaiibuzzle/feat/internal-doh

feat: move doh to internal
This commit is contained in:
xvzc 2024-08-13 06:50:12 +09:00 committed by GitHub
commit dbe7f32a1f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 137 additions and 29 deletions

View File

@ -8,8 +8,6 @@ import (
"strconv"
"time"
"github.com/likexian/doh"
dohDns "github.com/likexian/doh/dns"
"github.com/miekg/dns"
log "github.com/sirupsen/logrus"
"github.com/xvzc/SpoofDPI/util"
@ -37,17 +35,17 @@ func (d *DnsResolver) Lookup(domain string, useSystemDns bool) (string, error) {
}
if useSystemDns {
log.Debug("[DNS] ", domain, " resolving with system dns")
log.Debug("[DNS] ", domain, " resolving with system dns")
return systemLookup(domain)
}
if d.enableDoh {
log.Debug("[DNS] ", domain, " resolving with dns over https")
log.Debug("[DNS] ", domain, " resolving with dns over https")
return dohLookup(domain)
}
log.Debug("[DNS] ", domain, " resolving with custom dns")
return customLookup(d.host, d.port, domain)
log.Debug("[DNS] ", domain, " resolving with custom dns")
return customLookup(d.host, d.port, domain)
}
func customLookup(host string, port string, domain string) (string, error) {
@ -91,26 +89,18 @@ func systemLookup(domain string) (string, error) {
func dohLookup(domain string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
c := doh.Use(doh.CloudflareProvider, doh.GoogleProvider)
log.Debug("[DoH] ", domain, " resolving with dns over https")
rsp, err := c.Query(ctx, dohDns.Domain(domain), dohDns.TypeA)
if err != nil {
return "", errors.New("could not resolve the domain(doh)")
}
// doh dns answer
answer := rsp.Answer
// print all answer
for _, a := range answer {
if a.Type != 1 { // Type == 1 -> A Record
continue
dnsUpstream := util.GetConfig().DnsAddr
client := GetDoHClient(*dnsUpstream)
resp, err := client.Resolve(ctx, domain, []uint16{dns.TypeA, dns.TypeAAAA})
if err == nil {
if len(resp) == 0 { // yes this happens
return "", errors.New("no record found(doh)")
}
return a.Data, nil
return resp[0], nil
}
// close the client
c.Close()
return "", errors.New("no record found(doh)")
return "", errors.New("could not resolve the domain(doh)")
}

124
dns/doh.go Normal file
View File

@ -0,0 +1,124 @@
package dns
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/miekg/dns"
log "github.com/sirupsen/logrus"
)
type DoHClient struct {
upstream string
c *http.Client
}
var client *DoHClient
var clientOnce sync.Once
func GetDoHClient(upstream string) *DoHClient {
clientOnce.Do(func() {
if client == nil {
if !strings.HasPrefix(upstream, "https://") {
upstream = "https://" + upstream
}
if !strings.HasSuffix(upstream, "/dns-query") {
upstream = upstream + "/dns-query"
}
c := &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
MaxIdleConnsPerHost: 100,
MaxIdleConns: 100,
},
}
client = &DoHClient{
upstream: upstream,
c: c,
}
}
})
return client
}
func (d *DoHClient) doGetRequest(ctx context.Context, msg *dns.Msg) (*dns.Msg, error) {
pack, err := msg.Pack()
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s?dns=%s", d.upstream, base64.RawStdEncoding.EncodeToString(pack))
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Accept", "application/dns-message")
resp, err := d.c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Debug("[DoH] Error while resolving ", url, " : ", resp.Status)
}
buf := bytes.Buffer{}
buf.ReadFrom(resp.Body)
ret_msg := new(dns.Msg)
err = ret_msg.Unpack(buf.Bytes())
if err != nil {
return nil, err
}
return ret_msg, nil
}
func (d *DoHClient) Resolve(ctx context.Context, domain string, dnsTypes []uint16) ([]string, error) {
var ret []string
for _, dnsType := range dnsTypes {
msg := new(dns.Msg)
msg.SetQuestion(dns.Fqdn(domain), dnsType)
resp, err := d.doGetRequest(ctx, msg)
if err != nil {
return nil, err
}
if resp.Rcode != dns.RcodeSuccess {
continue
}
for _, answer := range resp.Answer {
if t, ok := answer.(*dns.A); ok {
ret = append(ret, t.A.String())
}
if t, ok := answer.(*dns.AAAA); ok {
ret = append(ret, t.AAAA.String())
}
}
}
return ret, nil
}

2
go.mod
View File

@ -5,7 +5,6 @@ go 1.21
toolchain go1.21.5
require (
github.com/likexian/doh v0.7.1
github.com/miekg/dns v1.1.61
github.com/pterm/pterm v0.12.79
github.com/sirupsen/logrus v1.9.3
@ -17,7 +16,6 @@ require (
atomicgo.dev/schedule v0.1.0 // indirect
github.com/containerd/console v1.0.3 // indirect
github.com/gookit/color v1.5.4 // indirect
github.com/likexian/gokit v0.25.15 // indirect
github.com/lithammer/fuzzysearch v1.1.8 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/rivo/uniseg v0.4.4 // indirect

4
go.sum
View File

@ -33,10 +33,6 @@ github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8t
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/likexian/doh v0.7.1 h1:0p75orMxXrfGNAOnOEtl2xZ5T9Ctqi++i/WhN6P6hs8=
github.com/likexian/doh v0.7.1/go.mod h1:aIEOK197o6nC82iRo5+5L5ws+X7xRCmuer3M4In91WA=
github.com/likexian/gokit v0.25.15 h1:QjospM1eXhdMMHwZRpMKKAHY/Wig9wgcREmLtf9NslY=
github.com/likexian/gokit v0.25.15/go.mod h1:S2QisdsxLEHWeD/XI0QMVeggp+jbxYqUxMvSBil7MRg=
github.com/lithammer/fuzzysearch v1.1.8 h1:/HIuJnjHuXS8bKaiTMeeDlW2/AyIWk2brx1V8LFgLN4=
github.com/lithammer/fuzzysearch v1.1.8/go.mod h1:IdqeyBClc3FFqSzYq/MXESsS4S0FsZ5ajtkr5xPLts4=
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=