nameserver.go 4.4 KB

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