From 0848dd8a2825c39b763ff6b7e2911d2a4160f59d Mon Sep 17 00:00:00 2001 From: lqqyt2423 <974923609@qq.com> Date: Thu, 20 Jan 2022 13:10:14 +0800 Subject: [PATCH] fix bug: socket not close when connection finished --- cmd/go-mitmproxy/main.go | 7 +++++++ proxy/helper.go | 15 +++++---------- proxy/proxy.go | 8 ++++---- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/cmd/go-mitmproxy/main.go b/cmd/go-mitmproxy/main.go index f6de2fd..de2621d 100644 --- a/cmd/go-mitmproxy/main.go +++ b/cmd/go-mitmproxy/main.go @@ -3,6 +3,9 @@ package main import ( "flag" "fmt" + + // slog "log" + "os" "github.com/lqqyt2423/go-mitmproxy/addon" @@ -50,6 +53,10 @@ func main() { os.Exit(0) } + // for debug + // slog.SetFlags(slog.LstdFlags | slog.Lshortfile) + // log.SetReportCaller(true) + log.SetLevel(log.InfoLevel) log.SetReportCaller(false) log.SetOutput(os.Stdout) diff --git a/proxy/helper.go b/proxy/helper.go index aa8e725..ffe8d82 100644 --- a/proxy/helper.go +++ b/proxy/helper.go @@ -18,6 +18,7 @@ var NormalErrMsgs []string = []string{ "io: read/write on closed pipe", "connect: connection refused", "connect: connection reset by peer", + "use of closed network connection", } // 仅打印预料之外的错误信息 @@ -39,20 +40,14 @@ func LogErr(log *_log.Entry, err error) (loged bool) { // 转发流量 // Read a => Write b // Read b => Write a -func Transfer(log *_log.Entry, a, b io.ReadWriter) { +func Transfer(log *_log.Entry, a, b io.ReadWriteCloser) { done := make(chan struct{}) defer close(done) - forward := func(dst io.Writer, src io.Reader, ec chan<- error) { + forward := func(dst io.WriteCloser, src io.Reader, ec chan<- error) { _, err := io.Copy(dst, src) - if err != nil { - select { - case <-done: - return - case ec <- err: - return - } - } + + dst.Close() // 当一端读结束时,结束另一端的写 select { case <-done: diff --git a/proxy/proxy.go b/proxy/proxy.go index ba175c8..881e2f0 100644 --- a/proxy/proxy.go +++ b/proxy/proxy.go @@ -42,12 +42,12 @@ func NewProxy(opts *Options) (*Proxy, error) { Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, + Timeout: 15 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, + IdleConnTimeout: 5 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, ForceAttemptHTTP2: false, // disable http2 @@ -280,8 +280,8 @@ func (proxy *Proxy) handleConnect(res http.ResponseWriter, req *http.Request) { return } - // send RST other than FIN when finished, to avoid TIME_WAIT state - cconn.(*net.TCPConn).SetLinger(0) + cconn.(*net.TCPConn).SetLinger(0) // send RST other than FIN when finished, to avoid TIME_WAIT state + cconn.(*net.TCPConn).SetKeepAlive(false) defer cconn.Close() _, err = io.WriteString(cconn, "HTTP/1.1 200 Connection Established\r\n\r\n")