udpns.go 7.1 KB

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