Skip to content

Commit

Permalink
removing error handling while closing connections
Browse files Browse the repository at this point in the history
  • Loading branch information
apoorvajagtap committed Mar 19, 2024
1 parent 951cb7e commit c8a6785
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 53 deletions.
15 changes: 8 additions & 7 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,8 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h
}
err = c.SetDeadline(deadline)
if err != nil {
return nil, errors.Join(err, c.Close())
c.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 296 in client.go

View check run for this annotation

Codecov / codecov/patch

client.go#L296

Added line #L296 was not covered by tests
return nil, err
}
return c, nil
}
Expand Down Expand Up @@ -332,7 +333,9 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h

defer func() {
if netConn != nil {
netConn.Close() //#nosec:G104 (CWE-703)
// As mentioned in https://github.com/gorilla/websocket/pull/897#issuecomment-1947108098:
// It's safe to ignore the errors for netconn.Close()
netConn.Close() //#nosec G104 (CWE-703): Errors unhandled
}
}()

Expand Down Expand Up @@ -423,11 +426,9 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h
resp.Body = io.NopCloser(bytes.NewReader([]byte{}))
conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")

if err := netConn.SetDeadline(time.Time{}); err != nil {
return nil, nil, err
}
netConn = nil // to avoid close in defer.
return conn, resp, err
netConn.SetDeadline(time.Time{}) //#nosec G104 (CWE-703): Errors unhandled

Check failure on line 429 in client.go

View workflow job for this annotation

GitHub Actions / lint (1.20)

Error return value of `netConn.SetDeadline` is not checked (errcheck)
netConn = nil // to avoid close in defer.
return conn, resp, nil
}

func cloneTLSConfig(cfg *tls.Config) *tls.Config {
Expand Down
26 changes: 11 additions & 15 deletions client_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ func (t cstHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
ws, err := cstUpgrader.Upgrade(w, r, http.Header{"Set-Cookie": {"sessionID=1234"}})
if err != nil {
t.Logf("Upgrade: %v", err)
return
}
defer ws.Close()
Expand All @@ -103,16 +104,20 @@ func (t cstHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
op, rd, err := ws.NextReader()
if err != nil {
t.Logf("NextReader: %v", err)
return
}
wr, err := ws.NextWriter(op)
if err != nil {
t.Logf("NextWriter: %v", err)
return
}
if _, err = io.Copy(wr, rd); err != nil {
t.Logf("Copy: %v", err)
return
}
if err := wr.Close(); err != nil {
t.Logf("Close: %v", err)
return
}
}
Expand Down Expand Up @@ -430,7 +435,7 @@ func TestDialBadOrigin(t *testing.T) {
ws.Close()
t.Fatalf("Dial: nil")
}
if resp == nil { // nolint:staticcheck
if resp == nil {
t.Fatalf("resp=nil, err=%v", err)
}
if resp.StatusCode != http.StatusForbidden { // nolint:staticcheck
Expand Down Expand Up @@ -539,9 +544,7 @@ func TestRespOnBadHandshake(t *testing.T) {

s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(expectedStatus)
if _, err := io.WriteString(w, expectedBody); err != nil {
t.Fatalf("WriteString: %v", err)
}
io.WriteString(w, expectedBody) // nolint:errcheck
}))
defer s.Close()

Expand Down Expand Up @@ -574,6 +577,7 @@ type testLogWriter struct {
}

func (w testLogWriter) Write(p []byte) (int, error) {
w.t.Logf("%s", p)
return len(p), nil
}

Expand Down Expand Up @@ -793,10 +797,7 @@ func TestSocksProxyDial(t *testing.T) {
}
defer c1.Close()

if err := c1.SetDeadline(time.Now().Add(30 * time.Second)); err != nil {
t.Errorf("set deadline failed: %v", err)
return
}
c1.SetDeadline(time.Now().Add(30 * time.Second)) // nolint:errcheck

buf := make([]byte, 32)
if _, err := io.ReadFull(c1, buf[:3]); err != nil {
Expand Down Expand Up @@ -835,15 +836,10 @@ func TestSocksProxyDial(t *testing.T) {
defer c2.Close()
done := make(chan struct{})
go func() {
if _, err := io.Copy(c1, c2); err != nil {
t.Errorf("copy failed: %v", err)
}
io.Copy(c1, c2) // nolint:errcheck
close(done)
}()
if _, err := io.Copy(c2, c1); err != nil {
t.Errorf("copy failed: %v", err)
return
}
io.Copy(c2, c1) // nolint:errcheck
<-done
}()

Expand Down
6 changes: 2 additions & 4 deletions compression.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
"\x01\x00\x00\xff\xff"

fr, _ := flateReaderPool.Get().(io.ReadCloser)
if err := fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil); err != nil {
panic(err)
}
fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) //#nosec G104 (CWE-703): Errors unhandled

Check failure on line 36 in compression.go

View workflow job for this annotation

GitHub Actions / lint (1.20)

Error return value of `(compress/flate.Resetter).Reset` is not checked (errcheck)
return &flateReadWrapper{fr}
}

