nameserver.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package server
  2. import (
  3. "context"
  4. "net"
  5. "sync"
  6. "time"
  7. "github.com/miekg/dns"
  8. "v2ray.com/core/app/dispatcher"
  9. "v2ray.com/core/app/log"
  10. "v2ray.com/core/common/buf"
  11. "v2ray.com/core/common/dice"
  12. "v2ray.com/core/common/errors"
  13. v2net "v2ray.com/core/common/net"
  14. "v2ray.com/core/transport/internet/udp"
  15. )
  16. const (
  17. DefaultTTL = uint32(3600)
  18. CleanupInterval = time.Second * 120
  19. CleanupThreshold = 512
  20. )
  21. var (
  22. pseudoDestination = v2net.UDPDestination(v2net.LocalHostIP, v2net.Port(53))
  23. )
  24. type ARecord struct {
  25. IPs []net.IP
  26. Expire time.Time
  27. }
  28. type NameServer interface {
  29. QueryA(domain string) <-chan *ARecord
  30. }
  31. type PendingRequest struct {
  32. expire time.Time
  33. response chan<- *ARecord
  34. }
  35. type UDPNameServer struct {
  36. sync.Mutex
  37. address v2net.Destination
  38. requests map[uint16]*PendingRequest
  39. udpServer *udp.Dispatcher
  40. nextCleanup time.Time
  41. }
  42. func NewUDPNameServer(address v2net.Destination, dispatcher dispatcher.Interface) *UDPNameServer {
  43. s := &UDPNameServer{
  44. address: address,
  45. requests: make(map[uint16]*PendingRequest),
  46. udpServer: udp.NewDispatcher(dispatcher),
  47. }
  48. return s
  49. }
  50. // Private: Visible for testing.
  51. func (v *UDPNameServer) Cleanup() {
  52. expiredRequests := make([]uint16, 0, 16)
  53. now := time.Now()
  54. v.Lock()
  55. for id, r := range v.requests {
  56. if r.expire.Before(now) {
  57. expiredRequests = append(expiredRequests, id)
  58. close(r.response)
  59. }
  60. }
  61. for _, id := range expiredRequests {
  62. delete(v.requests, id)
  63. }
  64. v.Unlock()
  65. expiredRequests = nil
  66. }
  67. // Private: Visible for testing.
  68. func (v *UDPNameServer) AssignUnusedID(response chan<- *ARecord) uint16 {
  69. var id uint16
  70. v.Lock()
  71. if len(v.requests) > CleanupThreshold && v.nextCleanup.Before(time.Now()) {
  72. v.nextCleanup = time.Now().Add(CleanupInterval)
  73. go v.Cleanup()
  74. }
  75. for {
  76. id = dice.RandomUint16()
  77. if _, found := v.requests[id]; found {
  78. continue
  79. }
  80. log.Debug("DNS: Add pending request id ", id)
  81. v.requests[id] = &PendingRequest{
  82. expire: time.Now().Add(time.Second * 8),
  83. response: response,
  84. }
  85. break
  86. }
  87. v.Unlock()
  88. return id
  89. }
  90. // Private: Visible for testing.
  91. func (v *UDPNameServer) HandleResponse(payload *buf.Buffer) {
  92. msg := new(dns.Msg)
  93. err := msg.Unpack(payload.Bytes())
  94. if err != nil {
  95. log.Warning("DNS: Failed to parse DNS response: ", err)
  96. return
  97. }
  98. record := &ARecord{
  99. IPs: make([]net.IP, 0, 16),
  100. }
  101. id := msg.Id
  102. ttl := DefaultTTL
  103. log.Debug("DNS: Handling response for id ", id, " content: ", msg.String())
  104. v.Lock()
  105. request, found := v.requests[id]
  106. if !found {
  107. v.Unlock()
  108. return
  109. }
  110. delete(v.requests, id)
  111. v.Unlock()
  112. for _, rr := range msg.Answer {
  113. switch rr := rr.(type) {
  114. case *dns.A:
  115. record.IPs = append(record.IPs, rr.A)
  116. if rr.Hdr.Ttl < ttl {
  117. ttl = rr.Hdr.Ttl
  118. }
  119. case *dns.AAAA:
  120. record.IPs = append(record.IPs, rr.AAAA)
  121. if rr.Hdr.Ttl < ttl {
  122. ttl = rr.Hdr.Ttl
  123. }
  124. }
  125. }
  126. record.Expire = time.Now().Add(time.Second * time.Duration(ttl))
  127. request.response <- record
  128. close(request.response)
  129. }
  130. func (v *UDPNameServer) BuildQueryA(domain string, id uint16) *buf.Buffer {
  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. buffer := buf.New()
  141. buffer.AppendSupplier(func(b []byte) (int, error) {
  142. writtenBuffer, err := msg.PackBuffer(b)
  143. return len(writtenBuffer), err
  144. })
  145. return buffer
  146. }
  147. func (v *UDPNameServer) QueryA(domain string) <-chan *ARecord {
  148. response := make(chan *ARecord, 1)
  149. id := v.AssignUnusedID(response)
  150. ctx, cancel := context.WithTimeout(context.Background(), time.Second*8)
  151. v.udpServer.Dispatch(ctx, v.address, v.BuildQueryA(domain, id), v.HandleResponse)
  152. go func() {
  153. for i := 0; i < 2; i++ {
  154. time.Sleep(time.Second)
  155. v.Lock()
  156. _, found := v.requests[id]
  157. v.Unlock()
  158. if found {
  159. v.udpServer.Dispatch(ctx, v.address, v.BuildQueryA(domain, id), v.HandleResponse)
  160. } else {
  161. break
  162. }
  163. }
  164. cancel()
  165. }()
  166. return response
  167. }
  168. type LocalNameServer struct {
  169. }
  170. func (v *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.Trace(errors.New("failed to lookup IPs for domain ", domain).Path("App", "DNS").Base(err))
  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. }