nameserver_quic.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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, 0))
  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, uint32, error) {
  212. s.RLock()
  213. record, found := s.ips[domain]
  214. s.RUnlock()
  215. if !found {
  216. return nil, 0, errRecordNotFound
  217. }
  218. var err4 error
  219. var err6 error
  220. var ips []net.Address
  221. var ip6 []net.Address
  222. var ttl uint32
  223. if option.IPv4Enable {
  224. ips, ttl, err4 = record.A.getIPs()
  225. }
  226. if option.IPv6Enable {
  227. ip6, ttl, err6 = record.AAAA.getIPs()
  228. ips = append(ips, ip6...)
  229. }
  230. if len(ips) > 0 {
  231. netips, err := toNetIP(ips)
  232. return netips, ttl, err
  233. }
  234. if err4 != nil {
  235. return nil, 0, err4
  236. }
  237. if err6 != nil {
  238. return nil, 0, err6
  239. }
  240. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  241. return nil, 0, dns_feature.ErrEmptyResponse
  242. }
  243. return nil, 0, errRecordNotFound
  244. }
  245. // QueryIP is called from dns.Server->queryIPTimeout
  246. func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, uint32, error) {
  247. fqdn := Fqdn(domain)
  248. option = ResolveIpOptionOverride(s.queryStrategy, option)
  249. if !option.IPv4Enable && !option.IPv6Enable {
  250. return nil, 0, dns_feature.ErrEmptyResponse
  251. }
  252. if disableCache {
  253. errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name)
  254. } else {
  255. ips, ttl, err := s.findIPsForDomain(fqdn, option)
  256. if err == nil || err == dns_feature.ErrEmptyResponse {
  257. errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips)
  258. log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
  259. return ips, ttl, err
  260. }
  261. }
  262. // ipv4 and ipv6 belong to different subscription groups
  263. var sub4, sub6 *pubsub.Subscriber
  264. if option.IPv4Enable {
  265. sub4 = s.pub.Subscribe(fqdn + "4")
  266. defer sub4.Close()
  267. }
  268. if option.IPv6Enable {
  269. sub6 = s.pub.Subscribe(fqdn + "6")
  270. defer sub6.Close()
  271. }
  272. done := make(chan interface{})
  273. go func() {
  274. if sub4 != nil {
  275. select {
  276. case <-sub4.Wait():
  277. case <-ctx.Done():
  278. }
  279. }
  280. if sub6 != nil {
  281. select {
  282. case <-sub6.Wait():
  283. case <-ctx.Done():
  284. }
  285. }
  286. close(done)
  287. }()
  288. s.sendQuery(ctx, fqdn, clientIP, option)
  289. start := time.Now()
  290. for {
  291. ips, ttl, err := s.findIPsForDomain(fqdn, option)
  292. if err != errRecordNotFound {
  293. log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
  294. return ips, ttl, err
  295. }
  296. select {
  297. case <-ctx.Done():
  298. return nil, 0, ctx.Err()
  299. case <-done:
  300. }
  301. }
  302. }
  303. func isActive(s quic.Connection) bool {
  304. select {
  305. case <-s.Context().Done():
  306. return false
  307. default:
  308. return true
  309. }
  310. }
  311. func (s *QUICNameServer) getConnection() (quic.Connection, error) {
  312. var conn quic.Connection
  313. s.RLock()
  314. conn = s.connection
  315. if conn != nil && isActive(conn) {
  316. s.RUnlock()
  317. return conn, nil
  318. }
  319. if conn != nil {
  320. // we're recreating the connection, let's create a new one
  321. _ = conn.CloseWithError(0, "")
  322. }
  323. s.RUnlock()
  324. s.Lock()
  325. defer s.Unlock()
  326. var err error
  327. conn, err = s.openConnection()
  328. if err != nil {
  329. // This does not look too nice, but QUIC (or maybe quic-go)
  330. // doesn't seem stable enough.
  331. // Maybe retransmissions aren't fully implemented in quic-go?
  332. // Anyways, the simple solution is to make a second try when
  333. // it fails to open the QUIC connection.
  334. conn, err = s.openConnection()
  335. if err != nil {
  336. return nil, err
  337. }
  338. }
  339. s.connection = conn
  340. return conn, nil
  341. }
  342. func (s *QUICNameServer) openConnection() (quic.Connection, error) {
  343. tlsConfig := tls.Config{}
  344. quicConfig := &quic.Config{
  345. HandshakeIdleTimeout: handshakeTimeout,
  346. }
  347. tlsConfig.ServerName = s.destination.Address.String()
  348. conn, err := quic.DialAddr(context.Background(), s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto("http/1.1", http2.NextProtoTLS, NextProtoDQ)), quicConfig)
  349. log.Record(&log.AccessMessage{
  350. From: "DNS",
  351. To: s.destination,
  352. Status: log.AccessAccepted,
  353. Detour: "local",
  354. })
  355. if err != nil {
  356. return nil, err
  357. }
  358. return conn, nil
  359. }
  360. func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
  361. conn, err := s.getConnection()
  362. if err != nil {
  363. return nil, err
  364. }
  365. // open a new stream
  366. return conn.OpenStreamSync(ctx)
  367. }