udpns.go 4.8 KB

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