udpns.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package dns
  2. import (
  3. "context"
  4. "strings"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/xtls/xray-core/common"
  9. "github.com/xtls/xray-core/common/net"
  10. "github.com/xtls/xray-core/common/protocol/dns"
  11. udp_proto "github.com/xtls/xray-core/common/protocol/udp"
  12. "github.com/xtls/xray-core/common/session"
  13. "github.com/xtls/xray-core/common/signal/pubsub"
  14. "github.com/xtls/xray-core/common/task"
  15. dns_feature "github.com/xtls/xray-core/features/dns"
  16. "github.com/xtls/xray-core/features/routing"
  17. "github.com/xtls/xray-core/transport/internet/udp"
  18. "golang.org/x/net/dns/dnsmessage"
  19. )
  20. type ClassicNameServer struct {
  21. sync.RWMutex
  22. name string
  23. address net.Destination
  24. ips map[string]record
  25. requests map[uint16]dnsRequest
  26. pub *pubsub.Service
  27. udpServer *udp.Dispatcher
  28. cleanup *task.Periodic
  29. reqID uint32
  30. clientIP net.IP
  31. }
  32. func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, clientIP net.IP) *ClassicNameServer {
  33. // default to 53 if unspecific
  34. if address.Port == 0 {
  35. address.Port = net.Port(53)
  36. }
  37. s := &ClassicNameServer{
  38. address: address,
  39. ips: make(map[string]record),
  40. requests: make(map[uint16]dnsRequest),
  41. clientIP: clientIP,
  42. pub: pubsub.NewService(),
  43. name: strings.ToUpper(address.String()),
  44. }
  45. s.cleanup = &task.Periodic{
  46. Interval: time.Minute,
  47. Execute: s.Cleanup,
  48. }
  49. s.udpServer = udp.NewDispatcher(dispatcher, s.HandleResponse)
  50. newError("DNS: created udp client inited for ", address.NetAddr()).AtInfo().WriteToLog()
  51. return s
  52. }
  53. func (s *ClassicNameServer) Name() string {
  54. return s.name
  55. }
  56. func (s *ClassicNameServer) Cleanup() error {
  57. now := time.Now()
  58. s.Lock()
  59. defer s.Unlock()
  60. if len(s.ips) == 0 && len(s.requests) == 0 {
  61. return newError(s.name, " nothing to do. stopping...")
  62. }
  63. for domain, record := range s.ips {
  64. if record.A != nil && record.A.Expire.Before(now) {
  65. record.A = nil
  66. }
  67. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  68. record.AAAA = nil
  69. }
  70. if record.A == nil && record.AAAA == nil {
  71. delete(s.ips, domain)
  72. } else {
  73. s.ips[domain] = record
  74. }
  75. }
  76. if len(s.ips) == 0 {
  77. s.ips = make(map[string]record)
  78. }
  79. for id, req := range s.requests {
  80. if req.expire.Before(now) {
  81. delete(s.requests, id)
  82. }
  83. }
  84. if len(s.requests) == 0 {
  85. s.requests = make(map[uint16]dnsRequest)
  86. }
  87. return nil
  88. }
  89. func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_proto.Packet) {
  90. ipRec, err := parseResponse(packet.Payload.Bytes())
  91. if err != nil {
  92. newError(s.name, " fail to parse responded DNS udp").AtError().WriteToLog()
  93. return
  94. }
  95. s.Lock()
  96. id := ipRec.ReqID
  97. req, ok := s.requests[id]
  98. if ok {
  99. // remove the pending request
  100. delete(s.requests, id)
  101. }
  102. s.Unlock()
  103. if !ok {
  104. newError(s.name, " cannot find the pending request").AtError().WriteToLog()
  105. return
  106. }
  107. var rec record
  108. switch req.reqType {
  109. case dnsmessage.TypeA:
  110. rec.A = ipRec
  111. case dnsmessage.TypeAAAA:
  112. rec.AAAA = ipRec
  113. }
  114. elapsed := time.Since(req.start)
  115. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  116. if len(req.domain) > 0 && (rec.A != nil || rec.AAAA != nil) {
  117. s.updateIP(req.domain, rec)
  118. }
  119. }
  120. func (s *ClassicNameServer) updateIP(domain string, newRec record) {
  121. s.Lock()
  122. newError(s.name, " updating IP records for domain:", domain).AtDebug().WriteToLog()
  123. rec := s.ips[domain]
  124. updated := false
  125. if isNewer(rec.A, newRec.A) {
  126. rec.A = newRec.A
  127. updated = true
  128. }
  129. if isNewer(rec.AAAA, newRec.AAAA) {
  130. rec.AAAA = newRec.AAAA
  131. updated = true
  132. }
  133. if updated {
  134. s.ips[domain] = rec
  135. }
  136. if newRec.A != nil {
  137. s.pub.Publish(domain+"4", nil)
  138. }
  139. if newRec.AAAA != nil {
  140. s.pub.Publish(domain+"6", nil)
  141. }
  142. s.Unlock()
  143. common.Must(s.cleanup.Start())
  144. }
  145. func (s *ClassicNameServer) newReqID() uint16 {
  146. return uint16(atomic.AddUint32(&s.reqID, 1))
  147. }
  148. func (s *ClassicNameServer) addPendingRequest(req *dnsRequest) {
  149. s.Lock()
  150. defer s.Unlock()
  151. id := req.msg.ID
  152. req.expire = time.Now().Add(time.Second * 8)
  153. s.requests[id] = *req
  154. }
  155. func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, option IPOption) {
  156. newError(s.name, " querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  157. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.clientIP))
  158. for _, req := range reqs {
  159. s.addPendingRequest(req)
  160. b, _ := dns.PackMessage(req.msg)
  161. udpCtx := context.Background()
  162. if inbound := session.InboundFromContext(ctx); inbound != nil {
  163. udpCtx = session.ContextWithInbound(udpCtx, inbound)
  164. }
  165. udpCtx = session.ContextWithContent(udpCtx, &session.Content{
  166. Protocol: "dns",
  167. })
  168. s.udpServer.Dispatch(udpCtx, s.address, b)
  169. }
  170. }
  171. func (s *ClassicNameServer) findIPsForDomain(domain string, option IPOption) ([]net.IP, error) {
  172. s.RLock()
  173. record, found := s.ips[domain]
  174. s.RUnlock()
  175. if !found {
  176. return nil, errRecordNotFound
  177. }
  178. var ips []net.Address
  179. var lastErr error
  180. if option.IPv4Enable {
  181. a, err := record.A.getIPs()
  182. if err != nil {
  183. lastErr = err
  184. }
  185. ips = append(ips, a...)
  186. }
  187. if option.IPv6Enable {
  188. aaaa, err := record.AAAA.getIPs()
  189. if err != nil {
  190. lastErr = err
  191. }
  192. ips = append(ips, aaaa...)
  193. }
  194. if len(ips) > 0 {
  195. return toNetIP(ips), nil
  196. }
  197. if lastErr != nil {
  198. return nil, lastErr
  199. }
  200. return nil, dns_feature.ErrEmptyResponse
  201. }
  202. func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  203. fqdn := Fqdn(domain)
  204. ips, err := s.findIPsForDomain(fqdn, option)
  205. if err != errRecordNotFound {
  206. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  207. return ips, err
  208. }
  209. // ipv4 and ipv6 belong to different subscription groups
  210. var sub4, sub6 *pubsub.Subscriber
  211. if option.IPv4Enable {
  212. sub4 = s.pub.Subscribe(fqdn + "4")
  213. defer sub4.Close()
  214. }
  215. if option.IPv6Enable {
  216. sub6 = s.pub.Subscribe(fqdn + "6")
  217. defer sub6.Close()
  218. }
  219. done := make(chan interface{})
  220. go func() {
  221. if sub4 != nil {
  222. select {
  223. case <-sub4.Wait():
  224. case <-ctx.Done():
  225. }
  226. }
  227. if sub6 != nil {
  228. select {
  229. case <-sub6.Wait():
  230. case <-ctx.Done():
  231. }
  232. }
  233. close(done)
  234. }()
  235. s.sendQuery(ctx, fqdn, option)
  236. for {
  237. ips, err := s.findIPsForDomain(fqdn, option)
  238. if err != errRecordNotFound {
  239. return ips, err
  240. }
  241. select {
  242. case <-ctx.Done():
  243. return nil, ctx.Err()
  244. case <-done:
  245. }
  246. }
  247. }