From 25a5ca47d8d9c5edd0519f1c46d0bf1e685014a0 Mon Sep 17 00:00:00 2001 From: Anmol Sethi Date: Thu, 19 Oct 2023 00:54:49 -0700 Subject: [PATCH] netconn.go: Fix panic on zero or negative deadline durations Glad no one ran into this in production. --- conn_test.go | 12 ++++++++++++ netconn.go | 12 ++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/conn_test.go b/conn_test.go index abc1c81d..17c52c32 100644 --- a/conn_test.go +++ b/conn_test.go @@ -236,6 +236,18 @@ func TestConn(t *testing.T) { assert.Equal(t, "read msg", s, string(b)) }) + t.Run("netConn/pastDeadline", func(t *testing.T) { + tt, c1, c2 := newConnTest(t, nil, nil) + + n1 := websocket.NetConn(tt.ctx, c1, websocket.MessageBinary) + n2 := websocket.NetConn(tt.ctx, c2, websocket.MessageBinary) + + n1.SetDeadline(time.Now().Add(-time.Minute)) + n2.SetDeadline(time.Now().Add(-time.Minute)) + + // No panic we're good. + }) + t.Run("wsjson", func(t *testing.T) { tt, c1, c2 := newConnTest(t, nil, nil) diff --git a/netconn.go b/netconn.go index e398b4f7..1667f45c 100644 --- a/netconn.go +++ b/netconn.go @@ -210,7 +210,11 @@ func (nc *netConn) SetWriteDeadline(t time.Time) error { if t.IsZero() { nc.writeTimer.Stop() } else { - nc.writeTimer.Reset(time.Until(t)) + dur := time.Until(t) + if dur <= 0 { + dur = 1 + } + nc.writeTimer.Reset(dur) } return nil } @@ -220,7 +224,11 @@ func (nc *netConn) SetReadDeadline(t time.Time) error { if t.IsZero() { nc.readTimer.Stop() } else { - nc.readTimer.Reset(time.Until(t)) + dur := time.Until(t) + if dur <= 0 { + dur = 1 + } + nc.readTimer.Reset(dur) } return nil }