nameserver.go 4.4 KB

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