nameserver_quic.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. package dns
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "net/url"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/quic-go/quic-go"
  11. "github.com/xtls/xray-core/common"
  12. "github.com/xtls/xray-core/common/buf"
  13. "github.com/xtls/xray-core/common/errors"
  14. "github.com/xtls/xray-core/common/log"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/common/protocol/dns"
  17. "github.com/xtls/xray-core/common/session"
  18. "github.com/xtls/xray-core/common/signal/pubsub"
  19. "github.com/xtls/xray-core/common/task"
  20. dns_feature "github.com/xtls/xray-core/features/dns"
  21. "github.com/xtls/xray-core/transport/internet/tls"
  22. "golang.org/x/net/dns/dnsmessage"
  23. "golang.org/x/net/http2"
  24. )
  25. // NextProtoDQ - During connection establishment, DNS/QUIC support is indicated
  26. // by selecting the ALPN token "dq" in the crypto handshake.
  27. const NextProtoDQ = "doq"
  28. const handshakeTimeout = time.Second * 8
  29. // QUICNameServer implemented DNS over QUIC
  30. type QUICNameServer struct {
  31. sync.RWMutex
  32. ips map[string]*record
  33. pub *pubsub.Service
  34. cleanup *task.Periodic
  35. reqID uint32
  36. name string
  37. destination *net.Destination
  38. connection quic.Connection
  39. queryStrategy QueryStrategy
  40. }
  41. // NewQUICNameServer creates DNS-over-QUIC client object for local resolving
  42. func NewQUICNameServer(url *url.URL, queryStrategy QueryStrategy) (*QUICNameServer, error) {
  43. errors.LogInfo(context.Background(), "DNS: created Local DNS-over-QUIC client for ", url.String())
  44. var err error
  45. port := net.Port(853)
  46. if url.Port() != "" {
  47. port, err = net.PortFromString(url.Port())
  48. if err != nil {
  49. return nil, err
  50. }
  51. }
  52. dest := net.UDPDestination(net.ParseAddress(url.Hostname()), port)
  53. s := &QUICNameServer{
  54. ips: make(map[string]*record),
  55. pub: pubsub.NewService(),
  56. name: url.String(),
  57. destination: &dest,
  58. queryStrategy: queryStrategy,
  59. }
  60. s.cleanup = &task.Periodic{
  61. Interval: time.Minute,
  62. Execute: s.Cleanup,
  63. }
  64. return s, nil
  65. }
  66. // Name returns client name
  67. func (s *QUICNameServer) Name() string {
  68. return s.name
  69. }
  70. // Cleanup clears expired items from cache
  71. func (s *QUICNameServer) Cleanup() error {
  72. now := time.Now()
  73. s.Lock()
  74. defer s.Unlock()
  75. if len(s.ips) == 0 {
  76. return errors.New("nothing to do. stopping...")
  77. }
  78. for domain, record := range s.ips {
  79. if record.A != nil && record.A.Expire.Before(now) {
  80. record.A = nil
  81. }
  82. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  83. record.AAAA = nil
  84. }
  85. if record.A == nil && record.AAAA == nil {
  86. errors.LogDebug(context.Background(), s.name, " cleanup ", domain)
  87. delete(s.ips, domain)
  88. } else {
  89. s.ips[domain] = record
  90. }
  91. }
  92. if len(s.ips) == 0 {
  93. s.ips = make(map[string]*record)
  94. }
  95. return nil
  96. }
  97. func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  98. elapsed := time.Since(req.start)
  99. s.Lock()
  100. rec, found := s.ips[req.domain]
  101. if !found {
  102. rec = &record{}
  103. }
  104. updated := false
  105. switch req.reqType {
  106. case dnsmessage.TypeA:
  107. if isNewer(rec.A, ipRec) {
  108. rec.A = ipRec
  109. updated = true
  110. }
  111. case dnsmessage.TypeAAAA:
  112. addr := make([]net.Address, 0)
  113. for _, ip := range ipRec.IP {
  114. if len(ip.IP()) == net.IPv6len {
  115. addr = append(addr, ip)
  116. }
  117. }
  118. ipRec.IP = addr
  119. if isNewer(rec.AAAA, ipRec) {
  120. rec.AAAA = ipRec
  121. updated = true
  122. }
  123. }
  124. errors.LogInfo(context.Background(), s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed)
  125. if updated {
  126. s.ips[req.domain] = rec
  127. }
  128. switch req.reqType {
  129. case dnsmessage.TypeA:
  130. s.pub.Publish(req.domain+"4", nil)
  131. case dnsmessage.TypeAAAA:
  132. s.pub.Publish(req.domain+"6", nil)
  133. }
  134. s.Unlock()
  135. common.Must(s.cleanup.Start())
  136. }
  137. func (s *QUICNameServer) newReqID() uint16 {
  138. return uint16(atomic.AddUint32(&s.reqID, 1))
  139. }
  140. func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
  141. errors.LogInfo(ctx, s.name, " querying: ", domain)
  142. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  143. var deadline time.Time
  144. if d, ok := ctx.Deadline(); ok {
  145. deadline = d
  146. } else {
  147. deadline = time.Now().Add(time.Second * 5)
  148. }
  149. for _, req := range reqs {
  150. go func(r *dnsRequest) {
  151. // generate new context for each req, using same context
  152. // may cause reqs all aborted if any one encounter an error
  153. dnsCtx := ctx
  154. // reserve internal dns server requested Inbound
  155. if inbound := session.InboundFromContext(ctx); inbound != nil {
  156. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  157. }
  158. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  159. Protocol: "quic",
  160. SkipDNSResolve: true,
  161. })
  162. var cancel context.CancelFunc
  163. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  164. defer cancel()
  165. b, err := dns.PackMessage(r.msg)
  166. if err != nil {
  167. errors.LogErrorInner(ctx, err, "failed to pack dns query")
  168. return
  169. }
  170. dnsReqBuf := buf.New()
  171. binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len()))
  172. dnsReqBuf.Write(b.Bytes())
  173. b.Release()
  174. conn, err := s.openStream(dnsCtx)
  175. if err != nil {
  176. errors.LogErrorInner(ctx, err, "failed to open quic connection")
  177. return
  178. }
  179. _, err = conn.Write(dnsReqBuf.Bytes())
  180. if err != nil {
  181. errors.LogErrorInner(ctx, err, "failed to send query")
  182. return
  183. }
  184. _ = conn.Close()
  185. respBuf := buf.New()
  186. defer respBuf.Release()
  187. n, err := respBuf.ReadFullFrom(conn, 2)
  188. if err != nil && n == 0 {
  189. errors.LogErrorInner(ctx, err, "failed to read response length")
  190. return
  191. }
  192. var length int16
  193. err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length)
  194. if err != nil {
  195. errors.LogErrorInner(ctx, err, "failed to parse response length")
  196. return
  197. }
  198. respBuf.Clear()
  199. n, err = respBuf.ReadFullFrom(conn, int32(length))
  200. if err != nil && n == 0 {
  201. errors.LogErrorInner(ctx, err, "failed to read response length")
  202. return
  203. }
  204. rec, err := parseResponse(respBuf.Bytes())
  205. if err != nil {
  206. errors.LogErrorInner(ctx, err, "failed to handle response")
  207. return
  208. }
  209. s.updateIP(r, rec)
  210. }(req)
  211. }
  212. }
  213. func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  214. s.RLock()
  215. record, found := s.ips[domain]
  216. s.RUnlock()
  217. if !found {
  218. return nil, errRecordNotFound
  219. }
  220. var err4 error
  221. var err6 error
  222. var ips []net.Address
  223. var ip6 []net.Address
  224. if option.IPv4Enable {
  225. ips, err4 = record.A.getIPs()
  226. }
  227. if option.IPv6Enable {
  228. ip6, err6 = record.AAAA.getIPs()
  229. ips = append(ips, ip6...)
  230. }
  231. if len(ips) > 0 {
  232. return toNetIP(ips)
  233. }
  234. if err4 != nil {
  235. return nil, err4
  236. }
  237. if err6 != nil {
  238. return nil, err6
  239. }
  240. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  241. return nil, dns_feature.ErrEmptyResponse
  242. }
  243. return nil, 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, error) {
  247. fqdn := Fqdn(domain)
  248. option = ResolveIpOptionOverride(s.queryStrategy, option)
  249. if !option.IPv4Enable && !option.IPv6Enable {
  250. return nil, 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, err := s.findIPsForDomain(fqdn, option)
  256. if err != errRecordNotFound {
  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, 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, 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, err
  295. }
  296. select {
  297. case <-ctx.Done():
  298. return nil, 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. }