nameserver_quic.go 8.8 KB

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