udpns.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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/pubsub"
  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. pub *pubsub.Service
  32. udpServer *udp.Dispatcher
  33. cleanup *task.Periodic
  34. reqID uint32
  35. clientIP net.IP
  36. }
  37. func NewClassicNameServer(address net.Destination, dispatcher core.Dispatcher, clientIP net.IP) *ClassicNameServer {
  38. s := &ClassicNameServer{
  39. address: address,
  40. ips: make(map[string][]IPRecord),
  41. udpServer: udp.NewDispatcher(dispatcher),
  42. clientIP: clientIP,
  43. pub: pubsub.NewService(),
  44. }
  45. s.cleanup = &task.Periodic{
  46. Interval: time.Minute,
  47. Execute: s.Cleanup,
  48. }
  49. common.Must(s.cleanup.Start())
  50. return s
  51. }
  52. func (s *ClassicNameServer) Cleanup() error {
  53. now := time.Now()
  54. s.Lock()
  55. for domain, ips := range s.ips {
  56. newIPs := make([]IPRecord, 0, len(ips))
  57. for _, ip := range ips {
  58. if ip.Expire.After(now) {
  59. newIPs = append(newIPs, ip)
  60. }
  61. }
  62. if len(newIPs) == 0 {
  63. delete(s.ips, domain)
  64. } else if len(newIPs) < len(ips) {
  65. s.ips[domain] = newIPs
  66. }
  67. }
  68. if len(s.ips) == 0 {
  69. s.ips = make(map[string][]IPRecord)
  70. }
  71. s.Unlock()
  72. return nil
  73. }
  74. func (s *ClassicNameServer) HandleResponse(payload *buf.Buffer) {
  75. msg := new(dns.Msg)
  76. err := msg.Unpack(payload.Bytes())
  77. if err == dns.ErrTruncated {
  78. newError("truncated message received. DNS server should still work. If you see anything abnormal, please submit an issue to v2ray-core.").AtWarning().WriteToLog()
  79. } else if err != nil {
  80. newError("failed to parse DNS response").Base(err).AtWarning().WriteToLog()
  81. return
  82. }
  83. var domain string
  84. ips := make([]IPRecord, 0, 16)
  85. now := time.Now()
  86. for _, rr := range msg.Answer {
  87. var ip net.IP
  88. name := rr.Header().Name
  89. if len(name) > 0 {
  90. domain = rr.Header().Name
  91. }
  92. ttl := rr.Header().Ttl
  93. switch rr := rr.(type) {
  94. case *dns.A:
  95. ip = rr.A
  96. case *dns.AAAA:
  97. ip = rr.AAAA
  98. }
  99. if ttl == 0 {
  100. ttl = 600
  101. }
  102. if len(ip) > 0 {
  103. ips = append(ips, IPRecord{
  104. IP: ip,
  105. Expire: now.Add(time.Second * time.Duration(ttl)),
  106. })
  107. }
  108. }
  109. if len(domain) > 0 && len(ips) > 0 {
  110. s.updateIP(domain, ips)
  111. }
  112. }
  113. func (s *ClassicNameServer) updateIP(domain string, ips []IPRecord) {
  114. s.Lock()
  115. defer s.Unlock()
  116. newError("updating IP records for domain:", domain).AtDebug().WriteToLog()
  117. now := time.Now()
  118. eips := s.ips[domain]
  119. for _, ip := range eips {
  120. if ip.Expire.After(now) {
  121. ips = append(ips, ip)
  122. }
  123. }
  124. s.ips[domain] = ips
  125. s.pub.Publish(domain, nil)
  126. }
  127. func (s *ClassicNameServer) getMsgOptions() *dns.OPT {
  128. if len(s.clientIP) == 0 {
  129. return nil
  130. }
  131. o := new(dns.OPT)
  132. o.Hdr.Name = "."
  133. o.Hdr.Rrtype = dns.TypeOPT
  134. o.SetUDPSize(1280)
  135. e := new(dns.EDNS0_SUBNET)
  136. e.Code = dns.EDNS0SUBNET
  137. if len(s.clientIP) == 4 {
  138. e.Family = 1 // 1 for IPv4 source address, 2 for IPv6
  139. } else {
  140. e.Family = 2
  141. }
  142. e.SourceNetmask = 24 // 32 for IPV4, 128 for IPv6
  143. e.SourceScope = 0
  144. e.Address = s.clientIP
  145. o.Option = append(o.Option, e)
  146. return o
  147. }
  148. func (s *ClassicNameServer) buildMsgs(domain string) []*dns.Msg {
  149. allowMulti := multiQuestionDNS[s.address.Address]
  150. qA := dns.Question{
  151. Name: domain,
  152. Qtype: dns.TypeA,
  153. Qclass: dns.ClassINET,
  154. }
  155. qAAAA := dns.Question{
  156. Name: domain,
  157. Qtype: dns.TypeAAAA,
  158. Qclass: dns.ClassINET,
  159. }
  160. var msgs []*dns.Msg
  161. {
  162. msg := new(dns.Msg)
  163. msg.Id = uint16(atomic.AddUint32(&s.reqID, 1))
  164. msg.RecursionDesired = true
  165. msg.Question = []dns.Question{qA}
  166. if allowMulti {
  167. msg.Question = append(msg.Question, qAAAA)
  168. }
  169. if opt := s.getMsgOptions(); opt != nil {
  170. msg.Extra = append(msg.Extra, opt)
  171. }
  172. msgs = append(msgs, msg)
  173. }
  174. if !allowMulti {
  175. msg := new(dns.Msg)
  176. msg.Id = uint16(atomic.AddUint32(&s.reqID, 1))
  177. msg.RecursionDesired = true
  178. msg.Question = []dns.Question{qAAAA}
  179. if opt := s.getMsgOptions(); opt != nil {
  180. msg.Extra = append(msg.Extra, opt)
  181. }
  182. msgs = append(msgs, msg)
  183. }
  184. return msgs
  185. }
  186. func msgToBuffer(msg *dns.Msg) (*buf.Buffer, error) {
  187. buffer := buf.New()
  188. if err := buffer.Reset(func(b []byte) (int, error) {
  189. writtenBuffer, err := msg.PackBuffer(b)
  190. return len(writtenBuffer), err
  191. }); err != nil {
  192. return nil, err
  193. }
  194. return buffer, nil
  195. }
  196. func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string) {
  197. msgs := s.buildMsgs(domain)
  198. for _, msg := range msgs {
  199. b, err := msgToBuffer(msg)
  200. common.Must(err)
  201. s.udpServer.Dispatch(ctx, s.address, b, s.HandleResponse)
  202. }
  203. }
  204. func (s *ClassicNameServer) findIPsForDomain(domain string) []net.IP {
  205. s.RLock()
  206. records, found := s.ips[domain]
  207. s.RUnlock()
  208. if found && len(records) > 0 {
  209. var ips []net.IP
  210. now := time.Now()
  211. for _, rec := range records {
  212. if rec.Expire.After(now) {
  213. ips = append(ips, rec.IP)
  214. }
  215. }
  216. return ips
  217. }
  218. return nil
  219. }
  220. func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string) ([]net.IP, error) {
  221. fqdn := dns.Fqdn(domain)
  222. ips := s.findIPsForDomain(fqdn)
  223. if len(ips) > 0 {
  224. return ips, nil
  225. }
  226. sub := s.pub.Subscribe(fqdn)
  227. defer sub.Close()
  228. s.sendQuery(ctx, fqdn)
  229. for {
  230. ips := s.findIPsForDomain(fqdn)
  231. if len(ips) > 0 {
  232. return ips, nil
  233. }
  234. select {
  235. case <-ctx.Done():
  236. return nil, ctx.Err()
  237. case <-sub.Wait():
  238. }
  239. }
  240. }