nameserver_quic.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package dns
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. go_errors "errors"
  7. "net/url"
  8. "sync"
  9. "time"
  10. "github.com/quic-go/quic-go"
  11. "github.com/xtls/xray-core/common/buf"
  12. "github.com/xtls/xray-core/common/errors"
  13. "github.com/xtls/xray-core/common/log"
  14. "github.com/xtls/xray-core/common/net"
  15. "github.com/xtls/xray-core/common/protocol/dns"
  16. "github.com/xtls/xray-core/common/session"
  17. dns_feature "github.com/xtls/xray-core/features/dns"
  18. "github.com/xtls/xray-core/transport/internet/tls"
  19. "golang.org/x/net/http2"
  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"
  24. const handshakeTimeout = time.Second * 8
  25. // QUICNameServer implemented DNS over QUIC
  26. type QUICNameServer struct {
  27. sync.RWMutex
  28. cacheController *CacheController
  29. destination *net.Destination
  30. connection *quic.Conn
  31. clientIP net.IP
  32. }
  33. // NewQUICNameServer creates DNS-over-QUIC client object for local resolving
  34. func NewQUICNameServer(url *url.URL, disableCache bool, serveStale bool, serveExpiredTTL uint32, clientIP net.IP) (*QUICNameServer, error) {
  35. errors.LogInfo(context.Background(), "DNS: created Local DNS-over-QUIC client for ", url.String())
  36. var err error
  37. port := net.Port(853)
  38. if url.Port() != "" {
  39. port, err = net.PortFromString(url.Port())
  40. if err != nil {
  41. return nil, err
  42. }
  43. }
  44. dest := net.UDPDestination(net.ParseAddress(url.Hostname()), port)
  45. s := &QUICNameServer{
  46. cacheController: NewCacheController(url.String(), disableCache, serveStale, serveExpiredTTL),
  47. destination: &dest,
  48. clientIP: clientIP,
  49. }
  50. return s, nil
  51. }
  52. // Name returns client name
  53. func (s *QUICNameServer) Name() string {
  54. return s.cacheController.name
  55. }
  56. func (s *QUICNameServer) newReqID() uint16 {
  57. return 0
  58. }
  59. func (s *QUICNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- error, domain string, option dns_feature.IPOption) {
  60. errors.LogInfo(ctx, s.Name(), " querying: ", domain)
  61. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(s.clientIP, 0))
  62. var deadline time.Time
  63. if d, ok := ctx.Deadline(); ok {
  64. deadline = d
  65. } else {
  66. deadline = time.Now().Add(time.Second * 5)
  67. }
  68. for _, req := range reqs {
  69. go func(r *dnsRequest) {
  70. // generate new context for each req, using same context
  71. // may cause reqs all aborted if any one encounter an error
  72. dnsCtx := ctx
  73. // reserve internal dns server requested Inbound
  74. if inbound := session.InboundFromContext(ctx); inbound != nil {
  75. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  76. }
  77. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  78. Protocol: "quic",
  79. SkipDNSResolve: true,
  80. })
  81. var cancel context.CancelFunc
  82. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  83. defer cancel()
  84. b, err := dns.PackMessage(r.msg)
  85. if err != nil {
  86. errors.LogErrorInner(ctx, err, "failed to pack dns query")
  87. if noResponseErrCh != nil {
  88. noResponseErrCh <- err
  89. }
  90. return
  91. }
  92. dnsReqBuf := buf.New()
  93. err = binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len()))
  94. if err != nil {
  95. errors.LogErrorInner(ctx, err, "binary write failed")
  96. if noResponseErrCh != nil {
  97. noResponseErrCh <- err
  98. }
  99. return
  100. }
  101. _, err = dnsReqBuf.Write(b.Bytes())
  102. if err != nil {
  103. errors.LogErrorInner(ctx, err, "buffer write failed")
  104. if noResponseErrCh != nil {
  105. noResponseErrCh <- err
  106. }
  107. return
  108. }
  109. b.Release()
  110. conn, err := s.openStream(dnsCtx)
  111. if err != nil {
  112. errors.LogErrorInner(ctx, err, "failed to open quic connection")
  113. if noResponseErrCh != nil {
  114. noResponseErrCh <- err
  115. }
  116. return
  117. }
  118. _, err = conn.Write(dnsReqBuf.Bytes())
  119. if err != nil {
  120. errors.LogErrorInner(ctx, err, "failed to send query")
  121. if noResponseErrCh != nil {
  122. noResponseErrCh <- err
  123. }
  124. return
  125. }
  126. _ = conn.Close()
  127. respBuf := buf.New()
  128. defer respBuf.Release()
  129. n, err := respBuf.ReadFullFrom(conn, 2)
  130. if err != nil && n == 0 {
  131. errors.LogErrorInner(ctx, err, "failed to read response length")
  132. if noResponseErrCh != nil {
  133. noResponseErrCh <- err
  134. }
  135. return
  136. }
  137. var length int16
  138. err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length)
  139. if err != nil {
  140. errors.LogErrorInner(ctx, err, "failed to parse response length")
  141. if noResponseErrCh != nil {
  142. noResponseErrCh <- err
  143. }
  144. return
  145. }
  146. respBuf.Clear()
  147. n, err = respBuf.ReadFullFrom(conn, int32(length))
  148. if err != nil && n == 0 {
  149. errors.LogErrorInner(ctx, err, "failed to read response length")
  150. if noResponseErrCh != nil {
  151. noResponseErrCh <- err
  152. }
  153. return
  154. }
  155. rec, err := parseResponse(respBuf.Bytes())
  156. if err != nil {
  157. errors.LogErrorInner(ctx, err, "failed to handle response")
  158. if noResponseErrCh != nil {
  159. noResponseErrCh <- err
  160. }
  161. return
  162. }
  163. s.cacheController.updateIP(r, rec)
  164. }(req)
  165. }
  166. }
  167. // QueryIP is called from dns.Server->queryIPTimeout
  168. func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, option dns_feature.IPOption) ([]net.IP, uint32, error) {
  169. fqdn := Fqdn(domain)
  170. sub4, sub6 := s.cacheController.registerSubscribers(fqdn, option)
  171. defer closeSubscribers(sub4, sub6)
  172. queryOption := option
  173. if s.cacheController.disableCache {
  174. errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.Name())
  175. } else {
  176. ips, ttl, isARecordExpired, isAAAARecordExpired, err := s.cacheController.findIPsForDomain(fqdn, option)
  177. if sub4 != nil && !isARecordExpired {
  178. sub4.Close()
  179. sub4 = nil
  180. queryOption.IPv4Enable = false
  181. }
  182. if sub6 != nil && !isAAAARecordExpired {
  183. sub6.Close()
  184. sub6 = nil
  185. queryOption.IPv6Enable = false
  186. }
  187. if !go_errors.Is(err, errRecordNotFound) {
  188. if ttl > 0 {
  189. errors.LogDebugInner(ctx, err, s.Name(), " cache HIT ", domain, " -> ", ips)
  190. log.Record(&log.DNSLog{Server: s.Name(), Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
  191. return ips, uint32(ttl), err
  192. }
  193. if s.cacheController.serveStale && (s.cacheController.serveExpiredTTL == 0 || s.cacheController.serveExpiredTTL < ttl) {
  194. errors.LogDebugInner(ctx, err, s.Name(), " cache OPTIMISTE ", domain, " -> ", ips)
  195. s.sendQuery(ctx, nil, fqdn, queryOption)
  196. return ips, 1, err
  197. }
  198. }
  199. }
  200. noResponseErrCh := make(chan error, 2)
  201. s.sendQuery(ctx, noResponseErrCh, fqdn, queryOption)
  202. start := time.Now()
  203. if sub4 != nil {
  204. select {
  205. case <-ctx.Done():
  206. return nil, 0, ctx.Err()
  207. case err := <-noResponseErrCh:
  208. return nil, 0, err
  209. case <-sub4.Wait():
  210. sub4.Close()
  211. }
  212. }
  213. if sub6 != nil {
  214. select {
  215. case <-ctx.Done():
  216. return nil, 0, ctx.Err()
  217. case err := <-noResponseErrCh:
  218. return nil, 0, err
  219. case <-sub6.Wait():
  220. sub6.Close()
  221. }
  222. }
  223. ips, ttl, _, _, err := s.cacheController.findIPsForDomain(fqdn, option)
  224. log.Record(&log.DNSLog{Server: s.Name(), Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
  225. var rTTL uint32
  226. if ttl <= 0 {
  227. rTTL = 1
  228. } else {
  229. rTTL = uint32(ttl)
  230. }
  231. return ips, rTTL, err
  232. }
  233. func isActive(s *quic.Conn) bool {
  234. select {
  235. case <-s.Context().Done():
  236. return false
  237. default:
  238. return true
  239. }
  240. }
  241. func (s *QUICNameServer) getConnection() (*quic.Conn, error) {
  242. var conn *quic.Conn
  243. s.RLock()
  244. conn = s.connection
  245. if conn != nil && isActive(conn) {
  246. s.RUnlock()
  247. return conn, nil
  248. }
  249. if conn != nil {
  250. // we're recreating the connection, let's create a new one
  251. _ = conn.CloseWithError(0, "")
  252. }
  253. s.RUnlock()
  254. s.Lock()
  255. defer s.Unlock()
  256. var err error
  257. conn, err = s.openConnection()
  258. if err != nil {
  259. // This does not look too nice, but QUIC (or maybe quic-go)
  260. // doesn't seem stable enough.
  261. // Maybe retransmissions aren't fully implemented in quic-go?
  262. // Anyways, the simple solution is to make a second try when
  263. // it fails to open the QUIC connection.
  264. conn, err = s.openConnection()
  265. if err != nil {
  266. return nil, err
  267. }
  268. }
  269. s.connection = conn
  270. return conn, nil
  271. }
  272. func (s *QUICNameServer) openConnection() (*quic.Conn, error) {
  273. tlsConfig := tls.Config{}
  274. quicConfig := &quic.Config{
  275. HandshakeIdleTimeout: handshakeTimeout,
  276. }
  277. tlsConfig.ServerName = s.destination.Address.String()
  278. conn, err := quic.DialAddr(context.Background(), s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto("http/1.1", http2.NextProtoTLS, NextProtoDQ)), quicConfig)
  279. log.Record(&log.AccessMessage{
  280. From: "DNS",
  281. To: s.destination,
  282. Status: log.AccessAccepted,
  283. Detour: "local",
  284. })
  285. if err != nil {
  286. return nil, err
  287. }
  288. return conn, nil
  289. }
  290. func (s *QUICNameServer) openStream(ctx context.Context) (*quic.Stream, error) {
  291. conn, err := s.getConnection()
  292. if err != nil {
  293. return nil, err
  294. }
  295. // open a new stream
  296. return conn.OpenStreamSync(ctx)
  297. }