server.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package dns
  2. //go:generate go run $GOPATH/src/v2ray.com/core/common/errors/errorgen/main.go -pkg dns -path App,DNS
  3. import (
  4. "context"
  5. "sync"
  6. "time"
  7. dnsmsg "github.com/miekg/dns"
  8. "v2ray.com/core"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/net"
  11. "v2ray.com/core/common/signal"
  12. )
  13. const (
  14. QueryTimeout = time.Second * 8
  15. )
  16. type DomainRecord struct {
  17. IP []net.IP
  18. Expire time.Time
  19. LastAccess time.Time
  20. }
  21. func (r *DomainRecord) Expired() bool {
  22. return r.Expire.Before(time.Now())
  23. }
  24. func (r *DomainRecord) Inactive() bool {
  25. now := time.Now()
  26. return r.Expire.Before(now) || r.LastAccess.Add(time.Minute*5).Before(now)
  27. }
  28. type Server struct {
  29. sync.Mutex
  30. hosts map[string]net.IP
  31. records map[string]*DomainRecord
  32. servers []NameServer
  33. task *signal.PeriodicTask
  34. }
  35. func New(ctx context.Context, config *Config) (*Server, error) {
  36. server := &Server{
  37. records: make(map[string]*DomainRecord),
  38. servers: make([]NameServer, len(config.NameServers)),
  39. hosts: config.GetInternalHosts(),
  40. }
  41. server.task = &signal.PeriodicTask{
  42. Interval: time.Minute * 10,
  43. Execute: func() error {
  44. server.cleanup()
  45. return nil
  46. },
  47. }
  48. v := core.FromContext(ctx)
  49. if v == nil {
  50. return nil, newError("V is not in context.")
  51. }
  52. if err := v.RegisterFeature((*core.DNSClient)(nil), server); err != nil {
  53. return nil, newError("unable to register DNSClient.").Base(err)
  54. }
  55. for idx, destPB := range config.NameServers {
  56. address := destPB.Address.AsAddress()
  57. if address.Family().IsDomain() && address.Domain() == "localhost" {
  58. server.servers[idx] = &LocalNameServer{}
  59. } else {
  60. dest := destPB.AsDestination()
  61. if dest.Network == net.Network_Unknown {
  62. dest.Network = net.Network_UDP
  63. }
  64. if dest.Network == net.Network_UDP {
  65. server.servers[idx] = NewUDPNameServer(dest, v.Dispatcher())
  66. }
  67. }
  68. }
  69. if len(config.NameServers) == 0 {
  70. server.servers = append(server.servers, &LocalNameServer{})
  71. }
  72. return server, nil
  73. }
  74. // Start implements common.Runnable.
  75. func (s *Server) Start() error {
  76. return s.task.Start()
  77. }
  78. // Close implements common.Runnable.
  79. func (s *Server) Close() error {
  80. return s.task.Close()
  81. }
  82. func (s *Server) GetCached(domain string) []net.IP {
  83. s.Lock()
  84. defer s.Unlock()
  85. if record, found := s.records[domain]; found && !record.Expired() {
  86. record.LastAccess = time.Now()
  87. return record.IP
  88. }
  89. return nil
  90. }
  91. func (s *Server) cleanup() {
  92. s.Lock()
  93. defer s.Unlock()
  94. for d, r := range s.records {
  95. if r.Expired() {
  96. delete(s.records, d)
  97. }
  98. }
  99. }
  100. func (s *Server) LookupIP(domain string) ([]net.IP, error) {
  101. if ip, found := s.hosts[domain]; found {
  102. return []net.IP{ip}, nil
  103. }
  104. domain = dnsmsg.Fqdn(domain)
  105. ips := s.GetCached(domain)
  106. if ips != nil {
  107. return ips, nil
  108. }
  109. for _, server := range s.servers {
  110. response := server.QueryA(domain)
  111. select {
  112. case a, open := <-response:
  113. if !open || a == nil {
  114. continue
  115. }
  116. s.Lock()
  117. s.records[domain] = &DomainRecord{
  118. IP: a.IPs,
  119. Expire: a.Expire,
  120. LastAccess: time.Now(),
  121. }
  122. s.Unlock()
  123. newError("returning ", len(a.IPs), " IPs for domain ", domain).AtDebug().WriteToLog()
  124. return a.IPs, nil
  125. case <-time.After(QueryTimeout):
  126. }
  127. }
  128. return nil, newError("returning nil for domain ", domain)
  129. }
  130. func init() {
  131. common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
  132. return New(ctx, config.(*Config))
  133. }))
  134. }