hosts.go 1.9 KB

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