udpns.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package dns
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "github.com/miekg/dns"
  8. "v2ray.com/core"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/buf"
  11. "v2ray.com/core/common/net"
  12. "v2ray.com/core/common/signal"
  13. "v2ray.com/core/common/task"
  14. "v2ray.com/core/transport/internet/udp"
  15. )
  16. type IPRecord struct {
  17. IP net.IP
  18. Expire time.Time
  19. }
  20. type ClassicNameServer struct {
  21. sync.RWMutex
  22. address net.Destination
  23. ips map[string][]IPRecord
  24. updated signal.Notifier
  25. udpServer *udp.Dispatcher
  26. cleanup *task.Periodic
  27. reqID uint32
  28. }
  29. func NewClassicNameServer(address net.Destination, dispatcher core.Dispatcher) *ClassicNameServer {
  30. s := &ClassicNameServer{
  31. address: address,
  32. ips: make(map[string][]IPRecord),
  33. udpServer: udp.NewDispatcher(dispatcher),
  34. }
  35. s.cleanup = &task.Periodic{
  36. Interval: time.Minute,
  37. Execute: s.Cleanup,
  38. }
  39. common.Must(s.cleanup.Start())
  40. return s
  41. }
  42. func (s *ClassicNameServer) Cleanup() error {
  43. now := time.Now()
  44. s.Lock()
  45. for domain, ips := range s.ips {
  46. newIPs := make([]IPRecord, 0, len(ips))
  47. for _, ip := range ips {
  48. if ip.Expire.After(now) {
  49. newIPs = append(newIPs, ip)
  50. }
  51. }
  52. if len(newIPs) == 0 {
  53. delete(s.ips, domain)
  54. } else if len(newIPs) < len(ips) {
  55. s.ips[domain] = newIPs
  56. }
  57. }
  58. if len(s.ips) == 0 {
  59. s.ips = make(map[string][]IPRecord)
  60. }
  61. s.Unlock()
  62. return nil
  63. }
  64. func (s *ClassicNameServer) HandleResponse(payload *buf.Buffer) {
  65. msg := new(dns.Msg)
  66. err := msg.Unpack(payload.Bytes())
  67. if err == dns.ErrTruncated {
  68. newError("truncated message received. DNS server should still work. If you see anything abnormal, please submit an issue to v2ray-core.").AtWarning().WriteToLog()
  69. } else if err != nil {
  70. newError("failed to parse DNS response").Base(err).AtWarning().WriteToLog()
  71. return
  72. }
  73. var domain string
  74. ips := make([]IPRecord, 0, 16)
  75. now := time.Now()
  76. for _, rr := range msg.Answer {
  77. var ip net.IP
  78. domain = rr.Header().Name
  79. ttl := rr.Header().Ttl
  80. switch rr := rr.(type) {
  81. case *dns.A:
  82. ip = rr.A
  83. case *dns.AAAA:
  84. ip = rr.AAAA
  85. }
  86. if ttl == 0 {
  87. ttl = 300
  88. }
  89. if len(ip) > 0 {
  90. ips = append(ips, IPRecord{
  91. IP: ip,
  92. Expire: now.Add(time.Second * time.Duration(ttl)),
  93. })
  94. }
  95. }
  96. if len(domain) > 0 && len(ips) > 0 {
  97. s.updateIP(domain, ips)
  98. }
  99. }
  100. func (s *ClassicNameServer) updateIP(domain string, ips []IPRecord) {
  101. s.Lock()
  102. defer s.Unlock()
  103. newError("updating IP records for domain:", domain).AtDebug().WriteToLog()
  104. now := time.Now()
  105. eips := s.ips[domain]
  106. for _, ip := range eips {
  107. if ip.Expire.After(now) {
  108. ips = append(ips, ip)
  109. }
  110. }
  111. s.ips[domain] = ips
  112. s.updated.Signal()
  113. }
  114. func (s *ClassicNameServer) buildMsgs(domain string) []*dns.Msg {
  115. allowMulti := multiQuestionDNS[s.address.Address]
  116. var msgs []*dns.Msg
  117. {
  118. msg := new(dns.Msg)
  119. msg.Id = uint16(atomic.AddUint32(&s.reqID, 1))
  120. msg.RecursionDesired = true
  121. msg.Question = []dns.Question{
  122. {
  123. Name: domain,
  124. Qtype: dns.TypeA,
  125. Qclass: dns.ClassINET,
  126. }}
  127. if allowMulti {
  128. msg.Question = append(msg.Question, dns.Question{
  129. Name: domain,
  130. Qtype: dns.TypeAAAA,
  131. Qclass: dns.ClassINET,
  132. })
  133. }
  134. msgs = append(msgs, msg)
  135. }
  136. if !allowMulti {
  137. msg := new(dns.Msg)
  138. msg.Id = uint16(atomic.AddUint32(&s.reqID, 1))
  139. msg.RecursionDesired = true
  140. msg.Question = []dns.Question{
  141. {
  142. Name: domain,
  143. Qtype: dns.TypeAAAA,
  144. Qclass: dns.ClassINET,
  145. },
  146. }
  147. msgs = append(msgs, msg)
  148. }
  149. return msgs
  150. }
  151. func msgToBuffer(msg *dns.Msg) (*buf.Buffer, error) {
  152. buffer := buf.New()
  153. if err := buffer.Reset(func(b []byte) (int, error) {
  154. writtenBuffer, err := msg.PackBuffer(b)
  155. return len(writtenBuffer), err
  156. }); err != nil {
  157. return nil, err
  158. }
  159. return buffer, nil
  160. }
  161. func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string) {
  162. msgs := s.buildMsgs(domain)
  163. for _, msg := range msgs {
  164. b, err := msgToBuffer(msg)
  165. common.Must(err)
  166. s.udpServer.Dispatch(ctx, s.address, b, s.HandleResponse)
  167. }
  168. }
  169. func (s *ClassicNameServer) findIPsForDomain(domain string) []net.IP {
  170. records, found := s.ips[domain]
  171. if found && len(records) > 0 {
  172. var ips []net.IP
  173. now := time.Now()
  174. for _, rec := range records {
  175. if rec.Expire.After(now) {
  176. ips = append(ips, rec.IP)
  177. }
  178. }
  179. return ips
  180. }
  181. return nil
  182. }
  183. func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string) ([]net.IP, error) {
  184. fqdn := dns.Fqdn(domain)
  185. ips := s.findIPsForDomain(fqdn)
  186. if len(ips) > 0 {
  187. return ips, nil
  188. }
  189. s.sendQuery(ctx, fqdn)
  190. for {
  191. ips := s.findIPsForDomain(fqdn)
  192. if len(ips) > 0 {
  193. return ips, nil
  194. }
  195. select {
  196. case <-ctx.Done():
  197. return nil, ctx.Err()
  198. case <-s.updated.Wait():
  199. }
  200. }
  201. }