Expand Down Expand Up @@ -134,7 +132,7 @@ func (r *flateReadWrapper) Read(p []byte) (int, error) {
// Preemptively place the reader back in the pool. This helps with
// scenarios where the application does not call NextReader() soon after
// this final read.
_ = r.Close()
r.Close() //#nosec G104 (CWE-703): Errors unhandled
}
return n, err
}
Expand Down
12 changes: 3 additions & 9 deletions compression_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ func TestTruncWriter(t *testing.T) {
if m > n {
m = n
}
if _, err := w.Write(p[:m]); err != nil {
t.Fatal(err)
}
w.Write(p[:m]) // nolint:errcheck
p = p[m:]
}
if b.String() != data[:len(data)-len(w.p)] {
Expand All @@ -49,9 +47,7 @@ func BenchmarkWriteNoCompression(b *testing.B) {
messages := textMessages(100)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := c.WriteMessage(TextMessage, messages[i%len(messages)]); err != nil {
b.Fatal(err)
}
c.WriteMessage(TextMessage, messages[i%len(messages)]) // nolint:errcheck
}
b.ReportAllocs()
}
Expand All @@ -64,9 +60,7 @@ func BenchmarkWriteWithCompression(b *testing.B) {
c.newCompressionWriter = compressNoContextTakeover
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := c.WriteMessage(TextMessage, messages[i%len(messages)]); err != nil {
b.Fatal(err)
}
c.WriteMessage(TextMessage, messages[i%len(messages)]) // nolint:errcheck
}
b.ReportAllocs()
}
Expand Down
8 changes: 2 additions & 6 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -934,9 +934,7 @@ func (c *Conn) advanceFrame() (int, error) {
}

if c.readLimit > 0 && c.readLength > c.readLimit {
if err := c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)); err != nil {
return noFrame, err
}
c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) //#nosec G104 (CWE-703): Errors unhandled

Check failure on line 937 in conn.go

View workflow job for this annotation

GitHub Actions / lint (1.20)

Error return value of `c.WriteControl` is not checked (errcheck)
return noFrame, ErrReadLimit
}

Expand Down Expand Up @@ -997,9 +995,7 @@ func (c *Conn) handleProtocolError(message string) error {
if len(data) > maxControlFramePayloadSize {
data = data[:maxControlFramePayloadSize]
}
if err := c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)); err != nil {
return err
}
c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)) //#nosec G104 (CWE-703): Errors unhandled

Check failure on line 998 in conn.go

View workflow job for this annotation

GitHub Actions / lint (1.20)

Error return value of `c.WriteControl` is not checked (errcheck)

Check warning on line 998 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L998

Added line #L998 was not covered by tests
return errors.New("websocket: " + message)
}

Expand Down
11 changes: 8 additions & 3 deletions proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,25 @@ func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error)
}

if err := connectReq.Write(conn); err != nil {
return nil, errors.Join(err, conn.Close())
// As mentioned in https://github.com/gorilla/websocket/pull/897#issuecomment-1947108098:
// It's safe to ignore the errors for conn.Close()
conn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 62 in proxy.go

View check run for this annotation

Codecov / codecov/patch

proxy.go#L60-L62

Added lines #L60 - L62 were not covered by tests
return nil, err
}

// Read response. It's OK to use and discard buffered reader here becaue
// the remote server does not speak until spoken to.
br := bufio.NewReader(conn)
resp, err := http.ReadResponse(br, connectReq)
if err != nil {
return nil, errors.Join(err, conn.Close())
conn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 71 in proxy.go

View check run for this annotation

Codecov / codecov/patch

proxy.go#L71

Added line #L71 was not covered by tests
return nil, err
}

if resp.StatusCode != http.StatusOK {
conn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 76 in proxy.go

View check run for this annotation

Codecov / codecov/patch

proxy.go#L76

Added line #L76 was not covered by tests
f := strings.SplitN(resp.Status, " ", 2)
return nil, errors.Join(errors.New(f[1]), conn.Close())
return nil, errors.New(f[1])
}
return conn, nil
}
23 changes: 14 additions & 9 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bufio"
"errors"
"io"
"log"
"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -179,10 +180,10 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
}

if brw.Reader.Buffered() > 0 {
return nil, errors.Join(
errors.New("websocket: client sent data before handshake is complete"),
netConn.Close(),
)
// As mentioned in https://github.com/gorilla/websocket/pull/897#issuecomment-1947108098:
// It's safe to ignore the errors for netconn.Close()
netConn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 185 in server.go

View check run for this annotation

Codecov / codecov/patch

server.go#L183-L185

Added lines #L183 - L185 were not covered by tests
return nil, errors.New("websocket: client sent data before handshake is complete")
}

var br *bufio.Reader
Expand Down Expand Up @@ -247,20 +248,24 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade

// Clear deadlines set by HTTP server.
if err := netConn.SetDeadline(time.Time{}); err != nil {
return nil, errors.Join(err, netConn.Close())
netConn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 251 in server.go

View check run for this annotation

Codecov / codecov/patch

server.go#L251

Added line #L251 was not covered by tests
return nil, err
}

if u.HandshakeTimeout > 0 {
if err := netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)); err != nil {
return nil, errors.Join(err, netConn.Close())
netConn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 257 in server.go

View check run for this annotation

Codecov / codecov/patch

server.go#L257

Added line #L257 was not covered by tests
return nil, err
}
}
if _, err = netConn.Write(p); err != nil {
return nil, errors.Join(err, netConn.Close())
netConn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 262 in server.go

View check run for this annotation

Codecov / codecov/patch

server.go#L262

Added line #L262 was not covered by tests
return nil, err
}
if u.HandshakeTimeout > 0 {
if err := netConn.SetWriteDeadline(time.Time{}); err != nil {
return nil, errors.Join(err, netConn.Close())
netConn.Close() //#nosec G104 (CWE-703): Errors unhandled

Check warning on line 267 in server.go

View check run for this annotation

Codecov / codecov/patch

server.go#L267

Added line #L267 was not covered by tests
return nil, err
}
}

Expand Down Expand Up @@ -363,7 +368,7 @@ func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
panic(err)
}
if err := bw.Flush(); err != nil {
panic(err)
log.Printf("websocket: bufioWriterBuffer: Flush: %v", err)
}

bw.Reset(originalWriter)
Expand Down

0 comments on commit c8a6785

Please sign in to comment.