udpns.go 5.7 KB

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