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

63 lines
1.5 KiB
Go
Raw Normal View History

2020-10-08 15:06:42 +08:00
package utils
import (
"fmt"
2020-11-21 21:43:03 +08:00
"github.com/TeaOSLab/EdgeNode/internal/ttlcache"
2020-10-08 15:06:42 +08:00
"github.com/TeaOSLab/EdgeNode/internal/utils"
"github.com/dchest/siphash"
2020-11-21 21:43:03 +08:00
"github.com/iwind/TeaGo/types"
2020-10-08 15:06:42 +08:00
"regexp"
"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 grid = grids.NewGrid(32, grids.NewLimitCountOpt(1000_0000))
var cache = ttlcache.NewCache()
2020-10-08 15:06:42 +08:00
// 正则表达式匹配字符串,并缓存结果
func MatchStringCache(regex *regexp.Regexp, s string) bool {
// 如果长度超过4096大概率是不能重用的
if len(s) > 4096 {
return regex.MatchString(s)
}
hash := siphash.Hash(0, 0, utils.UnsafeStringToBytes(s))
2020-11-21 21:43:03 +08:00
key := fmt.Sprintf("%p_", regex) + strconv.FormatUint(hash, 10)
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
}
b := regex.MatchString(s)
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
}
// 正则表达式匹配字节slice并缓存结果
func MatchBytesCache(regex *regexp.Regexp, byteSlice []byte) bool {
// 如果长度超过4096大概率是不能重用的
if len(byteSlice) > 4096 {
return regex.Match(byteSlice)
}
hash := siphash.Hash(0, 0, byteSlice)
2020-11-21 21:43:03 +08:00
key := fmt.Sprintf("%p_", regex) + strconv.FormatUint(hash, 10)
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
}
b := regex.Match(byteSlice)
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
}