nameserver_quic.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. // +build !confonly
  2. package dns
  3. import (
  4. "context"
  5. "net/url"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. core "github.com/v2fly/v2ray-core/v4"
  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.DomainAddress(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 session").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 ips []net.Address
  198. var lastErr error
  199. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  200. aaaa, err := record.AAAA.getIPs()
  201. if err != nil {
  202. lastErr = err
  203. }
  204. ips = append(ips, aaaa...)
  205. }
  206. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  207. a, err := record.A.getIPs()
  208. if err != nil {
  209. lastErr = err
  210. }
  211. ips = append(ips, a...)
  212. }
  213. if len(ips) > 0 {
  214. return toNetIP(ips)
  215. }
  216. if lastErr != nil {
  217. return nil, lastErr
  218. }
  219. if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
  220. return nil, dns_feature.ErrEmptyResponse
  221. }
  222. return nil, errRecordNotFound
  223. }
  224. // QueryIP is called from dns.Server->queryIPTimeout
  225. func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) {
  226. fqdn := Fqdn(domain)
  227. if disableCache {
  228. newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog()
  229. } else {
  230. ips, err := s.findIPsForDomain(fqdn, option)
  231. if err != errRecordNotFound {
  232. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  233. return ips, err
  234. }
  235. }
  236. // ipv4 and ipv6 belong to different subscription groups
  237. var sub4, sub6 *pubsub.Subscriber
  238. if option.IPv4Enable {
  239. sub4 = s.pub.Subscribe(fqdn + "4")
  240. defer sub4.Close()
  241. }
  242. if option.IPv6Enable {
  243. sub6 = s.pub.Subscribe(fqdn + "6")
  244. defer sub6.Close()
  245. }
  246. done := make(chan interface{})
  247. go func() {
  248. if sub4 != nil {
  249. select {
  250. case <-sub4.Wait():
  251. case <-ctx.Done():
  252. }
  253. }
  254. if sub6 != nil {
  255. select {
  256. case <-sub6.Wait():
  257. case <-ctx.Done():
  258. }
  259. }
  260. close(done)
  261. }()
  262. s.sendQuery(ctx, fqdn, clientIP, option)
  263. for {
  264. ips, err := s.findIPsForDomain(fqdn, option)
  265. if err != errRecordNotFound {
  266. return ips, err
  267. }
  268. select {
  269. case <-ctx.Done():
  270. return nil, ctx.Err()
  271. case <-done:
  272. }
  273. }
  274. }
  275. func isActive(s quic.Session) bool {
  276. select {
  277. case <-s.Context().Done():
  278. return false
  279. default:
  280. return true
  281. }
  282. }
  283. func (s *QUICNameServer) getSession(ctx context.Context) (quic.Session, error) {
  284. var session quic.Session
  285. s.RLock()
  286. session = s.session
  287. if session != nil && isActive(session) {
  288. s.RUnlock()
  289. return session, nil
  290. }
  291. if session != nil {
  292. // we're recreating the session, let's create a new one
  293. _ = session.CloseWithError(0, "")
  294. }
  295. s.RUnlock()
  296. s.Lock()
  297. defer s.Unlock()
  298. var err error
  299. session, err = s.openSession(ctx)
  300. if err != nil {
  301. // This does not look too nice, but QUIC (or maybe quic-go)
  302. // doesn't seem stable enough.
  303. // Maybe retransmissions aren't fully implemented in quic-go?
  304. // Anyways, the simple solution is to make a second try when
  305. // it fails to open the QUIC session.
  306. session, err = s.openSession(ctx)
  307. if err != nil {
  308. return nil, err
  309. }
  310. }
  311. s.session = session
  312. return session, nil
  313. }
  314. func (s *QUICNameServer) openSession(ctx context.Context) (quic.Session, error) {
  315. tlsConfig := tls.Config{}
  316. quicConfig := &quic.Config{
  317. HandshakeIdleTimeout: handshakeIdleTimeout,
  318. }
  319. session, err := quic.DialAddrContext(core.ToBackgroundDetachedContext(ctx), s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto("http/1.1", http2.NextProtoTLS, NextProtoDQ)), quicConfig)
  320. if err != nil {
  321. return nil, err
  322. }
  323. return session, nil
  324. }
  325. func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
  326. session, err := s.getSession(ctx)
  327. if err != nil {
  328. return nil, err
  329. }
  330. // open a new stream
  331. return session.OpenStreamSync(ctx)
  332. }