Files
EdgeNode/internal/waf/utils/utils.go

68 lines
1.5 KiB
Go
Raw Normal View History

2020-10-08 15:06:42 +08:00
package utils
import (
"github.com/TeaOSLab/EdgeNode/internal/re"
2020-11-21 21:43:03 +08:00
"github.com/TeaOSLab/EdgeNode/internal/ttlcache"
2020-11-21 22:29:57 +08:00
"github.com/cespare/xxhash"
2020-11-21 21:43:03 +08:00
"github.com/iwind/TeaGo/types"
2020-10-08 15:06:42 +08:00
"strconv"
2020-11-21 21:43:03 +08:00
"time"
2020-10-08 15:06:42 +08:00
)
2020-11-21 21:43:03 +08:00
var cache = ttlcache.NewCache()
2020-10-08 15:06:42 +08:00
// MatchStringCache 正则表达式匹配字符串,并缓存结果
func MatchStringCache(regex *re.Regexp, s string) bool {
if regex == nil {
return false
}
2020-10-08 15:06:42 +08:00
// 如果长度超过4096大概率是不能重用的
if len(s) > 4096 {
return regex.MatchString(s)
}
2022-04-04 18:25:54 +08:00
var hash = xxhash.Sum64String(s)
var key = regex.IdString() + "@" + strconv.FormatUint(hash, 10)
var item = cache.Read(key)
2020-10-08 15:06:42 +08:00
if item != nil {
2020-11-21 21:43:03 +08:00
return types.Int8(item.Value) == 1
2020-10-08 15:06:42 +08:00
}
2022-04-04 18:25:54 +08:00
var b = regex.MatchString(s)
2020-10-08 15:06:42 +08:00
if b {
2020-11-21 21:43:03 +08:00
cache.Write(key, 1, time.Now().Unix()+1800)
2020-10-08 15:06:42 +08:00
} else {
2020-11-21 21:43:03 +08:00
cache.Write(key, 0, time.Now().Unix()+1800)
2020-10-08 15:06:42 +08:00
}
return b
}
// MatchBytesCache 正则表达式匹配字节slice并缓存结果
func MatchBytesCache(regex *re.Regexp, byteSlice []byte) bool {
if regex == nil {
return false
}
2020-10-08 15:06:42 +08:00
// 如果长度超过4096大概率是不能重用的
if len(byteSlice) > 4096 {
return regex.Match(byteSlice)
}
2022-04-04 18:25:54 +08:00
var hash = xxhash.Sum64(byteSlice)
var key = regex.IdString() + "@" + strconv.FormatUint(hash, 10)
var item = cache.Read(key)
2020-10-08 15:06:42 +08:00
if item != nil {
2020-11-21 21:43:03 +08:00
return types.Int8(item.Value) == 1
}
if item != nil {
return types.Int8(item.Value) == 1
2020-10-08 15:06:42 +08:00
}
2022-04-04 18:25:54 +08:00
var b = regex.Match(byteSlice)
2020-10-08 15:06:42 +08:00
if b {
2020-11-21 21:43:03 +08:00
cache.Write(key, 1, time.Now().Unix()+1800)
2020-10-08 15:06:42 +08:00
} else {
2020-11-21 21:43:03 +08:00
cache.Write(key, 0, time.Now().Unix()+1800)
2020-10-08 15:06:42 +08:00
}
return b
}