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