nameserver.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package dns
  2. import (
  3. "math/rand"
  4. "net"
  5. "sync"
  6. "time"
  7. "github.com/v2ray/v2ray-core/app/dispatcher"
  8. "github.com/v2ray/v2ray-core/common/alloc"
  9. "github.com/v2ray/v2ray-core/common/log"
  10. v2net "github.com/v2ray/v2ray-core/common/net"
  11. "github.com/v2ray/v2ray-core/transport/hub"
  12. "github.com/miekg/dns"
  13. )
  14. const (
  15. DefaultTTL = uint32(3600)
  16. CleanupInterval = time.Second * 120
  17. CleanupThreshold = 512
  18. )
  19. type ARecord struct {
  20. IPs []net.IP
  21. Expire time.Time
  22. }
  23. type NameServer interface {
  24. QueryA(domain string) <-chan *ARecord
  25. }
  26. type PendingRequest struct {
  27. expire time.Time
  28. response chan<- *ARecord
  29. }
  30. type UDPNameServer struct {
  31. sync.Mutex
  32. address v2net.Destination
  33. requests map[uint16]*PendingRequest
  34. udpServer *hub.UDPServer
  35. nextCleanup time.Time
  36. }
  37. func NewUDPNameServer(address v2net.Destination, dispatcher dispatcher.PacketDispatcher) *UDPNameServer {
  38. s := &UDPNameServer{
  39. address: address,
  40. requests: make(map[uint16]*PendingRequest),
  41. udpServer: hub.NewUDPServer(dispatcher),
  42. }
  43. return s
  44. }
  45. // @Private
  46. func (this *UDPNameServer) Cleanup() {
  47. expiredRequests := make([]uint16, 0, 16)
  48. now := time.Now()
  49. this.Lock()
  50. for id, r := range this.requests {
  51. if r.expire.Before(now) {
  52. expiredRequests = append(expiredRequests, id)
  53. close(r.response)
  54. }
  55. }
  56. for _, id := range expiredRequests {
  57. delete(this.requests, id)
  58. }
  59. this.Unlock()
  60. expiredRequests = nil
  61. }
  62. // @Private
  63. func (this *UDPNameServer) AssignUnusedID(response chan<- *ARecord) uint16 {
  64. var id uint16
  65. this.Lock()
  66. if len(this.requests) > CleanupThreshold && this.nextCleanup.Before(time.Now()) {
  67. this.nextCleanup = time.Now().Add(CleanupInterval)
  68. go this.Cleanup()
  69. }
  70. for {
  71. id = uint16(rand.Intn(65536))
  72. if _, found := this.requests[id]; found {
  73. continue
  74. }
  75. log.Debug("DNS: Add pending request id ", id)
  76. this.requests[id] = &PendingRequest{
  77. expire: time.Now().Add(time.Second * 16),
  78. response: response,
  79. }
  80. break
  81. }
  82. this.Unlock()
  83. return id
  84. }
  85. // @Private
  86. func (this *UDPNameServer) HandleResponse(dest v2net.Destination, payload *alloc.Buffer) {
  87. msg := new(dns.Msg)
  88. err := msg.Unpack(payload.Value)
  89. if err != nil {
  90. log.Warning("DNS: Failed to parse DNS response: ", err)
  91. return
  92. }
  93. record := &ARecord{
  94. IPs: make([]net.IP, 0, 16),
  95. }
  96. id := msg.Id
  97. ttl := DefaultTTL
  98. log.Debug("DNS: Handling response for id ", id, " content: ", msg.String())
  99. this.Lock()
  100. request, found := this.requests[id]
  101. if !found {
  102. this.Unlock()
  103. return
  104. }
  105. delete(this.requests, id)
  106. this.Unlock()
  107. for _, rr := range msg.Answer {
  108. switch rr := rr.(type) {
  109. case *dns.A:
  110. record.IPs = append(record.IPs, rr.A)
  111. if rr.Hdr.Ttl < ttl {
  112. ttl = rr.Hdr.Ttl
  113. }
  114. case *dns.AAAA:
  115. record.IPs = append(record.IPs, rr.AAAA)
  116. if rr.Hdr.Ttl < ttl {
  117. ttl = rr.Hdr.Ttl
  118. }
  119. }
  120. }
  121. record.Expire = time.Now().Add(time.Second * time.Duration(ttl))
  122. request.response <- record
  123. close(request.response)
  124. }
  125. func (this *UDPNameServer) QueryA(domain string) <-chan *ARecord {
  126. response := make(chan *ARecord, 1)
  127. buffer := alloc.NewBuffer()
  128. msg := new(dns.Msg)
  129. msg.Id = this.AssignUnusedID(response)
  130. msg.RecursionDesired = true
  131. msg.Question = []dns.Question{
  132. dns.Question{
  133. Name: dns.Fqdn(domain),
  134. Qtype: dns.TypeA,
  135. Qclass: dns.ClassINET,
  136. }}
  137. writtenBuffer, _ := msg.PackBuffer(buffer.Value)
  138. buffer.Slice(0, len(writtenBuffer))
  139. fakeDestination := v2net.UDPDestination(v2net.LocalHostIP, v2net.Port(53))
  140. this.udpServer.Dispatch(fakeDestination, this.address, buffer, this.HandleResponse)
  141. return response
  142. }
  143. type LocalNameServer struct {
  144. }
  145. func (this *LocalNameServer) QueryA(domain string) <-chan *ARecord {
  146. response := make(chan *ARecord, 1)
  147. go func() {
  148. defer close(response)
  149. ips, err := net.LookupIP(domain)
  150. if err != nil {
  151. log.Info("DNS: Failed to lookup IPs for domain ", domain)
  152. return
  153. }
  154. response <- &ARecord{
  155. IPs: ips,
  156. Expire: time.Now().Add(time.Second * time.Duration(DefaultTTL)),
  157. }
  158. }()
  159. return response
  160. }