diff --git a/internal/events/events.go b/internal/events/events.go index 2b2f827e..255266e1 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -5,4 +5,6 @@ type Event = string const ( EventStart Event = "start" // start loading EventQuit Event = "quit" // quit node gracefully + + EventSecurityConfigChanged Event = "securityConfigChanged" // 安全设置变更 ) diff --git a/internal/securitymanager/security_config.go b/internal/securitymanager/security_config.go index dca9f0bd..ca24342e 100644 --- a/internal/securitymanager/security_config.go +++ b/internal/securitymanager/security_config.go @@ -2,6 +2,7 @@ package securitymanager import ( "encoding/json" + "github.com/TeaOSLab/EdgeAdmin/internal/events" "github.com/TeaOSLab/EdgeAdmin/internal/rpc" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" "github.com/iwind/TeaGo/logs" @@ -61,6 +62,10 @@ func UpdateSecurityConfig(securityConfig *SecurityConfig) error { return err } sharedSecurityConfig = securityConfig + + // 通知更新 + events.Notify(events.EventSecurityConfigChanged) + return nil } diff --git a/internal/web/helpers/utils.go b/internal/web/helpers/utils.go index 6eb10c37..420cf7e6 100644 --- a/internal/web/helpers/utils.go +++ b/internal/web/helpers/utils.go @@ -1,16 +1,52 @@ package helpers import ( + "github.com/TeaOSLab/EdgeAdmin/internal/events" nodes "github.com/TeaOSLab/EdgeAdmin/internal/rpc" "github.com/TeaOSLab/EdgeAdmin/internal/securitymanager" "github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb" "github.com/iwind/TeaGo/lists" "github.com/iwind/TeaGo/logs" "net" + "sync" ) -// 检查用户IP +var ipCacheMap = map[string]bool{} // ip => bool +var ipCacheLocker = sync.Mutex{} + +func init() { + events.On(events.EventSecurityConfigChanged, func() { + ipCacheLocker.Lock() + ipCacheMap = map[string]bool{} + ipCacheLocker.Unlock() + }) +} + +// 检查用户IP并支持缓存 func checkIP(config *securitymanager.SecurityConfig, ipAddr string) bool { + ipCacheLocker.Lock() + ipCache, ok := ipCacheMap[ipAddr] + if ok && ipCache { + ipCacheLocker.Unlock() + return ipCache + } + ipCacheLocker.Unlock() + + result := checkIPWithoutCache(config, ipAddr) + ipCacheLocker.Lock() + + // 缓存的内容不能过多 + if len(ipCacheMap) > 100_000 { + ipCacheMap = map[string]bool{} + } + + ipCacheMap[ipAddr] = result + ipCacheLocker.Unlock() + return result +} + +// 检查用户IP +func checkIPWithoutCache(config *securitymanager.SecurityConfig, ipAddr string) bool { if config == nil { return true }