Fix array out of bounds during using http-set-header (#627)

Happens for example when payload stops at a '-' and we are searching for
Accept-Encoding.The method has been simplified and now does full case
insensitivity. Performance checking, on x64, it is ever so slightly
faster than the original.
This commit is contained in:
bruce34
2019-02-16 09:49:29 +01:00
committed by Leonid Bugaev
parent 279aa3fc3f
commit 84e99a8bb0
+5 -69
View File
@@ -42,87 +42,23 @@ func MIMEHeadersStartPos(payload []byte) int {
return bytes.Index(payload, CLRF) + 2 // Find first line end
}
func isLower(b byte) bool {
if 'a' <= b && b <= 'z' {
return true
}
return false
}
func toUpper(b byte) byte {
if 'a' <= b && b <= 'z' {
b -= 'a' - 'A'
}
return b
}
func toLower(b byte) byte {
if 'A' <= b && b <= 'Z' {
b += 'a' - 'A'
}
return b
}
func headerIndex(payload []byte, name []byte) int {
isLower := isLower(name[0])
i := 0
for {
if i >= len(payload) {
// we need enough space for at least '\n' and the header name
if i >= (len(payload) - len(name) - 1) {
return -1
}
if payload[i] == '\n' {
i++
// We are at the end
if i == len(payload) {
return -1
}
if payload[i] == name[0] ||
(!isLower && payload[i] == toLower(name[0])) ||
(isLower && payload[i] == toUpper(name[0])) {
i++
j := 1
for {
if j == len(name) {
// Matched, and return start of the header
return i - len(name)
}
// We are at the end
if i == len(payload) {
return -1
}
if payload[i] != name[j] {
break
}
// If compound header name do one more case check: Content-Length or Transfer-Encoding
if name[j] == '-' {
i++
j++
if !(payload[i] == name[j] ||
(!isLower && payload[i] == toLower(name[j])) ||
(isLower && payload[i] == toUpper(name[j]))) {
break
}
}
j++
i++
}
if bytes.EqualFold(name, payload[i:i+len(name)]) {
return i
}
}
i++
}
}
return -1
}