Skip to content

Commit bd48140

Browse files
authored
fix: potential race when reading incomingErr (#125)
Reported by @parthshah1
1 parent 9a16432 commit bd48140

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

websocket.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ type wsConn struct {
6565
// incoming messages
6666
incoming chan io.Reader
6767
incomingErr error
68+
errLk sync.Mutex
6869

6970
readError chan error
7071

@@ -115,12 +116,16 @@ func (c *wsConn) nextMessage() {
115116
c.resetReadDeadline()
116117
msgType, r, err := c.conn.NextReader()
117118
if err != nil {
119+
c.errLk.Lock()
118120
c.incomingErr = err
121+
c.errLk.Unlock()
119122
close(c.incoming)
120123
return
121124
}
122125
if msgType != websocket.BinaryMessage && msgType != websocket.TextMessage {
126+
c.errLk.Lock()
123127
c.incomingErr = errors.New("unsupported message type")
128+
c.errLk.Unlock()
124129
close(c.incoming)
125130
return
126131
}
@@ -647,7 +652,9 @@ func (c *wsConn) tryReconnect(ctx context.Context) bool {
647652

648653
c.writeLk.Lock()
649654
c.conn = conn
655+
c.errLk.Lock()
650656
c.incomingErr = nil
657+
c.errLk.Unlock()
651658

652659
c.stopPings = c.setupPings()
653660

@@ -767,7 +774,9 @@ func (c *wsConn) handleWsConn(ctx context.Context) {
767774
select {
768775
case r, ok := <-c.incoming:
769776
action = "incoming"
777+
c.errLk.Lock()
770778
err := c.incomingErr
779+
c.errLk.Unlock()
771780

772781
if ok {
773782
go c.readFrame(ctx, r)
@@ -798,7 +807,10 @@ func (c *wsConn) handleWsConn(ctx context.Context) {
798807

799808
c.writeLk.Lock()
800809
if req.req.ID != nil { // non-notification
801-
if c.incomingErr != nil { // No conn?, immediate fail
810+
c.errLk.Lock()
811+
hasErr := c.incomingErr != nil
812+
c.errLk.Unlock()
813+
if hasErr { // No conn?, immediate fail
802814
req.ready <- clientResponse{
803815
Jsonrpc: "2.0",
804816
ID: req.req.ID,

0 commit comments

Comments
 (0)