multi: switch from btcsuite/websocket to gorilla/websocket
What changed, and why it matters
This commit swaps btcd's websocket library from an old, unmaintained in-house copy to the actively maintained gorilla/websocket. The only behavior change is that the new library reports a normal peer disconnect differently, so the code now treats a normal close frame like a clean disconnect instead of logging it as an error. There is no direct security vulnerability being fixed; it is primarily a maintenance and noise-reduction change.
Treat as routine maintenance. Reviewers should verify that all websocket close paths (normal, going away, abnormal) are handled consistently and that no other behavioral differences between btcsuite/websocket and gorilla/websocket affect production logic.
Security signals we found
Dependency switched from unmaintained fork to maintained upstream websocket library
Behavior change only in error classification for clean disconnects
No memory corruption, authentication bypass, or cryptographic weakness visible in diff
Added tests confirm normal close frames are not logged as errors
Evidence from the diff
The commit replaces github.com/btcsuite/websocket with github.com/gorilla/websocket across go.mod, go.sum, rpcserver.go, rpcwebsocket.go, and rpcclient/infrastructure.go. The functional adjustment is that gorilla/websocket returns a *websocket.CloseError for normal peer close frames, whereas the old library returned io.EOF. New helper logic (isNormalWebsocketClose and an extended shouldLogReadError) suppresses logging for CloseNormalClosure and CloseGoingAway, matching the prior EOF handling. Tests are added to verify normal closes are not logged as errors.
Changed components
rpcserver.gorpcwebsocket.gorpcclient/infrastructure.gogo.mod dependency graphInspect captured patch +367 / −8
### go.mod
@@ -13,7 +13,6 @@ require (
github.com/btcsuite/btcd/wire/v2 v2.0.1
github.com/btcsuite/btclog v1.0.0
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd
- github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792
github.com/davecgh/go-spew v1.1.1
github.com/decred/dcrd/lru v1.1.3
github.com/gorilla/websocket v1.5.3
### go.sum
@@ -20,8 +20,6 @@ github.com/btcsuite/btclog v1.0.0 h1:sEkpKJMmfGiyZjADwEIgB1NSwMyfdD1FB8v6+w1T0Ns
github.com/btcsuite/btclog v1.0.0/go.mod h1:w7xnGOhwT3lmrS4H3b/D1XAXxvh+tbhUm8xeHN2y3TQ=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd h1:R/opQEbFEy9JGkIguV40SvRY1uliPX8ifOvi6ICsFCw=
github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg=
-github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792 h1:R8vQdOQdZ9Y3SkEwmHoWBmX1DNXhXZqlTpq6s4tyJGc=
-github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
### rpcclient/infrastructure.go
@@ -29,7 +29,7 @@ import (
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg/v2"
"github.com/btcsuite/go-socks/socks"
- "github.com/btcsuite/websocket"
+ "github.com/gorilla/websocket"
)
var (
@@ -464,10 +464,16 @@ func (c *Client) shouldLogReadError(err error) bool {
default:
}
- // No logging when the connection has been disconnected.
+ // No logging when the connection has been disconnected, including when
+ // the server closed it normally with a close frame.
if err == io.EOF {
return false
}
+ if websocket.IsCloseError(err, websocket.CloseNormalClosure,
+ websocket.CloseGoingAway) {
+
+ return false
+ }
if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() {
return false
}
### rpcclient/infrastructure_test.go
@@ -12,6 +12,7 @@ import (
"testing"
"time"
+ "github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -768,3 +769,59 @@ func TestHTTPURLWiring(t *testing.T) {
require.Equal(t, "http://localhost:8332", c.httpURL)
}
+
+// TestShouldLogReadError checks which websocket read errors are logged: a
+// normal close by the server or a shutdown of the client is not an error worth
+// logging, while a dropped connection or any other failure is.
+func TestShouldLogReadError(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {
+ name: "EOF",
+ err: io.EOF,
+ want: false,
+ },
+ {
+ name: "normal close",
+ err: &websocket.CloseError{
+ Code: websocket.CloseNormalClosure,
+ },
+ want: false,
+ },
+ {
+ name: "going away",
+ err: &websocket.CloseError{
+ Code: websocket.CloseGoingAway,
+ },
+ want: false,
+ },
+ {
+ name: "connection dropped",
+ err: &websocket.CloseError{
+ Code: websocket.CloseAbnormalClosure,
+ Text: io.ErrUnexpectedEOF.Error(),
+ },
+ want: true,
+ },
+ {
+ name: "other error",
+ err: errors.New("read failed"),
+ want: true,
+ },
+ }
+
+ for _, test := range tests {
+ c := &Client{shutdown: make(chan struct{})}
+ require.Equal(t, test.want, c.shouldLogReadError(test.err),
+ test.name)
+
+ // Nothing is logged once the client is shutting down.
+ close(c.shutdown)
+ require.False(t, c.shouldLogReadError(test.err), test.name)
+ }
+}
### rpcserver.go
@@ -41,7 +41,7 @@ import (
"github.com/btcsuite/btcd/peer"
"github.com/btcsuite/btcd/txscript/v2"
"github.com/btcsuite/btcd/wire/v2"
- "github.com/btcsuite/websocket"
+ "github.com/gorilla/websocket"
)
// API version constants
### rpcwebsocket.go
@@ -29,7 +29,7 @@ import (
"github.com/btcsuite/btcd/database"
"github.com/btcsuite/btcd/txscript/v2"
"github.com/btcsuite/btcd/wire/v2"
- "github.com/btcsuite/websocket"
+ "github.com/gorilla/websocket"
"golang.org/x/crypto/ripemd160"
)
@@ -1257,6 +1257,13 @@ type wsClient struct {
wg sync.WaitGroup
}
+// isNormalWebsocketClose returns whether err is the error a websocket read
+// returns when the peer closes the connection normally with a close frame.
+func isNormalWebsocketClose(err error) bool {
+ return websocket.IsCloseError(err, websocket.CloseNormalClosure,
+ websocket.CloseGoingAway)
+}
+
// inHandler handles all incoming messages for the websocket connection. It
// must be run as a goroutine.
func (c *wsClient) inHandler() {
@@ -1273,7 +1280,7 @@ out:
_, msg, err := c.conn.ReadMessage()
if err != nil {
// Log the error if it's not due to disconnecting.
- if err != io.EOF {
+ if err != io.EOF && !isNormalWebsocketClose(err) {
rpcsLog.Errorf("Websocket receive error from "+
"%s: %v", c.addr, err)
}
### rpcwebsocket_test.go
@@ -0,0 +1,282 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "testing/synctest"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ // testWSUser and testWSPass are the RPC credentials of the websocket
+ // test server.
+ testWSUser = "user"
+ testWSPass = "pass"
+)
+
+// testRPCLog collects what the RPC server logs during the tests. TestMain
+// installs it.
+var testRPCLog = &syncBuffer{}
+
+// lastTestClientPort numbers the in-memory connections of the websocket tests,
+// so that each gets its own client address and rpcLogFor tells their log
+// lines apart.
+var lastTestClientPort atomic.Int32
+
+// rpcLogFor returns the lines of testRPCLog about the client connected through
+// conn. The server logs clients by their address.
+func rpcLogFor(conn *websocket.Conn) string {
+ addr := conn.LocalAddr().String()
+
+ var lines []string
+ for _, line := range strings.Split(testRPCLog.String(), "\n") {
+ if strings.Contains(line, addr) {
+ lines = append(lines, line)
+ }
+ }
+
+ return strings.Join(lines, "\n")
+}
+
+// syncBuffer is a bytes.Buffer that is safe for concurrent use, so that
+// server goroutines can log into it while a test reads it.
+type syncBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+// Write appends p to the buffer.
+func (b *syncBuffer) Write(p []byte) (int, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ return b.buf.Write(p)
+}
+
+// String returns the contents of the buffer.
+func (b *syncBuffer) String() string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+
+ return b.buf.String()
+}
+
+// pipeListener is a net.Listener whose connections are in-memory pipes made by
+// its dial method. Unlike loopback connections, pipes let the websocket tests
+// run in a synctest bubble.
+type pipeListener struct {
+ conns chan net.Conn
+ closed chan struct{}
+ once sync.Once
+}
+
+// newPipeListener returns a listener for in-memory connections.
+func newPipeListener() *pipeListener {
+ return &pipeListener{
+ conns: make(chan net.Conn),
+ closed: make(chan struct{}),
+ }
+}
+
+// Accept returns the server end of the next connection made by dial.
+func (l *pipeListener) Accept() (net.Conn, error) {
+ select {
+ case conn := <-l.conns:
+ return conn, nil
+
+ case <-l.closed:
+ return nil, net.ErrClosed
+ }
+}
+
+// Close stops the listener.
+func (l *pipeListener) Close() error {
+ l.once.Do(func() {
+ close(l.closed)
+ })
+
+ return nil
+}
+
+// Addr returns the address of the listener.
+func (l *pipeListener) Addr() net.Addr {
+ return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}
+}
+
+// dial connects to the listener through an in-memory pipe. Each connection
+// gets its own client address, which the server sees as the remote address.
+func (l *pipeListener) dial(ctx context.Context, _, _ string) (net.Conn,
+ error) {
+
+ port := 50000 + int(lastTestClientPort.Add(1))
+ addr := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port}
+
+ server, client := net.Pipe()
+ select {
+ case l.conns <- &addrConn{Conn: server, remoteAddr: addr}:
+ return &addrConn{Conn: client, localAddr: addr}, nil
+
+ case <-l.closed:
+ _, _ = server.Close(), client.Close()
+ return nil, net.ErrClosed
+
+ case <-ctx.Done():
+ _, _ = server.Close(), client.Close()
+ return nil, ctx.Err()
+ }
+}
+
+// addrConn is a connection that reports the given local and remote addresses,
+// when set, instead of those of the underlying connection.
+type addrConn struct {
+ net.Conn
+
+ localAddr net.Addr
+ remoteAddr net.Addr
+}
+
+// LocalAddr returns the local address of the connection.
+func (c *addrConn) LocalAddr() net.Addr {
+ if c.localAddr != nil {
+ return c.localAddr
+ }
+
+ return c.Conn.LocalAddr()
+}
+
+// RemoteAddr returns the remote address of the connection.
+func (c *addrConn) RemoteAddr() net.Addr {
+ if c.remoteAddr != nil {
+ return c.remoteAddr
+ }
+
+ return c.Conn.RemoteAddr()
+}
+
+// testWebsocketServer serves the websocket endpoint of an RPC server that has
+// no chain behind it, which is enough to exercise authentication and request
+// parsing.
+type testWebsocketServer struct {
+ // listener makes the in-memory connections to the server.
+ listener *pipeListener
+
+ // done receives a value each time the server finishes handling a
+ // connection.
+ done chan struct{}
+}
+
+// newTestWebsocketServer starts a websocket test server. When authenticated
+// is set, clients are treated as having passed HTTP basic auth during the
+// upgrade; otherwise they have to send the authenticate command.
+//
+// It must be called in a synctest bubble, so the server runs on the bubble's
+// fake clock, and a server that never does what a test waits for makes the
+// bubble deadlock, which fails the test. The server swaps the global config,
+// so tests using it must not run in parallel.
+func newTestWebsocketServer(t *testing.T,
+ authenticated bool) *testWebsocketServer {
+
+ t.Helper()
+
+ oldCfg := cfg
+ cfg = &config{RPCMaxWebsockets: 10, RPCMaxConcurrentReqs: 10}
+ t.Cleanup(func() {
+ cfg = oldCfg
+ })
+
+ login := testWSUser + ":" + testWSPass
+ auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
+ s := &rpcServer{authsha: sha256.Sum256([]byte(auth))}
+ s.ntfnMgr = newWsNotificationManager(s)
+ s.ntfnMgr.Start()
+ t.Cleanup(func() {
+ s.ntfnMgr.Shutdown()
+ s.ntfnMgr.WaitForShutdown()
+ })
+
+ // Wait for all connections to be handled before the config is restored.
+ // Hijacked connections aren't tracked by the HTTP server.
+ var handlers sync.WaitGroup
+ t.Cleanup(handlers.Wait)
+
+ done := make(chan struct{}, 10)
+ srv := &http.Server{Handler: http.HandlerFunc(
+ func(w http.ResponseWriter, r *http.Request) {
+ handlers.Add(1)
+ defer handlers.Done()
+
+ ws, err := websocket.Upgrade(w, r, nil, 0, 0)
+ if err != nil {
+ return
+ }
+ s.WebsocketHandler(
+ ws, r.RemoteAddr, authenticated, true,
+ )
+ done <- struct{}{}
+ },
+ )}
+ listener := newPipeListener()
+ go func() {
+ _ = srv.Serve(listener)
+ }()
+ t.Cleanup(func() {
+ _ = srv.Close()
+ })
+
+ return &testWebsocketServer{
+ listener: listener,
+ done: done,
+ }
+}
+
+// dial connects a websocket client to the test server. The connection is
+// closed when the test ends.
+func (s *testWebsocketServer) dial(t *testing.T) *websocket.Conn {
+ t.Helper()
+
+ dialer := websocket.Dialer{NetDialContext: s.listener.dial}
+ conn, _, err := dialer.Dial("ws://btcd/ws", nil)
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _ = conn.Close()
+ })
+
+ return conn
+}
+
+// waitDone waits for the server to finish handling a connection.
+func (s *testWebsocketServer) waitDone() {
+ <-s.done
+}
+
+// TestWebsocketNormalCloseNotLogged checks that a client closing the
+// connection with a normal close frame isn't logged as a receive error.
+func TestWebsocketNormalCloseNotLogged(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ s := newTestWebsocketServer(t, true)
+ conn := s.dial(t)
+
+ msg := websocket.FormatCloseMessage(
+ websocket.CloseNormalClosure, "",
+ )
+ deadline := time.Now().Add(time.Second)
+ err := conn.WriteControl(websocket.CloseMessage, msg, deadline)
+ require.NoError(t, err)
+ s.waitDone()
+
+ log := rpcLogFor(conn)
+ require.Contains(t, log, "Disconnected websocket client")
+ require.NotContains(t, log, "Websocket receive error")
+ })
+}
### server_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "io"
"net"
"os"
"path/filepath"
@@ -11,6 +12,7 @@ import (
"github.com/btcsuite/btcd/chaincfg/v2"
"github.com/btcsuite/btcd/internal/inbound"
"github.com/btcsuite/btcd/peer"
+ "github.com/btcsuite/btclog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -19,6 +21,14 @@ func TestMain(m *testing.M) {
// logRotator must be non-nil or any log write (e.g. from
// OnVerAck's double-call guard) panics via logWriter.Write.
initLogRotator(filepath.Join(os.TempDir(), "btcd-server-test.log"))
+
+ // Also send what the RPC server logs to testRPCLog for the websocket
+ // tests. This must happen before any test runs: server goroutines read
+ // rpcsLog without synchronization, even after their client shut down.
+ rpcsLog = btclog.NewBackend(
+ io.MultiWriter(logWriter{}, testRPCLog),
+ ).Logger("RPCS")
+
os.Exit(m.Run())
}
Why this scored 18/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.