nameserver_quic.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. package dns
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "net/url"
  7. "sync"
  8. "time"
  9. "github.com/quic-go/quic-go"
  10. "golang.org/x/net/dns/dnsmessage"
  11. "github.com/v2fly/v2ray-core/v5/common"
  12. "github.com/v2fly/v2ray-core/v5/common/buf"
  13. "github.com/v2fly/v2ray-core/v5/common/net"
  14. "github.com/v2fly/v2ray-core/v5/common/protocol/dns"
  15. "github.com/v2fly/v2ray-core/v5/common/session"
  16. "github.com/v2fly/v2ray-core/v5/common/signal/pubsub"
  17. "github.com/v2fly/v2ray-core/v5/common/task"
  18. dns_feature "github.com/v2fly/v2ray-core/v5/features/dns"
  19. "github.com/v2fly/v2ray-core/v5/transport/internet/tls"
  20. )
  21. // NextProtoDQ - During connection establishment, DNS/QUIC support is indicated
  22. // by selecting the ALPN token "doq" in the crypto handshake.
  23. const NextProtoDQ = "doq"
  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. name string
  32. destination net.Destination
  33. connection quic.Connection
  34. }
  35. // NewQUICNameServer creates DNS-over-QUIC client object for local resolving
  36. func NewQUICNameServer(url *url.URL) (*QUICNameServer, error) {
  37. newError("DNS: created Local DNS-over-QUIC client for ", url.String()).AtInfo().WriteToLog()
  38. var err error
  39. port := net.Port(853)
  40. if url.Port() != "" {
  41. port, err = net.PortFromString(url.Port())
  42. if err != nil {
  43. return nil, err
  44. }
  45. }
  46. dest := net.UDPDestination(net.ParseAddress(url.Hostname()), port)
  47. s := &QUICNameServer{
  48. ips: make(map[string]record),
  49. pub: pubsub.NewService(),
  50. name: url.String(),
  51. destination: dest,
  52. }
  53. s.cleanup = &task.Periodic{
  54. Interval: time.Minute,
  55. Execute: s.Cleanup,
  56. }
  57. return s, nil
  58. }
  59. // Name returns client name
  60. func (s *QUICNameServer) Name() string {
  61. return s.name
  62. }
  63. // Cleanup clears expired items from cache
  64. func (s *QUICNameServer) Cleanup() error {
  65. now := time.Now()
  66. s.Lock()
  67. defer s.Unlock()
  68. if len(s.ips) == 0 {
  69. return newError("nothing to do. stopping...")
  70. }
  71. for domain, record := range s.ips {
  72. if record.A != nil && record.A.Expire.Before(now) {
  73. record.A = nil
  74. }
  75. if record.AAAA != nil && record.AAAA.Expire.Before(now) {
  76. record.AAAA = nil
  77. }
  78. if record.A == nil && record.AAAA == nil {
  79. newError(s.name, " cleanup ", domain).AtDebug().WriteToLog()
  80. delete(s.ips, domain)
  81. } else {
  82. s.ips[domain] = record
  83. }
  84. }
  85. if len(s.ips) == 0 {
  86. s.ips = make(map[string]record)
  87. }
  88. return nil
  89. }
  90. func (s *QUICNameServer) updateIP(req *dnsRequest, ipRec *IPRecord) {
  91. elapsed := time.Since(req.start)
  92. s.Lock()
  93. rec := s.ips[req.domain]
  94. updated := false
  95. switch req.reqType {
  96. case dnsmessage.TypeA:
  97. if isNewer(rec.A, ipRec) {
  98. rec.A = ipRec
  99. updated = true
  100. }
  101. case dnsmessage.TypeAAAA:
  102. addr := make([]net.Address, 0)
  103. for _, ip := range ipRec.IP {
  104. if len(ip.IP()) == net.IPv6len {
  105. addr = append(addr, ip)
  106. }
  107. }
  108. ipRec.IP = addr
  109. if isNewer(rec.AAAA, ipRec) {
  110. rec.AAAA = ipRec
  111. updated = true
  112. }
  113. }
  114. newError(s.name, " got answer: ", req.domain, " ", req.reqType, " -> ", ipRec.IP, " ", elapsed).AtInfo().WriteToLog()
  115. if updated {
  116. s.ips[req.domain] = rec
  117. }
  118. switch req.reqType {
  119. case dnsmessage.TypeA:
  120. s.pub.Publish(req.domain+"4", nil)
  121. case dnsmessage.TypeAAAA:
  122. s.pub.Publish(req.domain+"6", nil)
  123. }
  124. s.Unlock()
  125. common.Must(s.cleanup.Start())
  126. }
  127. func (s *QUICNameServer) newReqID() uint16 {
  128. return 0
  129. }
  130. func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
  131. newError(s.name, " querying: ", domain).AtInfo().WriteToLog(session.ExportIDToError(ctx))
  132. reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP))
  133. var deadline time.Time
  134. if d, ok := ctx.Deadline(); ok {
  135. deadline = d
  136. } else {
  137. deadline = time.Now().Add(time.Second * 5)
  138. }
  139. for _, req := range reqs {
  140. go func(r *dnsRequest) {
  141. // generate new context for each req, using same context
  142. // may cause reqs all aborted if any one encounter an error
  143. dnsCtx := ctx
  144. // reserve internal dns server requested Inbound
  145. if inbound := session.InboundFromContext(ctx); inbound != nil {
  146. dnsCtx = session.ContextWithInbound(dnsCtx, inbound)
  147. }
  148. dnsCtx = session.ContextWithContent(dnsCtx, &session.Content{
  149. Protocol: "quic",
  150. SkipDNSResolve: true,
  151. })
  152. var cancel context.CancelFunc
  153. dnsCtx, cancel = context.WithDeadline(dnsCtx, deadline)
  154. defer cancel()
  155. b, err := dns.PackMessage(r.msg)
  156. if err != nil {
  157. newError("failed to pack dns query").Base(err).AtError().WriteToLog()
  158. return
  159. }
  160. dnsReqBuf := buf.New()
  161. binary.Write(dnsReqBuf, binary.BigEndian, uint16(b.Len()))
  162. dnsReqBuf.Write(b.Bytes())
  163. b.Release()
  164. conn, err := s.openStream(dnsCtx)
  165. if err != nil {
  166. newError("failed to open quic connection").Base(err).AtError().WriteToLog()
  167. return
  168. }
  169. _, err = conn.Write(dnsReqBuf.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.ReadFullFrom(conn, 2)
  178. if err != nil && n == 0 {
  179. newError("failed to read response length").Base(err).AtError().WriteToLog()
  180. return
  181. }
  182. var length int16
  183. err = binary.Read(bytes.NewReader(respBuf.Bytes()), binary.BigEndian, &length)
  184. if err != nil {
  185. newError("failed to parse response length").Base(err).AtError().WriteToLog()
  186. return
  187. }
  188. respBuf.Clear()
  189. n, err = respBuf.ReadFullFrom(conn, int32(length))
  190. if err != nil && n == 0 {
  191. newError("failed to read response length").Base(err).AtError().WriteToLog()
  192. return
  193. }
  194. rec, err := parseResponse(respBuf.Bytes())
  195. if err != nil {
  196. newError("failed to handle response").Base(err).AtError().WriteToLog()
  197. return
  198. }
  199. s.updateIP(r, rec)
  200. }(req)
  201. }
  202. }
  203. func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) {
  204. s.RLock()
  205. record, found := s.ips[domain]
  206. s.RUnlock()
  207. if !found {
  208. return nil, errRecordNotFound
  209. }
  210. var ips []net.Address
  211. var lastErr error
  212. if option.IPv4Enable {
  213. a, err := record.A.getIPs()
  214. if err != nil {
  215. lastErr = err
  216. }
  217. ips = append(ips, a...)
  218. }
  219. if option.IPv6Enable {
  220. aaaa, err := record.AAAA.getIPs()
  221. if err != nil {
  222. lastErr = err
  223. }
  224. ips = append(ips, aaaa...)
  225. }
  226. if len(ips) > 0 {
  227. return toNetIP(ips)
  228. }
  229. if lastErr != nil {
  230. return nil, lastErr
  231. }
  232. return nil, dns_feature.ErrEmptyResponse
  233. }
  234. // QueryIP is called from dns.Server->queryIPTimeout
  235. func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) {
  236. fqdn := Fqdn(domain)
  237. if disableCache {
  238. newError("DNS cache is disabled. Querying IP for ", domain, " at ", s.name).AtDebug().WriteToLog()
  239. } else {
  240. ips, err := s.findIPsForDomain(fqdn, option)
  241. if err != errRecordNotFound {
  242. newError(s.name, " cache HIT ", domain, " -> ", ips).Base(err).AtDebug().WriteToLog()
  243. return ips, err
  244. }
  245. }
  246. // ipv4 and ipv6 belong to different subscription groups
  247. var sub4, sub6 *pubsub.Subscriber
  248. if option.IPv4Enable {
  249. sub4 = s.pub.Subscribe(fqdn + "4")
  250. defer sub4.Close()
  251. }
  252. if option.IPv6Enable {
  253. sub6 = s.pub.Subscribe(fqdn + "6")
  254. defer sub6.Close()
  255. }
  256. done := make(chan interface{})
  257. go func() {
  258. if sub4 != nil {
  259. select {
  260. case <-sub4.Wait():
  261. case <-ctx.Done():
  262. }
  263. }
  264. if sub6 != nil {
  265. select {
  266. case <-sub6.Wait():
  267. case <-ctx.Done():
  268. }
  269. }
  270. close(done)
  271. }()
  272. s.sendQuery(ctx, fqdn, clientIP, option)
  273. for {
  274. ips, err := s.findIPsForDomain(fqdn, option)
  275. if err != errRecordNotFound {
  276. return ips, err
  277. }
  278. select {
  279. case <-ctx.Done():
  280. return nil, ctx.Err()
  281. case <-done:
  282. }
  283. }
  284. }
  285. func isActive(s quic.Connection) bool {
  286. select {
  287. case <-s.Context().Done():
  288. return false
  289. default:
  290. return true
  291. }
  292. }
  293. func (s *QUICNameServer) getConnection(ctx context.Context) (quic.Connection, error) {
  294. var conn quic.Connection
  295. s.RLock()
  296. conn = s.connection
  297. if conn != nil && isActive(conn) {
  298. s.RUnlock()
  299. return conn, nil
  300. }
  301. if conn != nil {
  302. // we're recreating the connection, let's create a new one
  303. _ = conn.CloseWithError(0, "")
  304. }
  305. s.RUnlock()
  306. s.Lock()
  307. defer s.Unlock()
  308. var err error
  309. conn, err = s.openConnection(ctx)
  310. if err != nil {
  311. // This does not look too nice, but QUIC (or maybe quic-go)
  312. // doesn't seem stable enough.
  313. // Maybe retransmissions aren't fully implemented in quic-go?
  314. // Anyways, the simple solution is to make a second try when
  315. // it fails to open the QUIC connection.
  316. conn, err = s.openConnection(ctx)
  317. if err != nil {
  318. return nil, err
  319. }
  320. }
  321. s.connection = conn
  322. return conn, nil
  323. }
  324. func (s *QUICNameServer) openConnection(ctx context.Context) (quic.Connection, error) {
  325. tlsConfig := tls.Config{
  326. ServerName: func() string {
  327. switch s.destination.Address.Family() {
  328. case net.AddressFamilyIPv4, net.AddressFamilyIPv6:
  329. return s.destination.Address.IP().String()
  330. case net.AddressFamilyDomain:
  331. return s.destination.Address.Domain()
  332. default:
  333. panic("unknown address family")
  334. }
  335. }(),
  336. }
  337. quicConfig := &quic.Config{
  338. HandshakeIdleTimeout: handshakeIdleTimeout,
  339. }
  340. conn, err := quic.DialAddr(ctx, s.destination.NetAddr(), tlsConfig.GetTLSConfig(tls.WithNextProto(NextProtoDQ)), quicConfig)
  341. if err != nil {
  342. return nil, err
  343. }
  344. return conn, nil
  345. }
  346. func (s *QUICNameServer) openStream(ctx context.Context) (quic.Stream, error) {
  347. conn, err := s.getConnection(ctx)
  348. if err != nil {
  349. return nil, err
  350. }
  351. // open a new stream
  352. return conn.OpenStreamSync(ctx)
  353. }