Skip to content
This repository was archived by the owner on Nov 5, 2024. It is now read-only.

Commit 72309a6

Browse files
committed
[waf]改进正则表达式缓存
1 parent 41248be commit 72309a6

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

teawaf/utils/utils.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ var grid = teamemory.NewGrid(32, teamemory.NewLimitCountOpt(1000_0000))
1313

1414
// 正则表达式匹配字符串,并缓存结果
1515
func MatchStringCache(regex *regexp.Regexp, s string) bool {
16+
// 如果长度超过4096,大概率是不能重用的
17+
if len(s) > 4096 {
18+
return regex.MatchString(s)
19+
}
20+
1621
hash := siphash.Hash(0, 0, teautils.UnsafeStringToBytes(s))
1722
key := []byte(fmt.Sprintf("%p_", regex) + strconv.FormatUint(hash, 10))
1823
item := grid.Read(key)
@@ -30,6 +35,11 @@ func MatchStringCache(regex *regexp.Regexp, s string) bool {
3035

3136
// 正则表达式匹配字节slice,并缓存结果
3237
func MatchBytesCache(regex *regexp.Regexp, byteSlice []byte) bool {
38+
// 如果长度超过4096,大概率是不能重用的
39+
if len(byteSlice) > 4096 {
40+
return regex.Match(byteSlice)
41+
}
42+
3343
hash := siphash.Hash(0, 0, byteSlice)
3444
key := []byte(fmt.Sprintf("%p_", regex) + strconv.FormatUint(hash, 10))
3545
item := grid.Read(key)

teawaf/utils/utils_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ func TestMatchBytesCache(t *testing.T) {
2121
}
2222

2323
func BenchmarkMatchStringCache(b *testing.B) {
24-
data := strings.Repeat("HELLO", 1024*4)
24+
data := strings.Repeat("HELLO", 512)
2525
regex := regexp.MustCompile(`(?iU)\b(eval|system|exec|execute|passthru|shell_exec|phpinfo)\b`)
2626

2727
for i := 0; i < b.N; i++ {
@@ -30,7 +30,7 @@ func BenchmarkMatchStringCache(b *testing.B) {
3030
}
3131

3232
func BenchmarkMatchStringCache_WithoutCache(b *testing.B) {
33-
data := strings.Repeat("HELLO", 1024*4)
33+
data := strings.Repeat("HELLO", 512)
3434
regex := regexp.MustCompile(`(?iU)\b(eval|system|exec|execute|passthru|shell_exec|phpinfo)\b`)
3535

3636
for i := 0; i < b.N; i++ {

0 commit comments

Comments
 (0)