github.com/metacubex/mihomo@v1.18.5/rules/common/ipasn.go (about)

     1  package common
     2  
     3  import (
     4  	"strconv"
     5  
     6  	"github.com/metacubex/mihomo/component/geodata"
     7  	"github.com/metacubex/mihomo/component/mmdb"
     8  	C "github.com/metacubex/mihomo/constant"
     9  	"github.com/metacubex/mihomo/log"
    10  )
    11  
    12  type ASN struct {
    13  	*Base
    14  	asn         string
    15  	adapter     string
    16  	noResolveIP bool
    17  	isSourceIP  bool
    18  }
    19  
    20  func (a *ASN) Match(metadata *C.Metadata) (bool, string) {
    21  	ip := metadata.DstIP
    22  	if a.isSourceIP {
    23  		ip = metadata.SrcIP
    24  	}
    25  	if !ip.IsValid() {
    26  		return false, ""
    27  	}
    28  
    29  	result := mmdb.ASNInstance().LookupASN(ip.AsSlice())
    30  	asnNumber := strconv.FormatUint(uint64(result.AutonomousSystemNumber), 10)
    31  	if !a.isSourceIP {
    32  		metadata.DstIPASN = asnNumber + " " + result.AutonomousSystemOrganization
    33  	}
    34  
    35  	match := a.asn == asnNumber
    36  	return match, a.adapter
    37  }
    38  
    39  func (a *ASN) RuleType() C.RuleType {
    40  	if a.isSourceIP {
    41  		return C.SrcIPASN
    42  	}
    43  	return C.IPASN
    44  }
    45  
    46  func (a *ASN) Adapter() string {
    47  	return a.adapter
    48  }
    49  
    50  func (a *ASN) Payload() string {
    51  	return a.asn
    52  }
    53  
    54  func (a *ASN) ShouldResolveIP() bool {
    55  	return !a.noResolveIP
    56  }
    57  
    58  func (a *ASN) GetASN() string {
    59  	return a.asn
    60  }
    61  
    62  func NewIPASN(asn string, adapter string, isSrc, noResolveIP bool) (*ASN, error) {
    63  	C.ASNEnable = true
    64  	if err := geodata.InitASN(); err != nil {
    65  		log.Errorln("can't initial ASN: %s", err)
    66  		return nil, err
    67  	}
    68  
    69  	return &ASN{
    70  		Base:        &Base{},
    71  		asn:         asn,
    72  		adapter:     adapter,
    73  		noResolveIP: noResolveIP,
    74  		isSourceIP:  isSrc,
    75  	}, nil
    76  }