nameserver_quic.go 9.2 KB

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