server.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. space app.Space
  20. records map[string]*DomainRecord
  21. servers []NameServer
  22. }
  23. func NewCacheServer(space app.Space, config *Config) *CacheServer {
  24. server := &CacheServer{
  25. records: make(map[string]*DomainRecord),
  26. servers: make([]NameServer, len(config.NameServers)),
  27. }
  28. space.InitializeApplication(func() error {
  29. if !space.HasApp(dispatcher.APP_ID) {
  30. log.Error("DNS: Dispatcher is not found in the space.")
  31. return app.ErrorMissingApplication
  32. }
  33. dispatcher := space.GetApp(dispatcher.APP_ID).(dispatcher.PacketDispatcher)
  34. for idx, ns := range config.NameServers {
  35. if ns.Address().IsDomain() && ns.Address().Domain() == "localhost" {
  36. server.servers[idx] = &LocalNameServer{}
  37. } else {
  38. server.servers[idx] = NewUDPNameServer(ns, dispatcher)
  39. }
  40. }
  41. return nil
  42. })
  43. return server
  44. }
  45. func (this *CacheServer) Release() {
  46. }
  47. //@Private
  48. func (this *CacheServer) GetCached(domain string) []net.IP {
  49. this.RLock()
  50. defer this.RUnlock()
  51. if record, found := this.records[domain]; found && record.A.Expire.After(time.Now()) {
  52. return record.A.IPs
  53. }
  54. return nil
  55. }
  56. func (this *CacheServer) Get(domain string) []net.IP {
  57. domain = dns.Fqdn(domain)
  58. ips := this.GetCached(domain)
  59. if ips != nil {
  60. return ips
  61. }
  62. for _, server := range this.servers {
  63. response := server.QueryA(domain)
  64. select {
  65. case a, open := <-response:
  66. if !open || a == nil {
  67. continue
  68. }
  69. this.Lock()
  70. this.records[domain] = &DomainRecord{
  71. A: a,
  72. }
  73. this.Unlock()
  74. log.Debug("DNS: Returning ", len(a.IPs), " IPs for domain ", domain)
  75. return a.IPs
  76. case <-time.After(QueryTimeout):
  77. }
  78. }
  79. log.Debug("DNS: Returning nil for domain ", domain)
  80. return nil
  81. }