2023-04-26 15:57:55 +08:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
2023-10-25 19:20:44 +08:00
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2024-10-02 14:44:52 +08:00
|
|
|
"github.com/metacubex/mihomo/component/resolver"
|
|
|
|
|
2023-10-25 19:20:44 +08:00
|
|
|
D "github.com/miekg/dns"
|
2023-04-26 15:57:55 +08:00
|
|
|
)
|
|
|
|
|
2023-10-25 19:20:44 +08:00
|
|
|
const (
|
|
|
|
SystemDnsFlushTime = 5 * time.Minute
|
|
|
|
SystemDnsDeleteTimes = 12 // 12*5 = 60min
|
|
|
|
)
|
|
|
|
|
|
|
|
type systemDnsClient struct {
|
|
|
|
disableTimes uint32
|
|
|
|
dnsClient
|
|
|
|
}
|
|
|
|
|
|
|
|
type systemClient struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
dnsClients map[string]*systemDnsClient
|
|
|
|
lastFlush time.Time
|
2024-10-02 14:44:52 +08:00
|
|
|
defaultNS []dnsClient
|
2023-10-25 19:20:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *systemClient) ExchangeContext(ctx context.Context, m *D.Msg) (msg *D.Msg, err error) {
|
|
|
|
dnsClients, err := c.getDnsClients()
|
2023-04-26 15:57:55 +08:00
|
|
|
if err != nil {
|
2024-10-02 14:44:52 +08:00
|
|
|
if len(c.defaultNS) > 0 {
|
|
|
|
dnsClients = c.defaultNS
|
|
|
|
} else {
|
|
|
|
return
|
|
|
|
}
|
2023-04-26 15:57:55 +08:00
|
|
|
}
|
2023-10-25 19:20:44 +08:00
|
|
|
msg, _, err = batchExchange(ctx, dnsClients, m)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Address implements dnsClient
|
|
|
|
func (c *systemClient) Address() string {
|
|
|
|
dnsClients, _ := c.getDnsClients()
|
|
|
|
addrs := make([]string, 0, len(dnsClients))
|
|
|
|
for _, c := range dnsClients {
|
|
|
|
addrs = append(addrs, c.Address())
|
2023-04-26 15:57:55 +08:00
|
|
|
}
|
2023-10-25 19:20:44 +08:00
|
|
|
return fmt.Sprintf("system(%s)", strings.Join(addrs, ","))
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ dnsClient = (*systemClient)(nil)
|
|
|
|
|
|
|
|
func newSystemClient() *systemClient {
|
|
|
|
return &systemClient{
|
|
|
|
dnsClients: map[string]*systemDnsClient{},
|
2023-04-26 15:57:55 +08:00
|
|
|
}
|
|
|
|
}
|
2024-10-02 14:44:52 +08:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
r, _ := NewResolver(Config{})
|
|
|
|
c := newSystemClient()
|
|
|
|
c.defaultNS = transform([]NameServer{{Addr: "114.114.114.114:53"}, {Addr: "8.8.8.8:53"}}, nil)
|
|
|
|
r.main = []dnsClient{c}
|
|
|
|
resolver.SystemResolver = r
|
|
|
|
}
|