udpns.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. o.SetUDPSize(1280)
  131. if len(s.clientIP.V4) == 4 {
  132. e := new(dns.EDNS0_SUBNET)
  133. e.Code = dns.EDNS0SUBNET
  134. e.Family = 1 // 1 for IPv4 source address, 2 for IPv6
  135. e.SourceNetmask = 24 // 32 for IPV4, 128 for IPv6
  136. e.SourceScope = 0
  137. e.Address = net.IP(s.clientIP.V4)
  138. o.Option = append(o.Option, e)
  139. }
  140. if len(s.clientIP.V6) == 16 {
  141. e := new(dns.EDNS0_SUBNET)
  142. e.Code = dns.EDNS0SUBNET
  143. e.Family = 2 // 1 for IPv4 source address, 2 for IPv6
  144. e.SourceNetmask = 24 // 32 for IPV4, 128 for IPv6
  145. e.SourceScope = 0
  146. e.Address = net.IP(s.clientIP.V6)
  147. o.Option = append(o.Option, e)
  148. }
  149. return o
  150. }
  151. func (s *ClassicNameServer) buildMsgs(domain string) []*dns.Msg {
  152. allowMulti := multiQuestionDNS[s.address.Address]
  153. qA := dns.Question{
  154. Name: domain,
  155. Qtype: dns.TypeA,
  156. Qclass: dns.ClassINET,
  157. }
  158. qAAAA := dns.Question{
  159. Name: domain,
  160. Qtype: dns.TypeAAAA,
  161. Qclass: dns.ClassINET,
  162. }
  163. var msgs []*dns.Msg
  164. {
  165. msg := new(dns.Msg)
  166. msg.Id = uint16(atomic.AddUint32(&s.reqID, 1))
  167. msg.RecursionDesired = true
  168. msg.Question = []dns.Question{qA}
  169. if allowMulti {
  170. msg.Question = append(msg.Question, qAAAA)
  171. }
  172. if opt := s.getMsgOptions(); opt != nil {
  173. msg.Extra = append(msg.Extra, opt)
  174. }
  175. msgs = append(msgs, msg)
  176. }
  177. if !allowMulti {
  178. msg := new(dns.Msg)
  179. msg.Id = uint16(atomic.AddUint32(&s.reqID, 1))
  180. msg.RecursionDesired = true
  181. msg.Question = []dns.Question{qAAAA}
  182. if opt := s.getMsgOptions(); opt != nil {
  183. msg.Extra = append(msg.Extra, opt)
  184. }
  185. msgs = append(msgs, msg)
  186. }
  187. return msgs
  188. }
  189. func msgToBuffer(msg *dns.Msg) (*buf.Buffer, error) {
  190. buffer := buf.New()
  191. if err := buffer.Reset(func(b []byte) (int, error) {
  192. writtenBuffer, err := msg.PackBuffer(b)
  193. return len(writtenBuffer), err
  194. }); err != nil {
  195. return nil, err
  196. }
  197. return buffer, nil
  198. }
  199. func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string) {
  200. msgs := s.buildMsgs(domain)
  201. for _, msg := range msgs {
  202. b, err := msgToBuffer(msg)
  203. common.Must(err)
  204. s.udpServer.Dispatch(ctx, s.address, b, s.HandleResponse)
  205. }
  206. }
  207. func (s *ClassicNameServer) findIPsForDomain(domain string) []net.IP {
  208. records, found := s.ips[domain]
  209. if found && len(records) > 0 {
  210. var ips []net.IP
  211. now := time.Now()
  212. for _, rec := range records {
  213. if rec.Expire.After(now) {
  214. ips = append(ips, rec.IP)
  215. }
  216. }
  217. return ips
  218. }
  219. return nil
  220. }
  221. func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string) ([]net.IP, error) {
  222. fqdn := dns.Fqdn(domain)
  223. ips := s.findIPsForDomain(fqdn)
  224. if len(ips) > 0 {
  225. return ips, nil
  226. }
  227. s.sendQuery(ctx, fqdn)
  228. for {
  229. ips := s.findIPsForDomain(fqdn)
  230. if len(ips) > 0 {
  231. return ips, nil
  232. }
  233. select {
  234. case <-ctx.Done():
  235. return nil, ctx.Err()
  236. case <-s.updated.Wait():
  237. }
  238. }
  239. }