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.

104 lines
2.3 KiB
Go

4 years ago
package addon
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
"strings"
4 years ago
"unicode"
4 years ago
2 years ago
"github.com/lqqyt2423/go-mitmproxy/proxy"
log "github.com/sirupsen/logrus"
4 years ago
)
type Dumper struct {
2 years ago
proxy.BaseAddon
out io.Writer
4 years ago
level int // 0: header 1: header + body
4 years ago
}
2 years ago
func NewDumper(out io.Writer, level int) *Dumper {
4 years ago
if level != 0 && level != 1 {
level = 0
}
2 years ago
return &Dumper{out: out, level: level}
}
func NewDumperWithFilename(filename string, level int) *Dumper {
out, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(err)
}
return NewDumper(out, level)
}
4 years ago
2 years ago
func (d *Dumper) Requestheaders(f *proxy.Flow) {
go func() {
<-f.Done()
d.dump(f)
}()
4 years ago
}
4 years ago
// call when <-f.Done()
2 years ago
func (d *Dumper) dump(f *proxy.Flow) {
4 years ago
// 参考 httputil.DumpRequest
4 years ago
log := log.WithField("in", "Dumper")
4 years ago
buf := bytes.NewBuffer(make([]byte, 0))
fmt.Fprintf(buf, "%s %s %s\r\n", f.Request.Method, f.Request.URL.RequestURI(), f.Request.Proto)
fmt.Fprintf(buf, "Host: %s\r\n", f.Request.URL.Host)
if len(f.Request.Raw().TransferEncoding) > 0 {
fmt.Fprintf(buf, "Transfer-Encoding: %s\r\n", strings.Join(f.Request.Raw().TransferEncoding, ","))
}
if f.Request.Raw().Close {
fmt.Fprintf(buf, "Connection: close\r\n")
}
4 years ago
4 years ago
err := f.Request.Header.WriteSubset(buf, nil)
if err != nil {
log.Error(err)
}
buf.WriteString("\r\n")
4 years ago
2 years ago
if d.level == 1 && f.Request.Body != nil && len(f.Request.Body) > 0 && canPrint(f.Request.Body) {
4 years ago
buf.Write(f.Request.Body)
buf.WriteString("\r\n\r\n")
}
4 years ago
4 years ago
if f.Response != nil {
fmt.Fprintf(buf, "%v %v %v\r\n", f.Request.Proto, f.Response.StatusCode, http.StatusText(f.Response.StatusCode))
err = f.Response.Header.WriteSubset(buf, nil)
4 years ago
if err != nil {
log.Error(err)
}
buf.WriteString("\r\n")
if d.level == 1 && f.Response.Body != nil && len(f.Response.Body) > 0 && f.Response.IsTextContentType() {
body, err := f.Response.DecodedBody()
if err == nil && body != nil && len(body) > 0 {
4 years ago
buf.Write(body)
buf.WriteString("\r\n\r\n")
4 years ago
}
4 years ago
}
4 years ago
}
4 years ago
4 years ago
buf.WriteString("\r\n\r\n")
4 years ago
2 years ago
_, err = d.out.Write(buf.Bytes())
4 years ago
if err != nil {
log.Error(err)
}
}
2 years ago
func canPrint(content []byte) bool {
4 years ago
for _, c := range string(content) {
if !unicode.IsPrint(c) && !unicode.IsSpace(c) {
return false
}
}
return true
}