Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: improve GetField logic #897

Merged
merged 4 commits into from
Nov 2, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 15 additions & 17 deletions internal/corazawaf/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -561,29 +561,27 @@ func (tx *Transaction) GetField(rv ruleVariableParams) []types.MatchData {
matches = col.FindAll()
}

var rmi []int
for i, c := range matches {
// in the most common scenario filteredMatches length will be
// the same as matches length, so we avoid allocating per result
filteredMatches := make([]types.MatchData, len(matches))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Think it's good to use make([], 0, len) and append since it basically allows Go to take care of the filteredCount variable while still preallocating

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done!

filteredCount := 0

for _, c := range matches {
isException := false
lkey := strings.ToLower(c.Key())
for _, ex := range rv.Exceptions {
lkey := strings.ToLower(c.Key())
// in case it matches the regex or the keyStr
// Since keys are case sensitive we need to check with lower case
if (ex.KeyRx != nil && ex.KeyRx.MatchString(lkey)) || strings.ToLower(ex.KeyStr) == lkey {
// we remove the exception from the list of values
// we tried with standard append, but it fails... let's do some hacking
// m2 := append(matches[:i], matches[i+1:]...)
rmi = append(rmi, i)
isException = true
break
}
}
}
// we read the list of indexes backwards
// then we remove each one of them because of the exceptions
for i := len(rmi) - 1; i >= 0; i-- {
if len(matches) < rmi[i]+1 {
matches = matches[:rmi[i]-1]
} else {
matches = append(matches[:rmi[i]], matches[rmi[i]+1:]...)
if !isException {
filteredMatches[filteredCount] = c
filteredCount++
}
}
matches = filteredMatches[:filteredCount]

if rv.Count {
count := len(matches)
matches = []types.MatchData{
Expand Down
Loading