Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close the connection used by https #256

Merged
merged 10 commits into from
Dec 23, 2024
18 changes: 15 additions & 3 deletions https.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"os"
"strconv"
"strings"
"sync"
"sync/atomic"

"github.com/elazarl/goproxy/internal/signer"
Expand Down Expand Up @@ -139,8 +140,18 @@ func (proxy *ProxyHttpServer) handleHttps(w http.ResponseWriter, r *http.Request
targetTCP, targetOK := targetSiteCon.(halfClosable)
proxyClientTCP, clientOK := proxyClient.(halfClosable)
if targetOK && clientOK {
go copyAndClose(ctx, targetTCP, proxyClientTCP)
go copyAndClose(ctx, proxyClientTCP, targetTCP)
go func() {
var wg sync.WaitGroup
wg.Add(2)
go copyAndClose(ctx, targetTCP, proxyClientTCP, &wg)
go copyAndClose(ctx, proxyClientTCP, targetTCP, &wg)
wg.Wait()
// Make sure to close the underlying TCP socket.
// CloseRead() and CloseWrite() keep it open until its timeout,
// causing error when there are thousands of requests.
proxyClientTCP.Close()
targetTCP.Close()
}()
} else {
// There is a race with the runtime here. In the case where the
// connection to the target site times out, we cannot control which
Expand Down Expand Up @@ -445,14 +456,15 @@ func copyOrWarn(ctx *ProxyCtx, dst io.Writer, src io.Reader) error {
return err
}

func copyAndClose(ctx *ProxyCtx, dst, src halfClosable) {
func copyAndClose(ctx *ProxyCtx, dst, src halfClosable, wg *sync.WaitGroup) {
_, err := io.Copy(dst, src)
if err != nil && !errors.Is(err, net.ErrClosed) {
ctx.Warnf("Error copying to client: %s", err.Error())
}

_ = dst.CloseWrite()
_ = src.CloseRead()
wg.Done()
}

func dialerFromEnv(proxy *ProxyHttpServer) func(network, addr string) (net.Conn, error) {
Expand Down
Loading