nameserver.go 4.6 KB

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