nameserver_quic.go 9.3 KB

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