2024-03-12 03:14:25 +08:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/metacubex/mihomo/component/geodata"
|
|
|
|
"github.com/metacubex/mihomo/component/mmdb"
|
|
|
|
C "github.com/metacubex/mihomo/constant"
|
|
|
|
"github.com/metacubex/mihomo/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ASN struct {
|
|
|
|
*Base
|
|
|
|
asn string
|
|
|
|
adapter string
|
|
|
|
noResolveIP bool
|
2024-04-01 18:16:34 +08:00
|
|
|
isSourceIP bool
|
2024-03-12 03:14:25 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (a *ASN) Match(metadata *C.Metadata) (bool, string) {
|
|
|
|
ip := metadata.DstIP
|
2024-04-01 18:16:34 +08:00
|
|
|
if a.isSourceIP {
|
|
|
|
ip = metadata.SrcIP
|
|
|
|
}
|
2024-03-12 03:14:25 +08:00
|
|
|
if !ip.IsValid() {
|
|
|
|
return false, ""
|
|
|
|
}
|
|
|
|
|
|
|
|
result := mmdb.ASNInstance().LookupASN(ip.AsSlice())
|
|
|
|
asnNumber := strconv.FormatUint(uint64(result.AutonomousSystemNumber), 10)
|
2024-04-01 18:16:34 +08:00
|
|
|
if !a.isSourceIP {
|
|
|
|
metadata.DstIPASN = asnNumber + " " + result.AutonomousSystemOrganization
|
|
|
|
}
|
2024-03-12 03:14:25 +08:00
|
|
|
|
|
|
|
match := a.asn == asnNumber
|
|
|
|
return match, a.adapter
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *ASN) RuleType() C.RuleType {
|
2024-04-01 18:16:34 +08:00
|
|
|
if a.isSourceIP {
|
|
|
|
return C.SrcIPASN
|
|
|
|
}
|
2024-03-12 03:14:25 +08:00
|
|
|
return C.IPASN
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *ASN) Adapter() string {
|
|
|
|
return a.adapter
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *ASN) Payload() string {
|
|
|
|
return a.asn
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *ASN) ShouldResolveIP() bool {
|
|
|
|
return !a.noResolveIP
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *ASN) GetASN() string {
|
|
|
|
return a.asn
|
|
|
|
}
|
|
|
|
|
2024-04-01 18:16:34 +08:00
|
|
|
func NewIPASN(asn string, adapter string, isSrc, noResolveIP bool) (*ASN, error) {
|
2024-03-12 03:14:25 +08:00
|
|
|
C.ASNEnable = true
|
|
|
|
if err := geodata.InitASN(); err != nil {
|
|
|
|
log.Errorln("can't initial ASN: %s", err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &ASN{
|
|
|
|
Base: &Base{},
|
|
|
|
asn: asn,
|
|
|
|
adapter: adapter,
|
|
|
|
noResolveIP: noResolveIP,
|
2024-04-01 18:16:34 +08:00
|
|
|
isSourceIP: isSrc,
|
2024-03-12 03:14:25 +08:00
|
|
|
}, nil
|
|
|
|
}
|