Skip to content

Commit

Permalink
Close the connection used by https (#256)
Browse files Browse the repository at this point in the history
* Close the connection used for https

* need Closing Read and Write

---------

Co-authored-by: YushiIso <iso@datasection.co.jp>
  • Loading branch information
YushiIso and YushiIso authored Dec 23, 2024
1 parent 928343f commit ffb746c
Showing 1 changed file with 15 additions and 3 deletions.
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

0 comments on commit ffb746c

Please sign in to comment.