hosts.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package dns
  2. import (
  3. "v2ray.com/core/common"
  4. "v2ray.com/core/common/net"
  5. "v2ray.com/core/common/strmatcher"
  6. )
  7. type StaticHosts struct {
  8. ips map[uint32][]net.IP
  9. matchers *strmatcher.MatcherGroup
  10. }
  11. var typeMap = map[Config_HostMapping_Type]strmatcher.Type{
  12. Config_HostMapping_Full: strmatcher.Full,
  13. Config_HostMapping_SubDomain: strmatcher.Domain,
  14. }
  15. func NewStaticHosts(hosts []*Config_HostMapping, legacy map[string]*net.IPOrDomain) (*StaticHosts, error) {
  16. g := strmatcher.NewMatcherGroup()
  17. sh := &StaticHosts{
  18. ips: make(map[uint32][]net.IP),
  19. matchers: g,
  20. }
  21. if legacy != nil {
  22. for domain, ip := range legacy {
  23. matcher, err := strmatcher.Full.New(domain)
  24. common.Must(err)
  25. id := g.Add(matcher)
  26. address := ip.AsAddress()
  27. if address.Family().IsDomain() {
  28. return nil, newError("ignoring domain address in static hosts: ", address.Domain()).AtWarning()
  29. }
  30. sh.ips[id] = []net.IP{address.IP()}
  31. }
  32. }
  33. for _, mapping := range hosts {
  34. strMType, f := typeMap[mapping.Type]
  35. if !f {
  36. return nil, newError("unknown mapping type", mapping.Type).AtWarning()
  37. }
  38. matcher, err := strMType.New(mapping.Domain)
  39. if err != nil {
  40. return nil, newError("failed to create domain matcher").Base(err)
  41. }
  42. id := g.Add(matcher)
  43. ips := make([]net.IP, len(mapping.Ip))
  44. for idx, ip := range mapping.Ip {
  45. ips[idx] = net.IP(ip)
  46. }
  47. sh.ips[id] = ips
  48. }
  49. return sh, nil
  50. }
  51. func (h *StaticHosts) LookupIP(domain string) []net.IP {
  52. id := h.matchers.Match(domain)
  53. if id == 0 {
  54. return nil
  55. }
  56. return h.ips[id]
  57. }