udpns.go 7.9 KB

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