new: now request object can be changed during OnRequest handlers (closes #135)

This commit is contained in:
evilsocket 2018-03-05 16:48:45 +01:00
parent cb58258bd7
commit 07fe790ad1
3 changed files with 111 additions and 34 deletions

View file

@ -24,7 +24,10 @@ type JSRequest struct {
ContentType string
Headers []JSHeader
Body string
req *http.Request
req *http.Request
refHash string
bodyRead bool
}
func NewJSRequest(req *http.Request) *JSRequest {
@ -41,7 +44,7 @@ func NewJSRequest(req *http.Request) *JSRequest {
}
}
return &JSRequest{
jreq := &JSRequest{
Client: strings.Split(req.RemoteAddr, ":")[0],
Method: req.Method,
Version: fmt.Sprintf("%d.%d", req.ProtoMajor, req.ProtoMinor),
@ -51,8 +54,38 @@ func NewJSRequest(req *http.Request) *JSRequest {
ContentType: cType,
Headers: headers,
req: req,
req: req,
bodyRead: false,
}
jreq.UpdateHash()
return jreq
}
func (j *JSRequest) NewHash() string {
hash := fmt.Sprintf("%s.%s.%s.%s.%s.%s.%s", j.Client, j.Method, j.Version, j.Hostname, j.Path, j.Query, j.ContentType)
for _, h := range j.Headers {
hash += fmt.Sprintf(".%s-%s", h.Name, h.Value)
}
hash += "." + j.Body
return hash
}
func (j *JSRequest) UpdateHash() {
j.refHash = j.NewHash()
}
func (j *JSRequest) WasModified() bool {
// body was read
if j.bodyRead == true {
return true
}
// check if any of the fields has been changed
newHash := j.NewHash()
if newHash != j.refHash {
return true
}
return false
}
func (j *JSRequest) ReadBody() string {
@ -62,6 +95,7 @@ func (j *JSRequest) ReadBody() string {
}
j.Body = string(raw)
j.bodyRead = true
// reset the request body to the original unread state
j.req.Body = ioutil.NopCloser(bytes.NewBuffer(raw))
@ -90,3 +124,26 @@ func (j *JSRequest) ParseForm() map[string]string {
return form
}
func (j *JSRequest) ToRequest() (req *http.Request) {
url := fmt.Sprintf("%s://%s:%s%s?%s", j.req.URL.Scheme, j.Hostname, j.req.URL.Port(), j.Path, j.Query)
if j.Body == "" {
req, _ = http.NewRequest(j.Method, url, j.req.Body)
} else {
req, _ = http.NewRequest(j.Method, url, strings.NewReader(j.Body))
}
hadType := false
for _, h := range j.Headers {
req.Header.Set(h.Name, h.Value)
if h.Name == "Content-Type" {
hadType = true
}
}
if hadType == false && j.ContentType != "" {
req.Header.Set("Content-Type", j.ContentType)
}
return
}