Maint: http proxy HTTPS handling simplifications

This commit is contained in:
Quentin McGaw (desktop)
2021-08-25 17:02:50 +00:00
parent 9f12ffc069
commit ca3b9e892d

View File

@@ -1,11 +1,9 @@
package httpproxy package httpproxy
import ( import (
"context"
"io" "io"
"net" "net"
"net/http" "net/http"
"sync"
) )
func (h *handler) handleHTTPS(responseWriter http.ResponseWriter, request *http.Request) { func (h *handler) handleHTTPS(responseWriter http.ResponseWriter, request *http.Request) {
@@ -38,27 +36,30 @@ func (h *handler) handleHTTPS(responseWriter http.ResponseWriter, request *http.
} }
h.wg.Add(1) h.wg.Add(1)
ctx, cancel := context.WithCancel(h.ctx)
const transferGoroutines = 2 serverToClientDone := make(chan struct{})
wg := &sync.WaitGroup{} clientToServerClientDone := make(chan struct{})
wg.Add(transferGoroutines) go transfer(destinationConn, clientConnection, clientToServerClientDone)
go func() { // trigger cleanup when done go transfer(clientConnection, destinationConn, serverToClientDone)
wg.Wait()
cancel() select {
}() case <-h.ctx.Done():
go func() { // cleanup
<-ctx.Done()
destinationConn.Close() destinationConn.Close()
clientConnection.Close() clientConnection.Close()
<-serverToClientDone
<-clientToServerClientDone
case <-serverToClientDone:
<-clientToServerClientDone
case <-clientToServerClientDone: // happens more rarely, when a connection is closed on the client side
<-serverToClientDone
}
h.wg.Done() h.wg.Done()
}()
go transfer(destinationConn, clientConnection, wg)
go transfer(clientConnection, destinationConn, wg)
} }
func transfer(destination io.WriteCloser, source io.ReadCloser, wg *sync.WaitGroup) { func transfer(destination io.WriteCloser, source io.ReadCloser, done chan<- struct{}) {
_, _ = io.Copy(destination, source) _, _ = io.Copy(destination, source)
_ = source.Close() _ = source.Close()
_ = destination.Close() _ = destination.Close()
wg.Done() close(done)
} }