nameserver_quic.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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/v4/common"
  12. "github.com/v2fly/v2ray-core/v4/common/buf"
  13. "github.com/v2fly/v2ray-core/v4/common/net"
  14. "github.com/v2fly/v2ray-core/v4/common/protocol/dns"
  15. "github.com/v2fly/v2ray-core/v4/common/session"
  16. "github.com/v2fly/v2ray-core/v4/common/signal/pubsub"
  17. "github.com/v2fly/v2ray-core/v4/common/task"
  18. dns_feature "github.com/v2fly/v2ray-core/v4/features/dns"
  19. "github.com/v2fly/v2ray-core/v4/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. session quic.Session
  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(784)
  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, found := s.ips[req.domain]
  95. if !found {
  96. rec = &record{}
  97. }
  98. updated := false
  99. switch req.reqType {
  100. case dnsmessage.TypeA:
  101. if isNewer(rec.A, ipRec) {
  102. rec.A = ipRec
  103. updated = true
  104. }
  105. case dnsmessage.TypeAAAA:
  106. addr := make([]net.Address, 0)
  107. for _, ip := range ipRec.IP {
  108. if len(ip.IP()) == net.IPv6len {
  109. addr = append(addr, ip)
  110. }
  111. }
  112. ipRec.IP = addr
  113. if isNewer(rec.AAAA, ipRec) {
  114. rec.AAAA = ipRec
  115. updated = true
  116. }
  117. }
  118. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  119. if updated {
  120. s.ips[req.domain] = rec
  121. }
  122. switch req.reqType {
  123. case dnsmessage.TypeA:
  124. s.pub.Publish(req.domain+"4", nil)
  125. case dnsmessage.TypeAAAA:
  126. s.pub.Publish(req.domain+"6", nil)
  127. }
  128. s.Unlock()
  129. common.Must(s.cleanup.Start())
  130. }
  131. func (s *QUICNameServer) newReqID() uint16 {
  132. return uint16(atomic.AddUint32(&s.reqID, 1))
  133. }
  134. func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
  135. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  136. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  137. var deadline time.Time
  138. if d, ok := ctx.Deadline(); ok {
  139. deadline = d
  140. } else {
  141. deadline = time.Now().Add(time.Second * 5)
  142. }
  143. for _, req := range reqs {
  144. go func(r *dnsRequest) {
  145. // generate new context for each req, using same context
  146. // may cause reqs all aborted if any one encounter an error
  147. dnsCtx := ctx
  148. // reserve internal dns server requested Inbound
  149. if inbound := session.InboundFromContext(ctx); inbound != nil {
  150. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  151. }
  152. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  153. Protocol: "quic",
  154. SkipDNSResolve: true,
  155. })
  156. var cancel context.CancelFunc
  157. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  158. defer cancel()
  159. b, err := dns.PackMessage(r.msg)
  160. if err != nil {
  161. newError("failed to pack dns query").Base(err).AtError().WriteToLog()
  162. return
  163. }
  164. conn, err := s.openStream(dnsCtx)
  165. if err != nil {
  166. newError("failed to open quic session").Base(err).AtError().WriteToLog()
  167. return
  168. }
  169. _, err = conn.Write(b.Bytes())
  170. if err != nil {
  171. newError("failed to send query").Base(err).AtError().WriteToLog()
  172. return
  173. }
  174. _ = conn.Close()
  175. respBuf := buf.New()
  176. defer respBuf.Release()
  177. n, err := respBuf.ReadFrom(conn)
  178. if err != nil && n == 0 {
  179. newError("failed to read response").Base(err).AtError().WriteToLog()
  180. return
  181. }
  182. rec, err := parseResponse(respBuf.Bytes())
  183. if err != nil {
  184. newError("failed to handle response").Base(err).AtError().WriteToLog()
  185. return
  186. }
  187. s.updateIP(r, rec)
  188. }(req)
  189. }
  190. }
  191. func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  192. s.RLock()
  193. record, found := s.ips[domain]
  194. s.RUnlock()
  195. if !found {
  196. return nil, errRecordNotFound
  197. }
  198. var err4 error
  199. var err6 error
  200. var ips []net.Address
  201. var ip6 []net.Address
  202. if option.IPv4Enable {
  203. ips, err4 = record.A.getIPs()
  204. }
  205. if option.IPv6Enable {
  206. ip6, err6 = record.AAAA.getIPs()
  207. ips = append(ips, ip6...)
  208. }
  209. if len(ips) > 0 {
  210. return toNetIP(ips)
  211. }
  212. if err4 != nil {
  213. return nil, err4
  214. }
  215. if err6 != nil {
  216. return nil, err6
  217. }
  218. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  219. return nil, dns_feature.ErrEmptyResponse
  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. }