nameserver_quic.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package dns
  2. import (
  3. "context"
  4. "net/url"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "github.com/lucas-clemente/quic-go"
  9. "golang.org/x/net/dns/dnsmessage"
  10. "golang.org/x/net/http2"
  11. "github.com/xtls/xray-core/common"
  12. "github.com/xtls/xray-core/common/buf"
  13. "github.com/xtls/xray-core/common/net"
  14. "github.com/xtls/xray-core/common/protocol/dns"
  15. "github.com/xtls/xray-core/common/session"
  16. "github.com/xtls/xray-core/common/signal/pubsub"
  17. "github.com/xtls/xray-core/common/task"
  18. dns_feature "github.com/xtls/xray-core/features/dns"
  19. "github.com/xtls/xray-core/transport/internet/tls"
  20. )
  21. // NextProtoDQ - During connection establishment, DNS/QUIC support is indicated
  22. // by selecting the ALPN token "dq" in the crypto handshake.
  23. const NextProtoDQ = "doq-i00"
  24. const handshakeTimeout = time.Second * 8
  25. // QUICNameServer implemented DNS over QUIC
  26. type QUICNameServer struct {
  27. sync.RWMutex
  28. ips map[string]record
  29. pub *pubsub.Service
  30. cleanup *task.Periodic
  31. reqID uint32
  32. name string
  33. destination net.Destination
  34. session quic.Session
  35. }
  36. // NewQUICNameServer creates DNS-over-QUIC client object for local resolving
  37. func NewQUICNameServer(url *url.URL) (*QUICNameServer, error) {
  38. newError("DNS: created Local DNS-over-QUIC client for ", url.String()).AtInfo().WriteToLog()
  39. var err error
  40. port := net.Port(784)
  41. if url.Port() != "" {
  42. port, err = net.PortFromString(url.Port())
  43. if err != nil {
  44. return nil, err
  45. }
  46. }
  47. dest := net.UDPDestination(net.DomainAddress(url.Hostname()), port)
  48. s := &QUICNameServer{
  49. ips: make(map[string]record),
  50. pub: pubsub.NewService(),
  51. name: url.String(),
  52. destination: dest,
  53. }
  54. s.cleanup = &task.Periodic{
  55. Interval: time.Minute,
  56. Execute: s.Cleanup,
  57. }
  58. return s, nil
  59. }
  60. // Name returns client name
  61. func (s *QUICNameServer) Name() string {
  62. return s.name
  63. }
  64. // Cleanup clears expired items from cache
  65. func (s *QUICNameServer) Cleanup() error {
  66. now := time.Now()
  67. s.Lock()
  68. defer s.Unlock()
  69. if len(s.ips) == 0 {
  70. return newError("nothing to do. stopping...")
  71. }
  72. for domain, record := range s.ips {
  73. if record.A != nil && record.A.Expire.Before(now) {
  74. record.A = nil
  75. }
  76. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  77. record.AAAA = nil
  78. }
  79. if record.A == nil && record.AAAA == nil {
  80. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  81. delete(s.ips, domain)
  82. } else {
  83. s.ips[domain] = record
  84. }
  85. }
  86. if len(s.ips) == 0 {
  87. s.ips = make(map[string]record)
  88. }
  89. return nil
  90. }
  91. func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  92. elapsed := time.Since(req.start)
  93. s.Lock()
  94. rec := s.ips[req.domain]
  95. updated := false
  96. switch req.reqType {
  97. case dnsmessage.TypeA:
  98. if isNewer(rec.A, ipRec) {
  99. rec.A = ipRec
  100. updated = true
  101. }
  102. case dnsmessage.TypeAAAA:
  103. addr := make([]net.Address, 0)
  104. for _, ip := range ipRec.IP {
  105. if len(ip.IP()) == net.IPv6len {
  106. addr = append(addr, ip)
  107. }
  108. }
  109. ipRec.IP = addr
  110. if isNewer(rec.AAAA, ipRec) {
  111. rec.AAAA = ipRec
  112. updated = true
  113. }
  114. }
  115. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  116. if updated {
  117. s.ips[req.domain] = rec
  118. }
  119. switch req.reqType {
  120. case dnsmessage.TypeA:
  121. s.pub.Publish(req.domain+"4", nil)
  122. case dnsmessage.TypeAAAA:
  123. s.pub.Publish(req.domain+"6", nil)
  124. }
  125. s.Unlock()
  126. common.Must(s.cleanup.Start())
  127. }
  128. func (s *QUICNameServer) newReqID() uint16 {
  129. return uint16(atomic.AddUint32(&s.reqID, 1))
  130. }
  131. func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
  132. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  133. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  134. var deadline time.Time
  135. if d, ok := ctx.Deadline(); ok {
  136. deadline = d
  137. } else {
  138. deadline = time.Now().Add(time.Second * 5)
  139. }
  140. for _, req := range reqs {
  141. go func(r *dnsRequest) {
  142. // generate new context for each req, using same context
  143. // may cause reqs all aborted if any one encounter an error
  144. dnsCtx := context.Background()
  145. // reserve internal dns server requested Inbound
  146. if inbound := session.InboundFromContext(ctx); inbound != nil {
  147. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  148. }
  149. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  150. Protocol: "quic",
  151. SkipDNSResolve: true,
  152. })
  153. var cancel context.CancelFunc
  154. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  155. defer cancel()
  156. b, err := dns.PackMessage(r.msg)
  157. if err != nil {
  158. newError("failed to pack dns query").Base(err).AtError().WriteToLog()
  159. return
  160. }
  161. conn, err := s.openStream(dnsCtx)
  162. if err != nil {
  163. newError("failed to open quic session").Base(err).AtError().WriteToLog()
  164. return
  165. }
  166. _, err = conn.Write(b.Bytes())
  167. if err != nil {
  168. newError("failed to send query").Base(err).AtError().WriteToLog()
  169. return
  170. }
  171. _ = conn.Close()
  172. respBuf := buf.New()
  173. defer respBuf.Release()
  174. n, err := respBuf.ReadFrom(conn)
  175. if err != nil && n == 0 {
  176. newError("failed to read response").Base(err).AtError().WriteToLog()
  177. return
  178. }
  179. rec, err := parseResponse(respBuf.Bytes())
  180. if err != nil {
  181. newError("failed to handle response").Base(err).AtError().WriteToLog()
  182. return
  183. }
  184. s.updateIP(r, rec)
  185. }(req)
  186. }
  187. }
  188. func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  189. s.RLock()
  190. record, found := s.ips[domain]
  191. s.RUnlock()
  192. if !found {
  193. return nil, errRecordNotFound
  194. }
  195. var ips []net.Address
  196. var lastErr error
  197. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  198. aaaa, err := record.AAAA.getIPs()
  199. if err != nil {
  200. lastErr = err
  201. }
  202. ips = append(ips, aaaa...)
  203. }
  204. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  205. a, err := record.A.getIPs()
  206. if err != nil {
  207. lastErr = err
  208. }
  209. ips = append(ips, a...)
  210. }
  211. if len(ips) > 0 {
  212. return toNetIP(ips)
  213. }
  214. if lastErr != nil {
  215. return nil, lastErr
  216. }
  217. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  218. return nil, dns_feature.ErrEmptyResponse
  219. }
  220. return nil, errRecordNotFound
  221. }
  222. // QueryIP is called from dns.Server->queryIPTimeout
  223. func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) {
  224. fqdn := Fqdn(domain)
  225. if disableCache {
  226. newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog()
  227. } else {
  228. ips, err := s.findIPsForDomain(fqdn, option)
  229. if err != errRecordNotFound {
  230. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  231. return ips, err
  232. }
  233. }
  234. // ipv4 and ipv6 belong to different subscription groups
  235. var sub4, sub6 *pubsub.Subscriber
  236. if option.IPv4Enable {
  237. sub4 = s.pub.Subscribe(fqdn + "4")
  238. defer sub4.Close()
  239. }
  240. if option.IPv6Enable {
  241. sub6 = s.pub.Subscribe(fqdn + "6")
  242. defer sub6.Close()
  243. }
  244. done := make(chan interface{})
  245. go func() {
  246. if sub4 != nil {
  247. select {
  248. case <-sub4.Wait():
  249. case <-ctx.Done():
  250. }
  251. }
  252. if sub6 != nil {
  253. select {
  254. case <-sub6.Wait():
  255. case <-ctx.Done():
  256. }
  257. }
  258. close(done)
  259. }()
  260. s.sendQuery(ctx, fqdn, clientIP, option)
  261. for {
  262. ips, err := s.findIPsForDomain(fqdn, option)
  263. if err != errRecordNotFound {
  264. return ips, err
  265. }
  266. select {
  267. case <-ctx.Done():
  268. return nil, ctx.Err()
  269. case <-done:
  270. }
  271. }
  272. }
  273. func isActive(s quic.Session) bool {
  274. select {
  275. case <-s.Context().Done():
  276. return false
  277. default:
  278. return true
  279. }
  280. }
  281. func (s *QUICNameServer) getSession() (quic.Session, error) {
  282. var session quic.Session
  283. s.RLock()
  284. session = s.session
  285. if session != nil && isActive(session) {
  286. s.RUnlock()
  287. return session, nil
  288. }
  289. if session != nil {
  290. // we're recreating the session, let's create a new one
  291. _ = session.CloseWithError(0, "")
  292. }
  293. s.RUnlock()
  294. s.Lock()
  295. defer s.Unlock()
  296. var err error
  297. session, err = s.openSession()
  298. if err != nil {
  299. // This does not look too nice, but QUIC (or maybe quic-go)
  300. // doesn't seem stable enough.
  301. // Maybe retransmissions aren't fully implemented in quic-go?
  302. // Anyways, the simple solution is to make a second try when
  303. // it fails to open the QUIC session.
  304. session, err = s.openSession()
  305. if err != nil {
  306. return nil, err
  307. }
  308. }
  309. s.session = session
  310. return session, nil
  311. }
  312. func (s *QUICNameServer) openSession() (quic.Session, error) {
  313. tlsConfig := tls.Config{}
  314. quicConfig := &quic.Config{
  315. HandshakeTimeout: handshakeTimeout,
  316. }
  317. session, err := quic.DialAddrContext(context.Background(), s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto("http/1.1", http2.NextProtoTLS, NextProtoDQ)), quicConfig)
  318. if err != nil {
  319. return nil, err
  320. }
  321. return session, nil
  322. }
  323. func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
  324. session, err := s.getSession()
  325. if err != nil {
  326. return nil, err
  327. }
  328. // open a new stream
  329. return session.OpenStreamSync(ctx)
  330. }