udpns.go 6.5 KB

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