clash/dns/client.go

60 lines
1 KiB
Go
Raw Normal View History

2018-12-05 13:13:29 +00:00
package dns
import (
"context"
"strings"
2018-12-05 13:13:29 +00:00
2020-02-09 09:02:48 +00:00
"github.com/Dreamacro/clash/component/dialer"
2018-12-05 13:13:29 +00:00
D "github.com/miekg/dns"
)
2019-06-28 04:29:08 +00:00
type client struct {
*D.Client
r *Resolver
addr string
host string
2018-12-05 13:13:29 +00:00
}
2019-06-28 04:29:08 +00:00
func (c *client) Exchange(m *D.Msg) (msg *D.Msg, err error) {
return c.ExchangeContext(context.Background(), m)
2018-12-05 13:13:29 +00:00
}
2019-06-28 04:29:08 +00:00
func (c *client) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
network := "udp"
if strings.HasPrefix(c.Client.Net, "tcp") {
network = "tcp"
}
2020-02-17 12:11:46 +00:00
ip, err := c.r.ResolveIP(c.host)
if err != nil {
return nil, err
}
d := dialer.Dialer()
if dialer.DialHook != nil {
dialer.DialHook(d, network, ip)
}
c.Client.Dialer = d
2020-02-09 09:02:48 +00: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() {
msg, _, err := c.Client.Exchange(m, c.addr)
ch <- result{msg, err}
}()
select {
case <-ctx.Done():
return nil, ctx.Err()
case ret := <-ch:
return ret.msg, ret.err
}
2018-12-05 13:13:29 +00:00
}