nuclei/pkg/protocols/offlinehttp/read_response.go
Tarun Koyalwar dc44105baf
nuclei v3 : misc updates (#4247)
* use parsed options while signing

* update project layout to v3

* fix .gitignore

* remove example template

* misc updates

* bump tlsx version

* hide template sig warning with env

* js: retain value while using log

* fix nil pointer derefernce

* misc doc update

---------

Co-authored-by: sandeep <8293321+ehsandeep@users.noreply.github.com>
2023-10-17 17:44:13 +05:30

53 lines
1.5 KiB
Go

package offlinehttp
import (
"bufio"
"errors"
"net/http"
"regexp"
"strings"
)
var noMinor = regexp.MustCompile(`HTTP/([0-9]) `)
// readResponseFromString reads a raw http response from a string.
func readResponseFromString(data string) (*http.Response, error) {
// Check if "data" contains RFC compatible Request followed by a response
br := bufio.NewReader(strings.NewReader(data))
if req, err := http.ReadRequest(br); err == nil {
if resp, err := http.ReadResponse(br, req); err == nil {
return resp, nil
}
}
// otherwise tries to patch known cases such as http minor version
var final string
if strings.HasPrefix(data, "HTTP/") {
final = addMinorVersionToHTTP(data)
} else {
lastIndex := strings.LastIndex(data, "HTTP/")
if lastIndex == -1 {
return nil, errors.New("malformed raw http response")
}
final = data[lastIndex:] // choose last http/ in case of it being later.
final = addMinorVersionToHTTP(final)
}
return http.ReadResponse(bufio.NewReader(strings.NewReader(final)), nil)
}
// addMinorVersionToHTTP tries to add a minor version to http status header
// fixing the compatibility issue with go standard library.
func addMinorVersionToHTTP(data string) string {
matches := noMinor.FindAllStringSubmatch(data, 1)
if len(matches) == 0 {
return data
}
if len(matches[0]) < 2 {
return data
}
replacedVersion := strings.Replace(matches[0][0], matches[0][1], matches[0][1]+".0", 1)
data = strings.Replace(data, matches[0][0], replacedVersion, 1)
return data
}