nameserver_quic.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. session quic.Session
  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, found := s.ips[req.domain]
  97. if !found {
  98. rec = &record{}
  99. }
  100. updated := false
  101. switch req.reqType {
  102. case dnsmessage.TypeA:
  103. if isNewer(rec.A, ipRec) {
  104. rec.A = ipRec
  105. updated = true
  106. }
  107. case dnsmessage.TypeAAAA:
  108. addr := make([]net.Address, 0)
  109. for _, ip := range ipRec.IP {
  110. if len(ip.IP()) == net.IPv6len {
  111. addr = append(addr, ip)
  112. }
  113. }
  114. ipRec.IP = addr
  115. if isNewer(rec.AAAA, ipRec) {
  116. rec.AAAA = ipRec
  117. updated = true
  118. }
  119. }
  120. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  121. if updated {
  122. s.ips[req.domain] = rec
  123. }
  124. switch req.reqType {
  125. case dnsmessage.TypeA:
  126. s.pub.Publish(req.domain+"4", nil)
  127. case dnsmessage.TypeAAAA:
  128. s.pub.Publish(req.domain+"6", nil)
  129. }
  130. s.Unlock()
  131. common.Must(s.cleanup.Start())
  132. }
  133. func (s *QUICNameServer) newReqID() uint16 {
  134. return uint16(atomic.AddUint32(&s.reqID, 1))
  135. }
  136. func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
  137. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  138. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  139. var deadline time.Time
  140. if d, ok := ctx.Deadline(); ok {
  141. deadline = d
  142. } else {
  143. deadline = time.Now().Add(time.Second * 5)
  144. }
  145. for _, req := range reqs {
  146. go func(r *dnsRequest) {
  147. // generate new context for each req, using same context
  148. // may cause reqs all aborted if any one encounter an error
  149. dnsCtx := ctx
  150. // reserve internal dns server requested Inbound
  151. if inbound := session.InboundFromContext(ctx); inbound != nil {
  152. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  153. }
  154. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  155. Protocol: "quic",
  156. SkipDNSResolve: true,
  157. })
  158. var cancel context.CancelFunc
  159. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  160. defer cancel()
  161. b, err := dns.PackMessage(r.msg)
  162. if err != nil {
  163. newError("failed to pack dns query").Base(err).AtError().WriteToLog()
  164. return
  165. }
  166. conn, err := s.openStream(dnsCtx)
  167. if err != nil {
  168. newError("failed to open quic session").Base(err).AtError().WriteToLog()
  169. return
  170. }
  171. _, err = conn.Write(b.Bytes())
  172. if err != nil {
  173. newError("failed to send query").Base(err).AtError().WriteToLog()
  174. return
  175. }
  176. _ = conn.Close()
  177. respBuf := buf.New()
  178. defer respBuf.Release()
  179. n, err := respBuf.ReadFrom(conn)
  180. if err != nil && n == 0 {
  181. newError("failed to read response").Base(err).AtError().WriteToLog()
  182. return
  183. }
  184. rec, err := parseResponse(respBuf.Bytes())
  185. if err != nil {
  186. newError("failed to handle response").Base(err).AtError().WriteToLog()
  187. return
  188. }
  189. s.updateIP(r, rec)
  190. }(req)
  191. }
  192. }
  193. func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  194. s.RLock()
  195. record, found := s.ips[domain]
  196. s.RUnlock()
  197. if !found {
  198. return nil, errRecordNotFound
  199. }
  200. var err4 error
  201. var err6 error
  202. var ips []net.Address
  203. var ip6 []net.Address
  204. switch {
  205. case option.IPv4Enable:
  206. ips, err4 = record.A.getIPs()
  207. fallthrough
  208. case option.IPv6Enable:
  209. ip6, err6 = record.AAAA.getIPs()
  210. ips = append(ips, ip6...)
  211. }
  212. if len(ips) > 0 {
  213. return toNetIP(ips)
  214. }
  215. if err4 != nil {
  216. return nil, err4
  217. }
  218. if err6 != nil {
  219. return nil, err6
  220. }
  221. return nil, errRecordNotFound
  222. }
  223. // QueryIP is called from dns.Server->queryIPTimeout
  224. func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) {
  225. fqdn := Fqdn(domain)
  226. if disableCache {
  227. newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog()
  228. } else {
  229. ips, err := s.findIPsForDomain(fqdn, option)
  230. if err != errRecordNotFound {
  231. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  232. return ips, err
  233. }
  234. }
  235. // ipv4 and ipv6 belong to different subscription groups
  236. var sub4, sub6 *pubsub.Subscriber
  237. if option.IPv4Enable {
  238. sub4 = s.pub.Subscribe(fqdn + "4")
  239. defer sub4.Close()
  240. }
  241. if option.IPv6Enable {
  242. sub6 = s.pub.Subscribe(fqdn + "6")
  243. defer sub6.Close()
  244. }
  245. done := make(chan interface{})
  246. go func() {
  247. if sub4 != nil {
  248. select {
  249. case <-sub4.Wait():
  250. case <-ctx.Done():
  251. }
  252. }
  253. if sub6 != nil {
  254. select {
  255. case <-sub6.Wait():
  256. case <-ctx.Done():
  257. }
  258. }
  259. close(done)
  260. }()
  261. s.sendQuery(ctx, fqdn, clientIP, option)
  262. for {
  263. ips, err := s.findIPsForDomain(fqdn, option)
  264. if err != errRecordNotFound {
  265. return ips, err
  266. }
  267. select {
  268. case <-ctx.Done():
  269. return nil, ctx.Err()
  270. case <-done:
  271. }
  272. }
  273. }
  274. func isActive(s quic.Session) bool {
  275. select {
  276. case <-s.Context().Done():
  277. return false
  278. default:
  279. return true
  280. }
  281. }
  282. func (s *QUICNameServer) getSession(ctx context.Context) (quic.Session, error) {
  283. var session quic.Session
  284. s.RLock()
  285. session = s.session
  286. if session != nil && isActive(session) {
  287. s.RUnlock()
  288. return session, nil
  289. }
  290. if session != nil {
  291. // we're recreating the session, let's create a new one
  292. _ = session.CloseWithError(0, "")
  293. }
  294. s.RUnlock()
  295. s.Lock()
  296. defer s.Unlock()
  297. var err error
  298. session, err = s.openSession(ctx)
  299. if err != nil {
  300. // This does not look too nice, but QUIC (or maybe quic-go)
  301. // doesn't seem stable enough.
  302. // Maybe retransmissions aren't fully implemented in quic-go?
  303. // Anyways, the simple solution is to make a second try when
  304. // it fails to open the QUIC session.
  305. session, err = s.openSession(ctx)
  306. if err != nil {
  307. return nil, err
  308. }
  309. }
  310. s.session = session
  311. return session, nil
  312. }
  313. func (s *QUICNameServer) openSession(ctx context.Context) (quic.Session, error) {
  314. tlsConfig := tls.Config{}
  315. quicConfig := &quic.Config{
  316. HandshakeIdleTimeout: handshakeIdleTimeout,
  317. }
  318. session, err := quic.DialAddrContext(ctx, s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto("http/1.1", http2.NextProtoTLS, NextProtoDQ)), quicConfig)
  319. if err != nil {
  320. return nil, err
  321. }
  322. return session, nil
  323. }
  324. func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
  325. session, err := s.getSession(ctx)
  326. if err != nil {
  327. return nil, err
  328. }
  329. // open a new stream
  330. return session.OpenStreamSync(ctx)
  331. }