Fix match geoip

This commit is contained in:
世界 2023-02-07 12:20:47 +08:00
parent 86ea035bdd
commit 960d04d172
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
2 changed files with 40 additions and 21 deletions

View file

@ -4,7 +4,6 @@ import (
"net/netip"
E "github.com/sagernet/sing/common/exceptions"
N "github.com/sagernet/sing/common/network"
"github.com/oschwald/maxminddb-golang"
)
@ -31,8 +30,5 @@ func (r *Reader) Lookup(addr netip.Addr) string {
if code != "" {
return code
}
if !N.IsPublicAddr(addr) {
return "private"
}
return "unknown"
}

View file

@ -1,10 +1,12 @@
package route
import (
"net/netip"
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/log"
N "github.com/sagernet/sing/common/network"
)
var _ RuleItem = (*GeoIPItem)(nil)
@ -32,29 +34,50 @@ func NewGeoIPItem(router adapter.Router, logger log.ContextLogger, isSource bool
}
func (r *GeoIPItem) Match(metadata *adapter.InboundContext) bool {
geoReader := r.router.GeoIPReader()
if geoReader == nil {
return false
var geoipCode string
if r.isSource && metadata.SourceGeoIPCode != "" {
geoipCode = metadata.SourceGeoIPCode
} else if !r.isSource && metadata.GeoIPCode != "" {
geoipCode = metadata.GeoIPCode
}
if geoipCode != "" {
return r.codeMap[geoipCode]
}
var destination netip.Addr
if r.isSource {
if metadata.SourceGeoIPCode == "" {
metadata.SourceGeoIPCode = geoReader.Lookup(metadata.Source.Addr)
}
return r.codeMap[metadata.SourceGeoIPCode]
destination = metadata.Source.Addr
} else {
if metadata.Destination.IsIP() {
if metadata.GeoIPCode == "" {
metadata.GeoIPCode = geoReader.Lookup(metadata.Destination.Addr)
destination = metadata.Destination.Addr
}
return r.codeMap[metadata.GeoIPCode]
if destination.IsValid() {
return r.match(metadata, destination)
}
for _, address := range metadata.DestinationAddresses {
if r.codeMap[geoReader.Lookup(address)] {
for _, destinationAddress := range metadata.DestinationAddresses {
if r.match(metadata, destinationAddress) {
return true
}
}
return false
}
func (r *GeoIPItem) match(metadata *adapter.InboundContext, destination netip.Addr) bool {
var geoipCode string
geoReader := r.router.GeoIPReader()
if geoReader != nil {
geoipCode = geoReader.Lookup(destination)
}
if geoipCode == "" && !N.IsPublicAddr(destination) {
geoipCode = "private"
}
if geoipCode == "" {
return false
}
if r.isSource {
metadata.SourceGeoIPCode = geoipCode
} else {
metadata.GeoIPCode = geoipCode
}
return r.codeMap[geoipCode]
}
func (r *GeoIPItem) String() string {