2022-07-02 22:55:10 +08:00
|
|
|
package route
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/adapter"
|
|
|
|
"github.com/sagernet/sing-box/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
var _ RuleItem = (*GeoIPItem)(nil)
|
|
|
|
|
|
|
|
type GeoIPItem struct {
|
|
|
|
router adapter.Router
|
2022-07-12 15:17:29 +08:00
|
|
|
logger log.ContextLogger
|
2022-07-02 22:55:10 +08:00
|
|
|
isSource bool
|
|
|
|
codes []string
|
|
|
|
codeMap map[string]bool
|
|
|
|
}
|
|
|
|
|
2022-07-12 15:17:29 +08:00
|
|
|
func NewGeoIPItem(router adapter.Router, logger log.ContextLogger, isSource bool, codes []string) *GeoIPItem {
|
2022-07-02 22:55:10 +08:00
|
|
|
codeMap := make(map[string]bool)
|
|
|
|
for _, code := range codes {
|
|
|
|
codeMap[code] = true
|
|
|
|
}
|
|
|
|
return &GeoIPItem{
|
|
|
|
router: router,
|
|
|
|
logger: logger,
|
|
|
|
codes: codes,
|
|
|
|
isSource: isSource,
|
|
|
|
codeMap: codeMap,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *GeoIPItem) Match(metadata *adapter.InboundContext) bool {
|
|
|
|
geoReader := r.router.GeoIPReader()
|
|
|
|
if geoReader == nil {
|
2022-07-07 23:36:32 +08:00
|
|
|
return false
|
2022-07-02 22:55:10 +08:00
|
|
|
}
|
|
|
|
if r.isSource {
|
|
|
|
if metadata.SourceGeoIPCode == "" {
|
2022-07-05 13:23:47 +08:00
|
|
|
metadata.SourceGeoIPCode = geoReader.Lookup(metadata.Source.Addr)
|
2022-07-02 22:55:10 +08:00
|
|
|
}
|
2022-07-03 15:57:09 +08:00
|
|
|
return r.codeMap[metadata.SourceGeoIPCode]
|
|
|
|
} else {
|
2022-07-07 23:36:32 +08:00
|
|
|
if metadata.Destination.IsIP() {
|
|
|
|
if metadata.GeoIPCode == "" {
|
|
|
|
metadata.GeoIPCode = geoReader.Lookup(metadata.Destination.Addr)
|
|
|
|
}
|
|
|
|
return r.codeMap[metadata.GeoIPCode]
|
2022-07-03 15:57:09 +08:00
|
|
|
}
|
2022-07-07 23:36:32 +08:00
|
|
|
for _, address := range metadata.DestinationAddresses {
|
|
|
|
if r.codeMap[geoReader.Lookup(address)] {
|
|
|
|
return true
|
2022-07-03 15:57:09 +08:00
|
|
|
}
|
2022-07-02 22:55:10 +08:00
|
|
|
}
|
2022-07-07 23:36:32 +08:00
|
|
|
return false
|
2022-07-02 22:55:10 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *GeoIPItem) String() string {
|
|
|
|
var description string
|
|
|
|
if r.isSource {
|
|
|
|
description = "source_geoip="
|
|
|
|
} else {
|
|
|
|
description = "geoip="
|
|
|
|
}
|
|
|
|
cLen := len(r.codes)
|
|
|
|
if cLen == 1 {
|
|
|
|
description += r.codes[0]
|
|
|
|
} else if cLen > 3 {
|
|
|
|
description += "[" + strings.Join(r.codes[:3], " ") + "...]"
|
|
|
|
} else {
|
|
|
|
description += "[" + strings.Join(r.codes, " ") + "]"
|
|
|
|
}
|
|
|
|
return description
|
|
|
|
}
|