优化WAF正则表达式缓存时间

This commit is contained in:
GoEdgeLab
2023-10-11 12:21:10 +08:00
parent ceb0c31cd0
commit bf68c29fa5
49 changed files with 368 additions and 124 deletions

View File

@@ -3,21 +3,34 @@ package utils
import (
"github.com/TeaOSLab/EdgeNode/internal/re"
"github.com/TeaOSLab/EdgeNode/internal/ttlcache"
"github.com/TeaOSLab/EdgeNode/internal/utils/fasttime"
"github.com/cespare/xxhash"
"strconv"
"time"
)
var cache = ttlcache.NewCache[int8]()
const (
maxCacheDataSize = 1024
)
type CacheLife = int64
const (
CacheDisabled CacheLife = 0
CacheShortLife CacheLife = 600
CacheMiddleLife CacheLife = 1800
CacheLongLife CacheLife = 7200
)
// MatchStringCache 正则表达式匹配字符串,并缓存结果
func MatchStringCache(regex *re.Regexp, s string) bool {
func MatchStringCache(regex *re.Regexp, s string, cacheLife CacheLife) bool {
if regex == nil {
return false
}
// 如果长度超过4096,大概率是不能重用的
if len(s) > 4096 {
// 如果长度超过一定数量,大概率是不能重用的
if cacheLife <= 0 || len(s) > maxCacheDataSize {
return regex.MatchString(s)
}
@@ -29,21 +42,21 @@ func MatchStringCache(regex *re.Regexp, s string) bool {
}
var b = regex.MatchString(s)
if b {
cache.Write(key, 1, time.Now().Unix()+1800)
cache.Write(key, 1, fasttime.Now().Unix()+cacheLife)
} else {
cache.Write(key, 0, time.Now().Unix()+1800)
cache.Write(key, 0, fasttime.Now().Unix()+cacheLife)
}
return b
}
// MatchBytesCache 正则表达式匹配字节slice并缓存结果
func MatchBytesCache(regex *re.Regexp, byteSlice []byte) bool {
func MatchBytesCache(regex *re.Regexp, byteSlice []byte, cacheLife CacheLife) bool {
if regex == nil {
return false
}
// 如果长度超过4096,大概率是不能重用的
if len(byteSlice) > 4096 {
// 如果长度超过一定数量,大概率是不能重用的
if cacheLife <= 0 || len(byteSlice) > maxCacheDataSize {
return regex.Match(byteSlice)
}
@@ -58,9 +71,9 @@ func MatchBytesCache(regex *re.Regexp, byteSlice []byte) bool {
}
var b = regex.Match(byteSlice)
if b {
cache.Write(key, 1, time.Now().Unix()+1800)
cache.Write(key, 1, fasttime.Now().Unix()+cacheLife)
} else {
cache.Write(key, 0, time.Now().Unix()+1800)
cache.Write(key, 0, fasttime.Now().Unix()+cacheLife)
}
return b
}