server.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package dns
  2. import (
  3. "net"
  4. "sync"
  5. "time"
  6. "github.com/v2ray/v2ray-core/app"
  7. "github.com/v2ray/v2ray-core/app/dispatcher"
  8. "github.com/v2ray/v2ray-core/common/log"
  9. "github.com/miekg/dns"
  10. )
  11. const (
  12. QueryTimeout = time.Second * 8
  13. )
  14. type DomainRecord struct {
  15. A *ARecord
  16. }
  17. type CacheServer struct {
  18. sync.RWMutex
  19. records map[string]*DomainRecord
  20. servers []NameServer
  21. }
  22. func NewCacheServer(space app.Space, config *Config) *CacheServer {
  23. server := &CacheServer{
  24. records: make(map[string]*DomainRecord),
  25. servers: make([]NameServer, len(config.NameServers)),
  26. }
  27. dispatcher := space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
  28. for idx, ns := range config.NameServers {
  29. if ns.Address().IsDomain() && ns.Address().Domain() == "localhost" {
  30. server.servers[idx] = &LocalNameServer{}
  31. } else {
  32. server.servers[idx] = NewUDPNameServer(ns, dispatcher)
  33. }
  34. }
  35. return server
  36. }
  37. //@Private
  38. func (this *CacheServer) GetCached(domain string) []net.IP {
  39. this.RLock()
  40. defer this.RUnlock()
  41. if record, found := this.records[domain]; found && record.A.Expire.After(time.Now()) {
  42. return record.A.IPs
  43. }
  44. return nil
  45. }
  46. func (this *CacheServer) Get(domain string) []net.IP {
  47. domain = dns.Fqdn(domain)
  48. ips := this.GetCached(domain)
  49. if ips != nil {
  50. return ips
  51. }
  52. for _, server := range this.servers {
  53. response := server.QueryA(domain)
  54. select {
  55. case a, open := <-response:
  56. if !open || a == nil {
  57. continue
  58. }
  59. this.Lock()
  60. this.records[domain] = &DomainRecord{
  61. A: a,
  62. }
  63. this.Unlock()
  64. log.Debug("DNS: Returning ", len(a.IPs), " IPs for domain ", domain)
  65. return a.IPs
  66. case <-time.After(QueryTimeout):
  67. }
  68. }
  69. log.Debug("DNS: Returning nil for domain ", domain)
  70. return nil
  71. }