hosts.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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[DomainMatchingType]strmatcher.Type{
  12. DomainMatchingType_Full: strmatcher.Full,
  13. DomainMatchingType_Subdomain: strmatcher.Domain,
  14. DomainMatchingType_Keyword: strmatcher.Substr,
  15. }
  16. func toStrMatcher(t DomainMatchingType, domain string) (strmatcher.Matcher, error) {
  17. strMType, f := typeMap[t]
  18. if !f {
  19. return nil, newError("unknown mapping type", t).AtWarning()
  20. }
  21. matcher, err := strMType.New(domain)
  22. if err != nil {
  23. return nil, newError("failed to create str matcher").Base(err)
  24. }
  25. return matcher, nil
  26. }
  27. func NewStaticHosts(hosts []*Config_HostMapping, legacy map[string]*net.IPOrDomain) (*StaticHosts, error) {
  28. g := new(strmatcher.MatcherGroup)
  29. sh := &StaticHosts{
  30. ips: make(map[uint32][]net.IP),
  31. matchers: g,
  32. }
  33. if legacy != nil {
  34. for domain, ip := range legacy {
  35. matcher, err := strmatcher.Full.New(domain)
  36. common.Must(err)
  37. id := g.Add(matcher)
  38. address := ip.AsAddress()
  39. if address.Family().IsDomain() {
  40. return nil, newError("ignoring domain address in static hosts: ", address.Domain()).AtWarning()
  41. }
  42. sh.ips[id] = []net.IP{address.IP()}
  43. }
  44. }
  45. for _, mapping := range hosts {
  46. matcher, err := toStrMatcher(mapping.Type, mapping.Domain)
  47. if err != nil {
  48. return nil, newError("failed to create domain matcher").Base(err)
  49. }
  50. id := g.Add(matcher)
  51. ips := make([]net.IP, len(mapping.Ip))
  52. for idx, ip := range mapping.Ip {
  53. ips[idx] = net.IP(ip)
  54. }
  55. sh.ips[id] = ips
  56. }
  57. return sh, nil
  58. }
  59. func (h *StaticHosts) LookupIP(domain string) []net.IP {
  60. id := h.matchers.Match(domain)
  61. if id == 0 {
  62. return nil
  63. }
  64. return h.ips[id]
  65. }