nameserver_quic.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package dns
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "net/url"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/quic-go/quic-go"
  11. "golang.org/x/net/dns/dnsmessage"
  12. "github.com/v2fly/v2ray-core/v5/common"
  13. "github.com/v2fly/v2ray-core/v5/common/buf"
  14. "github.com/v2fly/v2ray-core/v5/common/net"
  15. "github.com/v2fly/v2ray-core/v5/common/protocol/dns"
  16. "github.com/v2fly/v2ray-core/v5/common/session"
  17. "github.com/v2fly/v2ray-core/v5/common/signal/pubsub"
  18. "github.com/v2fly/v2ray-core/v5/common/task"
  19. dns_feature "github.com/v2fly/v2ray-core/v5/features/dns"
  20. "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
  21. )
  22. // NextProtoDQ - During connection establishment, DNS/QUIC support is indicated
  23. // by selecting the ALPN token "doq" in the crypto handshake.
  24. const NextProtoDQ = "doq"
  25. const handshakeIdleTimeout = 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. connection quic.Connection
  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(853)
  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.ParseAddress(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 dns_feature.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 := ctx
  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. dnsReqBuf := buf.New()
  163. binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len()))
  164. dnsReqBuf.Write(b.Bytes())
  165. b.Release()
  166. conn, err := s.openStream(dnsCtx)
  167. if err != nil {
  168. newError("failed to open quic connection").Base(err).AtError().WriteToLog()
  169. return
  170. }
  171. _, err = conn.Write(dnsReqBuf.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.ReadFullFrom(conn, 2)
  180. if err != nil && n == 0 {
  181. newError("failed to read response length").Base(err).AtError().WriteToLog()
  182. return
  183. }
  184. var length int16
  185. err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length)
  186. if err != nil {
  187. newError("failed to parse response length").Base(err).AtError().WriteToLog()
  188. return
  189. }
  190. respBuf.Clear()
  191. n, err = respBuf.ReadFullFrom(conn, int32(length))
  192. if err != nil && n == 0 {
  193. newError("failed to read response length").Base(err).AtError().WriteToLog()
  194. return
  195. }
  196. rec, err := parseResponse(respBuf.Bytes())
  197. if err != nil {
  198. newError("failed to handle response").Base(err).AtError().WriteToLog()
  199. return
  200. }
  201. s.updateIP(r, rec)
  202. }(req)
  203. }
  204. }
  205. func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  206. s.RLock()
  207. record, found := s.ips[domain]
  208. s.RUnlock()
  209. if !found {
  210. return nil, errRecordNotFound
  211. }
  212. var ips []net.Address
  213. var lastErr error
  214. if option.IPv4Enable {
  215. a, err := record.A.getIPs()
  216. if err != nil {
  217. lastErr = err
  218. }
  219. ips = append(ips, a...)
  220. }
  221. if option.IPv6Enable {
  222. aaaa, err := record.AAAA.getIPs()
  223. if err != nil {
  224. lastErr = err
  225. }
  226. ips = append(ips, aaaa...)
  227. }
  228. if len(ips) > 0 {
  229. return toNetIP(ips)
  230. }
  231. if lastErr != nil {
  232. return nil, lastErr
  233. }
  234. return nil, dns_feature.ErrEmptyResponse
  235. }
  236. // QueryIP is called from dns.Server->queryIPTimeout
  237. func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) {
  238. fqdn := Fqdn(domain)
  239. if disableCache {
  240. newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog()
  241. } else {
  242. ips, err := s.findIPsForDomain(fqdn, option)
  243. if err != errRecordNotFound {
  244. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  245. return ips, err
  246. }
  247. }
  248. // ipv4 and ipv6 belong to different subscription groups
  249. var sub4, sub6 *pubsub.Subscriber
  250. if option.IPv4Enable {
  251. sub4 = s.pub.Subscribe(fqdn + "4")
  252. defer sub4.Close()
  253. }
  254. if option.IPv6Enable {
  255. sub6 = s.pub.Subscribe(fqdn + "6")
  256. defer sub6.Close()
  257. }
  258. done := make(chan interface{})
  259. go func() {
  260. if sub4 != nil {
  261. select {
  262. case <-sub4.Wait():
  263. case <-ctx.Done():
  264. }
  265. }
  266. if sub6 != nil {
  267. select {
  268. case <-sub6.Wait():
  269. case <-ctx.Done():
  270. }
  271. }
  272. close(done)
  273. }()
  274. s.sendQuery(ctx, fqdn, clientIP, option)
  275. for {
  276. ips, err := s.findIPsForDomain(fqdn, option)
  277. if err != errRecordNotFound {
  278. return ips, err
  279. }
  280. select {
  281. case <-ctx.Done():
  282. return nil, ctx.Err()
  283. case <-done:
  284. }
  285. }
  286. }
  287. func isActive(s quic.Connection) bool {
  288. select {
  289. case <-s.Context().Done():
  290. return false
  291. default:
  292. return true
  293. }
  294. }
  295. func (s *QUICNameServer) getConnection(ctx context.Context) (quic.Connection, error) {
  296. var conn quic.Connection
  297. s.RLock()
  298. conn = s.connection
  299. if conn != nil && isActive(conn) {
  300. s.RUnlock()
  301. return conn, nil
  302. }
  303. if conn != nil {
  304. // we're recreating the connection, let's create a new one
  305. _ = conn.CloseWithError(0, "")
  306. }
  307. s.RUnlock()
  308. s.Lock()
  309. defer s.Unlock()
  310. var err error
  311. conn, err = s.openConnection(ctx)
  312. if err != nil {
  313. // This does not look too nice, but QUIC (or maybe quic-go)
  314. // doesn't seem stable enough.
  315. // Maybe retransmissions aren't fully implemented in quic-go?
  316. // Anyways, the simple solution is to make a second try when
  317. // it fails to open the QUIC connection.
  318. conn, err = s.openConnection(ctx)
  319. if err != nil {
  320. return nil, err
  321. }
  322. }
  323. s.connection = conn
  324. return conn, nil
  325. }
  326. func (s *QUICNameServer) openConnection(ctx context.Context) (quic.Connection, error) {
  327. tlsConfig := tls.Config{
  328. ServerName: s.destination.Address.Domain(),
  329. }
  330. quicConfig := &quic.Config{
  331. HandshakeIdleTimeout: handshakeIdleTimeout,
  332. }
  333. conn, err := quic.DialAddr(ctx, s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto(NextProtoDQ)), quicConfig)
  334. if err != nil {
  335. return nil, err
  336. }
  337. return conn, nil
  338. }
  339. func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
  340. conn, err := s.getConnection(ctx)
  341. if err != nil {
  342. return nil, err
  343. }
  344. // open a new stream
  345. return conn.OpenStreamSync(ctx)
  346. }