nameserver_quic.go 8.9 KB

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