github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/infra/conf/synthetic/dns/fakedns.go (about)

     1  package dns
     2  
     3  import (
     4  	"encoding/json"
     5  	"net"
     6  
     7  	"github.com/v2fly/v2ray-core/v5/app/dns/fakedns"
     8  )
     9  
    10  type FakeDNSPoolElementConfig struct {
    11  	IPPool  string `json:"ipPool"`
    12  	LRUSize int64  `json:"poolSize"`
    13  }
    14  
    15  type FakeDNSConfig struct {
    16  	pool  *FakeDNSPoolElementConfig
    17  	pools []*FakeDNSPoolElementConfig
    18  }
    19  
    20  // UnmarshalJSON implements encoding/json.Unmarshaler.UnmarshalJSON
    21  func (f *FakeDNSConfig) UnmarshalJSON(data []byte) error {
    22  	var pool FakeDNSPoolElementConfig
    23  	var pools []*FakeDNSPoolElementConfig
    24  	var ipPools []string
    25  	switch {
    26  	case json.Unmarshal(data, &pool) == nil:
    27  		f.pool = &pool
    28  	case json.Unmarshal(data, &pools) == nil:
    29  		f.pools = pools
    30  	case json.Unmarshal(data, &ipPools) == nil:
    31  		f.pools = make([]*FakeDNSPoolElementConfig, 0, len(ipPools))
    32  		for _, ipPool := range ipPools {
    33  			_, ipNet, err := net.ParseCIDR(ipPool)
    34  			if err != nil {
    35  				return err
    36  			}
    37  			ones, bits := ipNet.Mask.Size()
    38  			sizeInBits := bits - ones
    39  			if sizeInBits > 16 { // At most 65536 ips for a IP pool
    40  				sizeInBits = 16
    41  			}
    42  			f.pools = append(f.pools, &FakeDNSPoolElementConfig{
    43  				IPPool:  ipPool,
    44  				LRUSize: (1 << sizeInBits) - 1,
    45  			})
    46  		}
    47  	default:
    48  		return newError("invalid fakedns config")
    49  	}
    50  	return nil
    51  }
    52  
    53  func (f *FakeDNSConfig) Build() (*fakedns.FakeDnsPoolMulti, error) {
    54  	fakeDNSPool := fakedns.FakeDnsPoolMulti{}
    55  
    56  	if f.pool != nil {
    57  		fakeDNSPool.Pools = append(fakeDNSPool.Pools, &fakedns.FakeDnsPool{
    58  			IpPool:  f.pool.IPPool,
    59  			LruSize: f.pool.LRUSize,
    60  		})
    61  		return &fakeDNSPool, nil
    62  	}
    63  
    64  	if f.pools != nil {
    65  		for _, v := range f.pools {
    66  			fakeDNSPool.Pools = append(fakeDNSPool.Pools, &fakedns.FakeDnsPool{IpPool: v.IPPool, LruSize: v.LRUSize})
    67  		}
    68  		return &fakeDNSPool, nil
    69  	}
    70  
    71  	return nil, newError("no valid FakeDNS config")
    72  }
    73  
    74  type FakeDNSConfigExtend struct { // Adds boolean value parsing for "fakedns" config
    75  	*FakeDNSConfig
    76  }
    77  
    78  func (f *FakeDNSConfigExtend) UnmarshalJSON(data []byte) error {
    79  	var enabled bool
    80  	if json.Unmarshal(data, &enabled) == nil {
    81  		if enabled {
    82  			f.FakeDNSConfig = &FakeDNSConfig{pools: []*FakeDNSPoolElementConfig{}}
    83  		}
    84  		return nil
    85  	}
    86  	return json.Unmarshal(data, &f.FakeDNSConfig)
    87  }