Repository navigation
Description
When using this library, we had the use case of forwarding log messages back to the other peer, using the jsonrpc2.SetLogger jsonrpc2.ConnOpt. This, however, might result in an internal deadlock.
I am unsure how much of a bug this is, but the API allows it and I have not found any warning in the docs. If this is unsupported behavior, please consider adding an API doc comment stating so.
Thanks!
Trace
When the underlying Conn is closed with a known cause, the logger is called while the internal mutex is locked.
Lines 169 to 182 in 2cc9417
| c.mu.Lock() | |
| defer c.mu.Unlock() | |
| if c.closed { | |
| return ErrClosed | |
| } | |
| for _, call := range c.pending { | |
| close(call.done) | |
| } | |
| if cause != nil && cause != io.EOF && cause != io.ErrUnexpectedEOF { | |
| c.logger.Printf("jsonrpc2: protocol error: %v\n", cause) | |
| } |
Now, c.logger.Printf results in e.conn.Notify being called, which calls c.send.
Lines 127 to 142 in 2cc9417
| func (c *Conn) Notify(ctx context.Context, method string, params interface{}, opts ...CallOption) error { | |
| req := &Request{Method: method, Notif: true} | |
| for _, opt := range opts { | |
| if opt == nil { | |
| continue | |
| } | |
| if err := opt.apply(req); err != nil { | |
| return err | |
| } | |
| } | |
| if params != nil { | |
| if err := req.SetParams(params); err != nil { | |
| return err | |
| } | |
| } | |
| _, err := c.send(ctx, &anyMessage{request: req}, false) |
And there, another mutex lock is being set, while the prior lock is still active.
Lines 241 to 260 in 2cc9417
| func (c *Conn) send(_ context.Context, m *anyMessage, wait bool) (cc *call, err error) { | |
| c.sending.Lock() | |
| defer c.sending.Unlock() | |
| // double check the error isn't due to being closed while sending. | |
| defer func() { | |
| if err != nil { | |
| c.mu.Lock() | |
| if c.closed { | |
| err = ErrClosed | |
| } | |
| c.mu.Unlock() | |
| } | |
| }() | |
| // m.request.ID could be changed, so we store a copy to correctly | |
| // clean up pending | |
| var id ID | |
| c.mu.Lock() |
Btw, Conn.close is only called with a cause in c.readMessage if the next JSON RPC message cannot be read.
Lines 191 to 194 in 2cc9417
| var m anyMessage | |
| err := c.stream.ReadObject(&m) | |
| if err != nil { | |
| c.close(err) |
Proof of Concept
package main
import (
"context"
"errors"
"io"
"runtime/debug"
"time"
"github.com/sourcegraph/jsonrpc2"
)
// logger using the underlying jsonrpc2.Conn. The pointer-pointer is used to ease self-reference in main below.
type logger struct{ conn **jsonrpc2.Conn }
func (l logger) Printf(string, ...any) {
_ = (*l.conn).Notify(context.Background(), "log", nil)
}
type handler struct{}
func (handler) Handle(context.Context, *jsonrpc2.Conn, *jsonrpc2.Request) {}
type readWriteCloser struct {
r io.ReadCloser
w io.WriteCloser
}
func (rwc *readWriteCloser) Read(p []byte) (n int, err error) { return rwc.r.Read(p) }
func (rwc *readWriteCloser) Write(p []byte) (n int, err error) { return rwc.w.Write(p) }
func (rwc *readWriteCloser) Close() error { return errors.Join(rwc.r.Close(), rwc.w.Close()) }
func main() {
debug.SetTraceback("all")
r, w := io.Pipe()
var conn *jsonrpc2.Conn
conn = jsonrpc2.NewConn(
context.Background(),
jsonrpc2.NewPlainObjectStream(&readWriteCloser{r, w}),
handler{},
jsonrpc2.SetLogger(logger{&conn}),
)
// Faulty or malicious peer sends invalid JSON RPC message.
_, _ = w.Write([]byte("☃\n"))
select {
case <-conn.DisconnectNotify():
case <-time.After(3 * time.Second):
panic("timeout")
}
}$ go run main.go
panic: timeout
goroutine 1 [running]:
main.main()
…/main.go:52 +0x485
goroutine 7 [sync.Mutex.Lock]:
internal/sync.runtime_SemacquireMutex(0x1bb09bbebc08?, 0x25?, 0x1bb09bbebc18?)
/nix/store/rcz9i4msbg3178grqll9h98b07dwk7zg-go-1.26.5/share/go/src/runtime/sema.go:95 +0x25
internal/sync.(*Mutex).lockSlow(0x1bb09bbf8020)
/nix/store/rcz9i4msbg3178grqll9h98b07dwk7zg-go-1.26.5/share/go/src/internal/sync/mutex.go:149 +0x15d
internal/sync.(*Mutex).Lock(...)
/nix/store/rcz9i4msbg3178grqll9h98b07dwk7zg-go-1.26.5/share/go/src/internal/sync/mutex.go:70
sync.(*Mutex).Lock(...)
/nix/store/rcz9i4msbg3178grqll9h98b07dwk7zg-go-1.26.5/share/go/src/sync/mutex.go:46
github.com/sourcegraph/jsonrpc2.(*Conn).send(0x1bb09bbf8000, {0x1bb09bbebd78?, 0x4?}, 0x1bb09bb520d0, 0x0)
…/go/pkg/mod/github.com/sourcegraph/jsonrpc2@v0.2.1/conn.go:260 +0x12d
github.com/sourcegraph/jsonrpc2.(*Conn).Notify(0x1bb09bbf8000, {0x529988, 0x63a100}, {0x51c18f, 0x3}, {0x0, 0x0}, {0x0, 0x0, 0x0})
…/go/pkg/mod/github.com/sourcegraph/jsonrpc2@v0.2.1/conn.go:142 +0x1ce
main.logger.Printf({0x4?}, {0x1bb09bb4e060?, 0x1bb09bbebe58?}, {0x1bb09bbebe78?, 0x4d84ac?, 0x1bb09bbf60c0?})
…/go/jsonrpc2-poc-zhjl/main.go:17 +0x45
github.com/sourcegraph/jsonrpc2.(*Conn).close(0x1bb09bbf8000, {0x529660, 0x1bb09bb4e060})
…/go/pkg/mod/github.com/sourcegraph/jsonrpc2@v0.2.1/conn.go:181 +0x257
github.com/sourcegraph/jsonrpc2.(*Conn).readMessages(0x1bb09bbf8000, {0x529988, 0x63a100})
…/go/pkg/mod/github.com/sourcegraph/jsonrpc2@v0.2.1/conn.go:194 +0x2c6
created by github.com/sourcegraph/jsonrpc2.NewConn in goroutine 1
/…/go/pkg/mod/github.com/sourcegraph/jsonrpc2@v0.2.1/conn.go:62 +0x1e6
exit status 2
Activity
keegancsmith commentedon Jul 31, 2026
Thanks for the detailed report! Just published a fix under v0.2.2