nameserver_quic.go 10 KB

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