nameserver_quic.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // +build !confonly
  2. package dns
  3. import (
  4. "context"
  5. "net/url"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/lucas-clemente/quic-go"
  10. "golang.org/x/net/dns/dnsmessage"
  11. "golang.org/x/net/http2"
  12. "github.com/v2fly/v2ray-core/v4/common"
  13. "github.com/v2fly/v2ray-core/v4/common/buf"
  14. "github.com/v2fly/v2ray-core/v4/common/net"
  15. "github.com/v2fly/v2ray-core/v4/common/protocol/dns"
  16. "github.com/v2fly/v2ray-core/v4/common/session"
  17. "github.com/v2fly/v2ray-core/v4/common/signal/pubsub"
  18. "github.com/v2fly/v2ray-core/v4/common/task"
  19. dns_feature "github.com/v2fly/v2ray-core/v4/features/dns"
  20. "github.com/v2fly/v2ray-core/v4/transport/internet/tls"
  21. )
  22. // NextProtoDQ - During connection establishment, DNS/QUIC support is indicated
  23. // by selecting the ALPN token "dq" in the crypto handshake.
  24. const NextProtoDQ = "doq-i00"
  25. const handshakeTimeout = time.Second * 8
  26. // QUICNameServer implemented DNS over QUIC
  27. type QUICNameServer struct {
  28. sync.RWMutex
  29. ips map[string]record
  30. pub *pubsub.Service
  31. cleanup *task.Periodic
  32. reqID uint32
  33. name string
  34. destination net.Destination
  35. session quic.Session
  36. }
  37. // NewQUICNameServer creates DNS-over-QUIC client object for local resolving
  38. func NewQUICNameServer(url *url.URL) (*QUICNameServer, error) {
  39. newError("DNS: created Local DNS-over-QUIC client for ", url.String()).AtInfo().WriteToLog()
  40. var err error
  41. port := net.Port(784)
  42. if url.Port() != "" {
  43. port, err = net.PortFromString(url.Port())
  44. if err != nil {
  45. return nil, err
  46. }
  47. }
  48. dest := net.UDPDestination(net.DomainAddress(url.Hostname()), port)
  49. s := &QUICNameServer{
  50. ips: make(map[string]record),
  51. pub: pubsub.NewService(),
  52. name: url.String(),
  53. destination: dest,
  54. }
  55. s.cleanup = &task.Periodic{
  56. Interval: time.Minute,
  57. Execute: s.Cleanup,
  58. }
  59. return s, nil
  60. }
  61. // Name returns client name
  62. func (s *QUICNameServer) Name() string {
  63. return s.name
  64. }
  65. // Cleanup clears expired items from cache
  66. func (s *QUICNameServer) Cleanup() error {
  67. now := time.Now()
  68. s.Lock()
  69. defer s.Unlock()
  70. if len(s.ips) == 0 {
  71. return newError("nothing to do. stopping...")
  72. }
  73. for domain, record := range s.ips {
  74. if record.A != nil && record.A.Expire.Before(now) {
  75. record.A = nil
  76. }
  77. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  78. record.AAAA = nil
  79. }
  80. if record.A == nil && record.AAAA == nil {
  81. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  82. delete(s.ips, domain)
  83. } else {
  84. s.ips[domain] = record
  85. }
  86. }
  87. if len(s.ips) == 0 {
  88. s.ips = make(map[string]record)
  89. }
  90. return nil
  91. }
  92. func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  93. elapsed := time.Since(req.start)
  94. s.Lock()
  95. rec := s.ips[req.domain]
  96. updated := false
  97. switch req.reqType {
  98. case dnsmessage.TypeA:
  99. if isNewer(rec.A, ipRec) {
  100. rec.A = ipRec
  101. updated = true
  102. }
  103. case dnsmessage.TypeAAAA:
  104. addr := make([]net.Address, 0)
  105. for _, ip := range ipRec.IP {
  106. if len(ip.IP()) == net.IPv6len {
  107. addr = append(addr, ip)
  108. }
  109. }
  110. ipRec.IP = addr
  111. if isNewer(rec.AAAA, ipRec) {
  112. rec.AAAA = ipRec
  113. updated = true
  114. }
  115. }
  116. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  117. if updated {
  118. s.ips[req.domain] = rec
  119. }
  120. switch req.reqType {
  121. case dnsmessage.TypeA:
  122. s.pub.Publish(req.domain+"4", nil)
  123. case dnsmessage.TypeAAAA:
  124. s.pub.Publish(req.domain+"6", nil)
  125. }
  126. s.Unlock()
  127. common.Must(s.cleanup.Start())
  128. }
  129. func (s *QUICNameServer) newReqID() uint16 {
  130. return uint16(atomic.AddUint32(&s.reqID, 1))
  131. }
  132. func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option IPOption) {
  133. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  134. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  135. var deadline time.Time
  136. if d, ok := ctx.Deadline(); ok {
  137. deadline = d
  138. } else {
  139. deadline = time.Now().Add(time.Second * 5)
  140. }
  141. for _, req := range reqs {
  142. go func(r *dnsRequest) {
  143. // generate new context for each req, using same context
  144. // may cause reqs all aborted if any one encounter an error
  145. dnsCtx := context.Background()
  146. // reserve internal dns server requested Inbound
  147. if inbound := session.InboundFromContext(ctx); inbound != nil {
  148. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  149. }
  150. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  151. Protocol: "quic",
  152. SkipDNSResolve: true,
  153. })
  154. var cancel context.CancelFunc
  155. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  156. defer cancel()
  157. b, err := dns.PackMessage(r.msg)
  158. if err != nil {
  159. newError("failed to pack dns query").Base(err).AtError().WriteToLog()
  160. return
  161. }
  162. conn, err := s.openStream(dnsCtx)
  163. if err != nil {
  164. newError("failed to open quic session").Base(err).AtError().WriteToLog()
  165. return
  166. }
  167. _, err = conn.Write(b.Bytes())
  168. if err != nil {
  169. newError("failed to send query").Base(err).AtError().WriteToLog()
  170. return
  171. }
  172. _ = conn.Close()
  173. respBuf := buf.New()
  174. defer respBuf.Release()
  175. n, err := respBuf.ReadFrom(conn)
  176. if err != nil && n == 0 {
  177. newError("failed to read response").Base(err).AtError().WriteToLog()
  178. return
  179. }
  180. rec, err := parseResponse(respBuf.Bytes())
  181. if err != nil {
  182. newError("failed to handle response").Base(err).AtError().WriteToLog()
  183. return
  184. }
  185. s.updateIP(r, rec)
  186. }(req)
  187. }
  188. }
  189. func (s *QUICNameServer) findIPsForDomain(domain string, option IPOption) ([]net.IP, error) {
  190. s.RLock()
  191. record, found := s.ips[domain]
  192. s.RUnlock()
  193. if !found {
  194. return nil, errRecordNotFound
  195. }
  196. var ips []net.Address
  197. var lastErr error
  198. if option.IPv6Enable && record.AAAA != nil && record.AAAA.RCode == dnsmessage.RCodeSuccess {
  199. aaaa, err := record.AAAA.getIPs()
  200. if err != nil {
  201. lastErr = err
  202. }
  203. ips = append(ips, aaaa...)
  204. }
  205. if option.IPv4Enable && record.A != nil && record.A.RCode == dnsmessage.RCodeSuccess {
  206. a, err := record.A.getIPs()
  207. if err != nil {
  208. lastErr = err
  209. }
  210. ips = append(ips, a...)
  211. }
  212. if len(ips) > 0 {
  213. return toNetIP(ips)
  214. }
  215. if lastErr != nil {
  216. return nil, lastErr
  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 IPOption) ([]net.IP, error) {
  225. fqdn := Fqdn(domain)
  226. ips, err := s.findIPsForDomain(fqdn, option)
  227. if err != errRecordNotFound {
  228. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  229. return ips, err
  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.Session) bool {
  271. select {
  272. case <-s.Context().Done():
  273. return false
  274. default:
  275. return true
  276. }
  277. }
  278. func (s *QUICNameServer) getSession() (quic.Session, error) {
  279. var session quic.Session
  280. s.RLock()
  281. session = s.session
  282. if session != nil && isActive(session) {
  283. s.RUnlock()
  284. return session, nil
  285. }
  286. if session != nil {
  287. // we're recreating the session, let's create a new one
  288. _ = session.CloseWithError(0, "")
  289. }
  290. s.RUnlock()
  291. s.Lock()
  292. defer s.Unlock()
  293. var err error
  294. session, err = s.openSession()
  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 session.
  301. session, err = s.openSession()
  302. if err != nil {
  303. return nil, err
  304. }
  305. }
  306. s.session = session
  307. return session, nil
  308. }
  309. func (s *QUICNameServer) openSession() (quic.Session, error) {
  310. tlsConfig := tls.Config{}
  311. quicConfig := &quic.Config{
  312. HandshakeTimeout: handshakeTimeout,
  313. }
  314. session, err := quic.DialAddrContext(context.Background(), 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 session, nil
  319. }
  320. func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
  321. session, err := s.getSession()
  322. if err != nil {
  323. return nil, err
  324. }
  325. // open a new stream
  326. return session.OpenStreamSync(ctx)
  327. }