udpns.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package dns
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. "golang.org/x/net/dns/dnsmessage"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/common/buf"
  11. "v2ray.com/core/common/net"
  12. "v2ray.com/core/common/session"
  13. "v2ray.com/core/common/signal/pubsub"
  14. "v2ray.com/core/common/task"
  15. "v2ray.com/core/features/routing"
  16. "v2ray.com/core/transport/internet/udp"
  17. )
  18. type IPRecord struct {
  19. IP net.IP
  20. Expire time.Time
  21. }
  22. type pendingRequest struct {
  23. domain string
  24. expire time.Time
  25. }
  26. type ClassicNameServer struct {
  27. sync.RWMutex
  28. address net.Destination
  29. ips map[string][]IPRecord
  30. requests map[uint16]pendingRequest
  31. pub *pubsub.Service
  32. udpServer *udp.Dispatcher
  33. cleanup *task.Periodic
  34. reqID uint32
  35. clientIP net.IP
  36. }
  37. func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, clientIP net.IP) *ClassicNameServer {
  38. s := &ClassicNameServer{
  39. address: address,
  40. ips: make(map[string][]IPRecord),
  41. requests: make(map[uint16]pendingRequest),
  42. clientIP: clientIP,
  43. pub: pubsub.NewService(),
  44. }
  45. s.cleanup = &task.Periodic{
  46. Interval: time.Minute,
  47. Execute: s.Cleanup,
  48. }
  49. s.udpServer = udp.NewDispatcher(dispatcher, s.HandleResponse)
  50. return s
  51. }
  52. func (s *ClassicNameServer) Cleanup() error {
  53. now := time.Now()
  54. s.Lock()
  55. defer s.Unlock()
  56. if len(s.ips) == 0 && len(s.requests) == 0 {
  57. return newError("nothing to do. stopping...")
  58. }
  59. for domain, ips := range s.ips {
  60. newIPs := make([]IPRecord, 0, len(ips))
  61. for _, ip := range ips {
  62. if ip.Expire.After(now) {
  63. newIPs = append(newIPs, ip)
  64. }
  65. }
  66. if len(newIPs) == 0 {
  67. delete(s.ips, domain)
  68. } else if len(newIPs) < len(ips) {
  69. s.ips[domain] = newIPs
  70. }
  71. }
  72. if len(s.ips) == 0 {
  73. s.ips = make(map[string][]IPRecord)
  74. }
  75. for id, req := range s.requests {
  76. if req.expire.Before(now) {
  77. delete(s.requests, id)
  78. }
  79. }
  80. if len(s.requests) == 0 {
  81. s.requests = make(map[uint16]pendingRequest)
  82. }
  83. return nil
  84. }
  85. func (s *ClassicNameServer) HandleResponse(ctx context.Context, payload *buf.Buffer) {
  86. var parser dnsmessage.Parser
  87. header, err := parser.Start(payload.Bytes())
  88. if err != nil {
  89. newError("failed to parse DNS response").Base(err).AtWarning().WriteToLog()
  90. return
  91. }
  92. if err := parser.SkipAllQuestions(); err != nil {
  93. newError("failed to skip questions in DNS response").Base(err).AtWarning().WriteToLog()
  94. return
  95. }
  96. id := header.ID
  97. s.Lock()
  98. req, f := s.requests[id]
  99. if f {
  100. delete(s.requests, id)
  101. }
  102. s.Unlock()
  103. if !f {
  104. return
  105. }
  106. domain := req.domain
  107. ips := make([]IPRecord, 0, 16)
  108. now := time.Now()
  109. for {
  110. header, err := parser.AnswerHeader()
  111. if err != nil {
  112. break
  113. }
  114. ttl := header.TTL
  115. if ttl == 0 {
  116. ttl = 600
  117. }
  118. switch header.Type {
  119. case dnsmessage.TypeA:
  120. ans, err := parser.AResource()
  121. if err != nil {
  122. break
  123. }
  124. ips = append(ips, IPRecord{
  125. IP: net.IP(ans.A[:]),
  126. Expire: now.Add(time.Duration(ttl) * time.Second),
  127. })
  128. case dnsmessage.TypeAAAA:
  129. ans, err := parser.AAAAResource()
  130. if err != nil {
  131. break
  132. }
  133. ips = append(ips, IPRecord{
  134. IP: net.IP(ans.AAAA[:]),
  135. Expire: now.Add(time.Duration(ttl) * time.Second),
  136. })
  137. default:
  138. }
  139. }
  140. if len(domain) > 0 && len(ips) > 0 {
  141. s.updateIP(domain, ips)
  142. }
  143. }
  144. func (s *ClassicNameServer) updateIP(domain string, ips []IPRecord) {
  145. s.Lock()
  146. newError("updating IP records for domain:", domain).AtDebug().WriteToLog()
  147. now := time.Now()
  148. eips := s.ips[domain]
  149. for _, ip := range eips {
  150. if ip.Expire.After(now) {
  151. ips = append(ips, ip)
  152. }
  153. }
  154. s.ips[domain] = ips
  155. s.pub.Publish(domain, nil)
  156. s.Unlock()
  157. common.Must(s.cleanup.Start())
  158. }
  159. func (s *ClassicNameServer) getMsgOptions() *dnsmessage.Resource {
  160. if len(s.clientIP) == 0 {
  161. return nil
  162. }
  163. var netmask int
  164. var family uint16
  165. if len(s.clientIP) == 4 {
  166. family = 1
  167. netmask = 24 // 24 for IPV4, 96 for IPv6
  168. } else {
  169. family = 2
  170. netmask = 96
  171. }
  172. b := make([]byte, 4)
  173. binary.BigEndian.PutUint16(b[0:], family)
  174. b[2] = byte(netmask)
  175. b[3] = 0
  176. switch family {
  177. case 1:
  178. ip := s.clientIP.To4().Mask(net.CIDRMask(netmask, net.IPv4len*8))
  179. needLength := (netmask + 8 - 1) / 8 // division rounding up
  180. b = append(b, ip[:needLength]...)
  181. case 2:
  182. ip := s.clientIP.Mask(net.CIDRMask(netmask, net.IPv6len*8))
  183. needLength := (netmask + 8 - 1) / 8 // division rounding up
  184. b = append(b, ip[:needLength]...)
  185. }
  186. const EDNS0SUBNET = 0x08
  187. opt := new(dnsmessage.Resource)
  188. common.Must(opt.Header.SetEDNS0(1350, 0xfe00, true))
  189. opt.Body = &dnsmessage.OPTResource{
  190. Options: []dnsmessage.Option{
  191. {
  192. Code: EDNS0SUBNET,
  193. Data: b,
  194. },
  195. },
  196. }
  197. return opt
  198. }
  199. func (s *ClassicNameServer) addPendingRequest(domain string) uint16 {
  200. id := uint16(atomic.AddUint32(&s.reqID, 1))
  201. s.Lock()
  202. defer s.Unlock()
  203. s.requests[id] = pendingRequest{
  204. domain: domain,
  205. expire: time.Now().Add(time.Second * 8),
  206. }
  207. return id
  208. }
  209. func (s *ClassicNameServer) buildMsgs(domain string, option IPOption) []*dnsmessage.Message {
  210. qA := dnsmessage.Question{
  211. Name: dnsmessage.MustNewName(domain),
  212. Type: dnsmessage.TypeA,
  213. Class: dnsmessage.ClassINET,
  214. }
  215. qAAAA := dnsmessage.Question{
  216. Name: dnsmessage.MustNewName(domain),
  217. Type: dnsmessage.TypeAAAA,
  218. Class: dnsmessage.ClassINET,
  219. }
  220. var msgs []*dnsmessage.Message
  221. if option.IPv4Enable {
  222. msg := new(dnsmessage.Message)
  223. msg.Header.ID = s.addPendingRequest(domain)
  224. msg.Header.RecursionDesired = true
  225. msg.Questions = []dnsmessage.Question{qA}
  226. if opt := s.getMsgOptions(); opt != nil {
  227. msg.Additionals = append(msg.Additionals, *opt)
  228. }
  229. msgs = append(msgs, msg)
  230. }
  231. if option.IPv6Enable {
  232. msg := new(dnsmessage.Message)
  233. msg.Header.ID = s.addPendingRequest(domain)
  234. msg.Header.RecursionDesired = true
  235. msg.Questions = []dnsmessage.Question{qAAAA}
  236. if opt := s.getMsgOptions(); opt != nil {
  237. msg.Additionals = append(msg.Additionals, *opt)
  238. }
  239. msgs = append(msgs, msg)
  240. }
  241. return msgs
  242. }
  243. func msgToBuffer2(msg *dnsmessage.Message) (*buf.Buffer, error) {
  244. buffer := buf.New()
  245. rawBytes := buffer.Extend(buf.Size)
  246. packed, err := msg.AppendPack(rawBytes[:0])
  247. if err != nil {
  248. buffer.Release()
  249. return nil, err
  250. }
  251. buffer.Resize(0, int32(len(packed)))
  252. return buffer, nil
  253. }
  254. func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, option IPOption) {
  255. newError("querying DNS for: ", domain).AtDebug().WriteToLog(session.ExportIDToError(ctx))
  256. msgs := s.buildMsgs(domain, option)
  257. for _, msg := range msgs {
  258. b, err := msgToBuffer2(msg)
  259. common.Must(err)
  260. s.udpServer.Dispatch(context.Background(), s.address, b)
  261. }
  262. }
  263. func (s *ClassicNameServer) findIPsForDomain(domain string, option IPOption) []net.IP {
  264. s.RLock()
  265. records, found := s.ips[domain]
  266. s.RUnlock()
  267. if found && len(records) > 0 {
  268. var ips []net.IP
  269. now := time.Now()
  270. for _, rec := range records {
  271. if rec.Expire.After(now) {
  272. ips = append(ips, rec.IP)
  273. }
  274. }
  275. return filterIP(ips, option)
  276. }
  277. return nil
  278. }
  279. func Fqdn(domain string) string {
  280. if len(domain) > 0 && domain[len(domain)-1] == '.' {
  281. return domain
  282. }
  283. return domain + "."
  284. }
  285. func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, option IPOption) ([]net.IP, error) {
  286. fqdn := Fqdn(domain)
  287. ips := s.findIPsForDomain(fqdn, option)
  288. if len(ips) > 0 {
  289. return ips, nil
  290. }
  291. sub := s.pub.Subscribe(fqdn)
  292. defer sub.Close()
  293. s.sendQuery(ctx, fqdn, option)
  294. for {
  295. ips := s.findIPsForDomain(fqdn, option)
  296. if len(ips) > 0 {
  297. return ips, nil
  298. }
  299. select {
  300. case <-ctx.Done():
  301. return nil, ctx.Err()
  302. case <-sub.Wait():
  303. }
  304. }
  305. }