udpns.go 7.9 KB

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