Skip to content

Commit 590c606

Browse files
authored
Handle panics when calling the RPCHandler instead of dying (#488)
Added a wrapper around the callRPCHandler function to recover from panic and translate that to and error so that the RPC thread doesn't just die when something malformed comes in. This should keep the Jet flying.
1 parent a60e1a5 commit 590c606

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

jsonrpc.go

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,31 @@ func rpcSetTLSState(state TLSState) error {
466466
return nil
467467
}
468468

469-
func callRPCHandler(handler RPCHandler, params map[string]interface{}) (interface{}, error) {
469+
type RPCHandler struct {
470+
Func interface{}
471+
Params []string
472+
}
473+
474+
// call the handler but recover from a panic to ensure our RPC thread doesn't collapse on malformed calls
475+
func callRPCHandler(handler RPCHandler, params map[string]interface{}) (result interface{}, err error) {
476+
// Use defer to recover from a panic
477+
defer func() {
478+
if r := recover(); r != nil {
479+
// Convert the panic to an error
480+
if e, ok := r.(error); ok {
481+
err = e
482+
} else {
483+
err = fmt.Errorf("panic occurred: %v", r)
484+
}
485+
}
486+
}()
487+
488+
// Call the handler
489+
result, err = riskyCallRPCHandler(handler, params)
490+
return result, err
491+
}
492+
493+
func riskyCallRPCHandler(handler RPCHandler, params map[string]interface{}) (interface{}, error) {
470494
handlerValue := reflect.ValueOf(handler.Func)
471495
handlerType := handlerValue.Type()
472496

@@ -563,11 +587,6 @@ func callRPCHandler(handler RPCHandler, params map[string]interface{}) (interfac
563587
return nil, errors.New("unexpected return values from handler")
564588
}
565589

566-
type RPCHandler struct {
567-
Func interface{}
568-
Params []string
569-
}
570-
571590
func rpcSetMassStorageMode(mode string) (string, error) {
572591
logger.Info().Str("mode", mode).Msg("Setting mass storage mode")
573592
var cdrom bool

0 commit comments

Comments
 (0)