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

Improve handling of errors from body.Close() #526

Merged
merged 2 commits into from
Nov 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions e2e/tests/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,19 @@ import (
"context"
"errors"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"

"github.com/gorilla/websocket"
"github.com/saucelabs/forwarder/e2e/forwarder"
Expand Down Expand Up @@ -287,3 +291,47 @@ func TestProxyUpstream(t *testing.T) {
t.Fatalf("%s via header not found", forwarder.UpstreamProxyServiceName)
}
}

func TestProxyReuseConnection(t *testing.T) {
c := newClient(t, "http://wronghost", func(tr *http.Transport) {
var (
d net.Dialer
dialed atomic.Bool
)
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
if dialed.CompareAndSwap(false, true) {
return d.DialContext(ctx, network, addr)
}
return nil, errors.New("only one dial is allowed")
}
})

for i := 0; i < 2; i++ {
r, w := io.Pipe()

written := make(chan struct{})
go func() {
zeros := make([]byte, 1024*1024)
if _, err := w.Write(zeros); err != nil {
t.Error(err)
}
if err := w.Close(); err != nil {
t.Error(err)
}
close(written)
}()

res := c.GET("/", func(req *http.Request) {
req.Body = r
})
if res.StatusCode != http.StatusBadGateway {
t.Fatalf("Expected status %d, got %d", http.StatusBadGateway, res.StatusCode)
}

select {
case <-written:
case <-time.After(10 * time.Second):
t.Fatal("timed-out waiting for body read")
}
}
}
9 changes: 9 additions & 0 deletions internal/martian/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,15 @@ func (p *Proxy) handle(ctx *Context, conn net.Conn, brw *bufio.ReadWriter) error
log.Errorf(req.Context(), "got error while flushing response back to client: %v", err)
}

if err := req.Body.Close(); err != nil {
log.Errorf(req.Context(), "failed to close request body: %v", err)
closing = errClose
}
if err := res.Body.Close(); err != nil {
log.Errorf(req.Context(), "failed to close response body: %v", err)
closing = errClose
}

if p.CloseAfterReply {
closing = errClose
}
Expand Down