1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-27 22:36:12 -04:00
v2fly/app/dns/internal/dns.go

74 lines
1.3 KiB
Go
Raw Normal View History

2016-01-31 11:01:28 -05:00
package internal
import (
"net"
2016-05-16 02:09:28 -04:00
"sync"
2016-01-31 11:01:28 -05:00
"time"
"github.com/v2ray/v2ray-core/app"
2016-05-16 02:09:28 -04:00
"github.com/v2ray/v2ray-core/app/dispatcher"
"github.com/miekg/dns"
2016-01-31 11:01:28 -05:00
)
2016-05-16 02:09:28 -04:00
const (
QueryTimeout = time.Second * 2
)
2016-01-31 11:01:28 -05:00
2016-05-16 02:09:28 -04:00
type DomainRecord struct {
A *ARecord
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
type Server struct {
sync.RWMutex
records map[string]*DomainRecord
servers []NameServer
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
func NewServer(space app.Space, config *Config) *Server {
server := &Server{
records: make(map[string]*DomainRecord),
servers: make([]NameServer, len(config.NameServers)),
}
dispatcher := space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
for idx, ns := range config.NameServers {
server.servers[idx] = NewUDPNameServer(ns, dispatcher)
}
return server
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
//@Private
func (this *Server) GetCached(domain string) []net.IP {
this.RLock()
defer this.RUnlock()
2016-01-31 11:01:28 -05:00
2016-05-16 02:09:28 -04:00
if record, found := this.records[domain]; found && record.A.Expire.After(time.Now()) {
return record.A.IPs
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
return nil
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
func (this *Server) Get(context app.Context, domain string) []net.IP {
domain = dns.Fqdn(domain)
ips := this.GetCached(domain)
if ips != nil {
return ips
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
for _, server := range this.servers {
response := server.QueryA(domain)
select {
case a := <-response:
this.Lock()
this.records[domain] = &DomainRecord{
A: a,
}
this.Unlock()
return a.IPs
case <-time.Tick(QueryTimeout):
}
2016-01-31 11:01:28 -05:00
}
2016-05-16 02:09:28 -04:00
2016-01-31 11:01:28 -05:00
return nil
}