udpns.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package dns
  2. import (
  3. "context"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "github.com/miekg/dns"
  8. "v2ray.com/core"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/buf"
  11. "v2ray.com/core/common/net"
  12. "v2ray.com/core/common/signal/pubsub"
  13. "v2ray.com/core/common/task"
  14. "v2ray.com/core/transport/internet/udp"
  15. )
  16. var (
  17. multiQuestionDNS = map[net.Address]bool{
  18. net.IPAddress([]byte{8, 8, 8, 8}): true,
  19. net.IPAddress([]byte{8, 8, 4, 4}): true,
  20. net.IPAddress([]byte{9, 9, 9, 9}): true,
  21. }
  22. )
  23. type IPRecord struct {
  24. IP net.IP
  25. Expire time.Time
  26. }
  27. type pendingRequest struct {
  28. domain string
  29. expire time.Time
  30. }
  31. type ClassicNameServer struct {
  32. sync.RWMutex
  33. address net.Destination
  34. ips map[string][]IPRecord
  35. requests map[uint16]pendingRequest
  36. pub *pubsub.Service
  37. udpServer *udp.Dispatcher
  38. cleanup *task.Periodic
  39. reqID uint32
  40. clientIP net.IP
  41. }
  42. func NewClassicNameServer(address net.Destination, dispatcher core.Dispatcher, clientIP net.IP) *ClassicNameServer {
  43. s := &ClassicNameServer{
  44. address: address,
  45. ips: make(map[string][]IPRecord),
  46. requests: make(map[uint16]pendingRequest),
  47. clientIP: clientIP,
  48. pub: pubsub.NewService(),
  49. }
  50. s.cleanup = &task.Periodic{
  51. Interval: time.Minute,
  52. Execute: s.Cleanup,
  53. }
  54. s.udpServer = udp.NewDispatcher(dispatcher, s.HandleResponse)
  55. return s
  56. }
  57. func (s *ClassicNameServer) Cleanup() error {
  58. now := time.Now()
  59. s.Lock()
  60. defer s.Unlock()
  61. if len(s.ips) == 0 && len(s.requests) == 0 {
  62. return newError("nothing to do. stopping...")
  63. }
  64. for domain, ips := range s.ips {
  65. newIPs := make([]IPRecord, 0, len(ips))
  66. for _, ip := range ips {
  67. if ip.Expire.After(now) {
  68. newIPs = append(newIPs, ip)
  69. }
  70. }
  71. if len(newIPs) == 0 {
  72. delete(s.ips, domain)
  73. } else if len(newIPs) < len(ips) {
  74. s.ips[domain] = newIPs
  75. }
  76. }
  77. if len(s.ips) == 0 {
  78. s.ips = make(map[string][]IPRecord)
  79. }
  80. for id, req := range s.requests {
  81. if req.expire.Before(now) {
  82. delete(s.requests, id)
  83. }
  84. }
  85. if len(s.requests) == 0 {
  86. s.requests = make(map[uint16]pendingRequest)
  87. }
  88. return nil
  89. }
  90. func (s *ClassicNameServer) HandleResponse(ctx context.Context, payload *buf.Buffer) {
  91. msg := new(dns.Msg)
  92. err := msg.Unpack(payload.Bytes())
  93. if err == dns.ErrTruncated {
  94. newError("truncated message received. DNS server should still work. If you see anything abnormal, please submit an issue to v2ray-core.").AtWarning().WriteToLog()
  95. } else if err != nil {
  96. newError("failed to parse DNS response").Base(err).AtWarning().WriteToLog()
  97. return
  98. }
  99. id := msg.Id
  100. s.Lock()
  101. req, f := s.requests[id]
  102. if f {
  103. delete(s.requests, id)
  104. }
  105. s.Unlock()
  106. if !f {
  107. return
  108. }
  109. domain := req.domain
  110. ips := make([]IPRecord, 0, 16)
  111. now := time.Now()
  112. for _, rr := range msg.Answer {
  113. var ip net.IP
  114. ttl := rr.Header().Ttl
  115. switch rr := rr.(type) {
  116. case *dns.A:
  117. ip = rr.A
  118. case *dns.AAAA:
  119. ip = rr.AAAA
  120. }
  121. if ttl == 0 {
  122. ttl = 600
  123. }
  124. if len(ip) > 0 {
  125. ips = append(ips, IPRecord{
  126. IP: ip,
  127. Expire: now.Add(time.Second * time.Duration(ttl)),
  128. })
  129. }
  130. }
  131. if len(domain) > 0 && len(ips) > 0 {
  132. s.updateIP(domain, ips)
  133. }
  134. }
  135. func (s *ClassicNameServer) updateIP(domain string, ips []IPRecord) {
  136. s.Lock()
  137. newError("updating IP records for domain:", domain).AtDebug().WriteToLog()
  138. now := time.Now()
  139. eips := s.ips[domain]
  140. for _, ip := range eips {
  141. if ip.Expire.After(now) {
  142. ips = append(ips, ip)
  143. }
  144. }
  145. s.ips[domain] = ips
  146. s.pub.Publish(domain, nil)
  147. s.Unlock()
  148. common.Must(s.cleanup.Start())
  149. }
  150. func (s *ClassicNameServer) getMsgOptions() *dns.OPT {
  151. if len(s.clientIP) == 0 {
  152. return nil
  153. }
  154. o := new(dns.OPT)
  155. o.Hdr.Name = "."
  156. o.Hdr.Rrtype = dns.TypeOPT
  157. o.SetUDPSize(1350)
  158. e := new(dns.EDNS0_SUBNET)
  159. e.Code = dns.EDNS0SUBNET
  160. if len(s.clientIP) == 4 {
  161. e.Family = 1 // 1 for IPv4 source address, 2 for IPv6
  162. e.SourceNetmask = 24 // 32 for IPV4, 128 for IPv6
  163. } else {
  164. e.Family = 2
  165. e.SourceNetmask = 96
  166. }
  167. e.SourceScope = 0
  168. e.Address = s.clientIP
  169. o.Option = append(o.Option, e)
  170. return o
  171. }
  172. func (s *ClassicNameServer) addPendingRequest(domain string) uint16 {
  173. id := uint16(atomic.AddUint32(&s.reqID, 1))
  174. s.Lock()
  175. defer s.Unlock()
  176. s.requests[id] = pendingRequest{
  177. domain: domain,
  178. expire: time.Now().Add(time.Second * 8),
  179. }
  180. return id
  181. }
  182. func (s *ClassicNameServer) buildMsgs(domain string) []*dns.Msg {
  183. allowMulti := multiQuestionDNS[s.address.Address]
  184. qA := dns.Question{
  185. Name: domain,
  186. Qtype: dns.TypeA,
  187. Qclass: dns.ClassINET,
  188. }
  189. qAAAA := dns.Question{
  190. Name: domain,
  191. Qtype: dns.TypeAAAA,
  192. Qclass: dns.ClassINET,
  193. }
  194. var msgs []*dns.Msg
  195. {
  196. msg := new(dns.Msg)
  197. msg.Id = s.addPendingRequest(domain)
  198. msg.RecursionDesired = true
  199. msg.Question = []dns.Question{qA}
  200. if allowMulti {
  201. msg.Question = append(msg.Question, qAAAA)
  202. }
  203. if opt := s.getMsgOptions(); opt != nil {
  204. msg.Extra = append(msg.Extra, opt)
  205. }
  206. msgs = append(msgs, msg)
  207. }
  208. if !allowMulti {
  209. msg := new(dns.Msg)
  210. msg.Id = s.addPendingRequest(domain)
  211. msg.RecursionDesired = true
  212. msg.Question = []dns.Question{qAAAA}
  213. if opt := s.getMsgOptions(); opt != nil {
  214. msg.Extra = append(msg.Extra, opt)
  215. }
  216. msgs = append(msgs, msg)
  217. }
  218. return msgs
  219. }
  220. func msgToBuffer(msg *dns.Msg) (*buf.Buffer, error) {
  221. buffer := buf.New()
  222. if err := buffer.Reset(func(b []byte) (int, error) {
  223. writtenBuffer, err := msg.PackBuffer(b)
  224. return len(writtenBuffer), err
  225. }); err != nil {
  226. buffer.Release()
  227. return nil, err
  228. }
  229. return buffer, nil
  230. }
  231. func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string) {
  232. msgs := s.buildMsgs(domain)
  233. for _, msg := range msgs {
  234. b, err := msgToBuffer(msg)
  235. common.Must(err)
  236. s.udpServer.Dispatch(context.Background(), s.address, b)
  237. }
  238. }
  239. func (s *ClassicNameServer) findIPsForDomain(domain string) []net.IP {
  240. s.RLock()
  241. records, found := s.ips[domain]
  242. s.RUnlock()
  243. if found && len(records) > 0 {
  244. var ips []net.IP
  245. now := time.Now()
  246. for _, rec := range records {
  247. if rec.Expire.After(now) {
  248. ips = append(ips, rec.IP)
  249. }
  250. }
  251. return ips
  252. }
  253. return nil
  254. }
  255. func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string) ([]net.IP, error) {
  256. fqdn := dns.Fqdn(domain)
  257. ips := s.findIPsForDomain(fqdn)
  258. if len(ips) > 0 {
  259. return ips, nil
  260. }
  261. sub := s.pub.Subscribe(fqdn)
  262. defer sub.Close()
  263. s.sendQuery(ctx, fqdn)
  264. for {
  265. ips := s.findIPsForDomain(fqdn)
  266. if len(ips) > 0 {
  267. return ips, nil
  268. }
  269. select {
  270. case <-ctx.Done():
  271. return nil, ctx.Err()
  272. case <-sub.Wait():
  273. }
  274. }
  275. }