Skip to content

Commit

Permalink
chore: Increase support for other format of ASN
Browse files Browse the repository at this point in the history
  • Loading branch information
xishang0128 committed Nov 4, 2024
1 parent 3e966e8 commit a86c562
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
26 changes: 21 additions & 5 deletions component/mmdb/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net"
"strings"

"github.com/metacubex/mihomo/log"
"github.com/oschwald/maxminddb-golang"
)

Expand All @@ -23,11 +24,16 @@ type ASNReader struct {
*maxminddb.Reader
}

type ASNResult struct {
type GeoLite2 struct {
AutonomousSystemNumber uint32 `maxminddb:"autonomous_system_number"`
AutonomousSystemOrganization string `maxminddb:"autonomous_system_organization"`
}

type IPInfo struct {
ASN string `maxminddb:"asn"`
Name string `maxminddb:"name"`
}

func (r IPReader) LookupCode(ipAddress net.IP) []string {
switch r.databaseType {
case typeMaxmind:
Expand Down Expand Up @@ -66,8 +72,18 @@ func (r IPReader) LookupCode(ipAddress net.IP) []string {
}
}

func (r ASNReader) LookupASN(ip net.IP) ASNResult {
var result ASNResult
r.Lookup(ip, &result)
return result
func (r ASNReader) LookupASN(ip net.IP) (string, string) {
switch r.Metadata.DatabaseType {
case "GeoLite2-ASN", "DBIP-ASN-Lite (compat=GeoLite2-ASN)":
var result GeoLite2
_ = r.Lookup(ip, &result)
return fmt.Sprint(result.AutonomousSystemNumber), result.AutonomousSystemOrganization
case "ipinfo generic_asn_free.mmdb":
var result IPInfo
_ = r.Lookup(ip, &result)
return result.ASN[2:], result.Name
default:
log.Warnln("Unsupported ASN type: %s", r.Metadata.DatabaseType)
}
return "", ""
}
13 changes: 4 additions & 9 deletions rules/common/ipasn.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package common

import (
"strconv"

"github.com/metacubex/mihomo/component/geodata"
"github.com/metacubex/mihomo/component/mmdb"
C "github.com/metacubex/mihomo/constant"
Expand All @@ -26,17 +24,14 @@ func (a *ASN) Match(metadata *C.Metadata) (bool, string) {
return false, ""
}

result := mmdb.ASNInstance().LookupASN(ip.AsSlice())
asnNumber := strconv.FormatUint(uint64(result.AutonomousSystemNumber), 10)
ipASN := asnNumber + " " + result.AutonomousSystemOrganization
asn, aso := mmdb.ASNInstance().LookupASN(ip.AsSlice())
if a.isSourceIP {
metadata.SrcIPASN = ipASN
metadata.SrcIPASN = asn + " " + aso
} else {
metadata.DstIPASN = ipASN
metadata.DstIPASN = asn + " " + aso
}

match := a.asn == asnNumber
return match, a.adapter
return a.asn == asn, a.adapter
}

func (a *ASN) RuleType() C.RuleType {
Expand Down

0 comments on commit a86c562

Please # to comment.