udpns.go 6.2 KB

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