You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-mitmproxy/proxy/flowencoding.go

120 lines
2.3 KiB
Go

2 years ago
package proxy
4 years ago
import (
"bytes"
"compress/flate"
4 years ago
"compress/gzip"
"errors"
"io"
4 years ago
"strconv"
"strings"
"github.com/andybalholm/brotli"
4 years ago
)
2 years ago
var errEncodingNotSupport = errors.New("content-encoding not support")
4 years ago
var textContentTypes = []string{
"text",
"javascript",
"json",
}
func (r *Response) IsTextContentType() bool {
contentType := r.Header.Get("Content-Type")
if contentType == "" {
return false
}
for _, substr := range textContentTypes {
if strings.Contains(contentType, substr) {
return true
}
}
return false
}
func (r *Response) DecodedBody() ([]byte, error) {
4 years ago
if r.decodedBody != nil {
return r.decodedBody, nil
4 years ago
}
if r.decodedErr != nil {
return nil, r.decodedErr
4 years ago
}
if r.Body == nil {
return nil, nil
4 years ago
}
if len(r.Body) == 0 {
r.decodedBody = r.Body
return r.decodedBody, nil
4 years ago
}
enc := r.Header.Get("Content-Encoding")
if enc == "" || enc == "identity" {
4 years ago
r.decodedBody = r.Body
return r.decodedBody, nil
4 years ago
}
2 years ago
decodedBody, decodedErr := decode(enc, r.Body)
if decodedErr != nil {
r.decodedErr = decodedErr
4 years ago
log.Error(r.decodedErr)
return nil, decodedErr
4 years ago
}
r.decodedBody = decodedBody
r.decoded = true
return r.decodedBody, nil
4 years ago
}
4 years ago
func (r *Response) ReplaceToDecodedBody() {
body, err := r.DecodedBody()
if err != nil || body == nil {
return
}
r.Body = body
4 years ago
r.Header.Del("Content-Encoding")
4 years ago
r.Header.Set("Content-Length", strconv.Itoa(len(body)))
r.Header.Del("Transfer-Encoding")
4 years ago
}
2 years ago
func decode(enc string, body []byte) ([]byte, error) {
4 years ago
if enc == "gzip" {
dreader, err := gzip.NewReader(bytes.NewReader(body))
4 years ago
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(make([]byte, 0))
_, err = io.Copy(buf, dreader)
4 years ago
if err != nil {
return nil, err
}
err = dreader.Close()
4 years ago
if err != nil {
return nil, err
}
return buf.Bytes(), nil
} else if enc == "br" {
dreader := brotli.NewReader(bytes.NewReader(body))
buf := bytes.NewBuffer(make([]byte, 0))
_, err := io.Copy(buf, dreader)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
} else if enc == "deflate" {
dreader := flate.NewReader(bytes.NewReader(body))
buf := bytes.NewBuffer(make([]byte, 0))
_, err := io.Copy(buf, dreader)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
4 years ago
}
2 years ago
return nil, errEncodingNotSupport
4 years ago
}