udpns.go 7.5 KB

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