2018-12-05 21:13:29 +08:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2020-02-17 22:13:15 +08:00
|
|
|
"fmt"
|
|
|
|
"net"
|
2020-02-15 21:42:46 +08:00
|
|
|
"strings"
|
2018-12-05 21:13:29 +08:00
|
|
|
|
2020-02-09 17:02:48 +08:00
|
|
|
"github.com/Dreamacro/clash/component/dialer"
|
|
|
|
|
2018-12-05 21:13:29 +08:00
|
|
|
D "github.com/miekg/dns"
|
|
|
|
)
|
|
|
|
|
2019-06-28 12:29:08 +08:00
|
|
|
type client struct {
|
|
|
|
*D.Client
|
2020-02-15 21:42:46 +08:00
|
|
|
r *Resolver
|
2020-02-17 22:13:15 +08:00
|
|
|
port string
|
2020-02-15 21:42:46 +08:00
|
|
|
host string
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|
|
|
|
|
2019-06-28 12:29:08 +08:00
|
|
|
func (c *client) Exchange(m *D.Msg) (msg *D.Msg, err error) {
|
|
|
|
return c.ExchangeContext(context.Background(), m)
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|
|
|
|
|
2019-06-28 12:29:08 +08:00
|
|
|
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
2020-02-17 22:13:15 +08:00
|
|
|
var ip net.IP
|
|
|
|
if c.r == nil {
|
|
|
|
// a default ip dns
|
|
|
|
ip = net.ParseIP(c.host)
|
|
|
|
} else {
|
|
|
|
var err error
|
|
|
|
if ip, err = c.r.ResolveIP(c.host); err != nil {
|
|
|
|
return nil, fmt.Errorf("use default dns resolve failed: %w", err)
|
|
|
|
}
|
2020-02-15 21:42:46 +08:00
|
|
|
}
|
|
|
|
|
2020-04-24 23:48:55 +08:00
|
|
|
d, err := dialer.Dialer()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-02-15 21:42:46 +08:00
|
|
|
if dialer.DialHook != nil {
|
2020-02-17 22:13:15 +08:00
|
|
|
network := "udp"
|
|
|
|
if strings.HasPrefix(c.Client.Net, "tcp") {
|
|
|
|
network = "tcp"
|
|
|
|
}
|
2020-04-24 23:48:55 +08:00
|
|
|
if err := dialer.DialHook(d, network, ip); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-02-15 21:42:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
c.Client.Dialer = d
|
2020-02-09 17:02:48 +08:00
|
|
|
|
2020-02-14 16:36:20 +08:00
|
|
|
// miekg/dns ExchangeContext doesn't respond to context cancel.
|
|
|
|
// this is a workaround
|
|
|
|
type result struct {
|
|
|
|
msg *D.Msg
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
ch := make(chan result, 1)
|
|
|
|
go func() {
|
2020-02-17 22:13:15 +08:00
|
|
|
msg, _, err := c.Client.Exchange(m, net.JoinHostPort(ip.String(), c.port))
|
2020-02-14 16:36:20 +08:00
|
|
|
ch <- result{msg, err}
|
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, ctx.Err()
|
|
|
|
case ret := <-ch:
|
|
|
|
return ret.msg, ret.err
|
|
|
|
}
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|