Files
Reims-Go/internal/plugin/rpc.go
T
千川白浪 d55241cba2 feat(plugin): catalog the Host API, open secret typing and extend the SDK
Give the Sidecar Host API one authoritative catalog in pkg/pluginproto: every
host/* method's status, required permissions, handshake feature and request and
result shapes. The host, pkg/pluginsdk and plugins share those types, so a field
can no longer exist on one side only, and permissions come from the catalog
instead of from each handler. Tests gate that every served method is
catalogued, every stable catalogued method is served, and every catalogued
permission is one the host recognizes.

Open the interface up instead of adding consent gates. Typing a secret setting
is no longer reserved for reims.agent: any plugin that holds qmp:write and that
the user authorized for the VM can have the host type the plugin's own setting,
which the plugin never reads back. Restoring a snapshot works on any authorized
VM, a plugin names its own clones, a held key may carry modifiers, and a
screenshot width outside the supported range is brought into range rather than
refused. Deleting a VM stays limited to the temporary VMs a plugin created.

Record the keys and pointer buttons each plugin holds per VM and lift them when
the plugin's process exits, its scope is disposed, the VM stops or it stops
calling, so a guest never stays stuck with a modifier down. Requests from
plugins that declare pluginApi 1.3 or newer are decoded strictly and answer an
undefined field with JSON-RPC -32602, while older plugins keep tolerant
decoding.

Add typed VM and console methods to pkg/pluginsdk so a plugin no longer needs
its own JSON-RPC client. A method the contract does not catalog, or one the
host did not advertise in the handshake, is refused before it is sent, and the
host's JSON-RPC error code reaches the caller.
2026-12-05 01:43:28 -07:00

355 lines
8.1 KiB
Go

package plugin
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
"sync"
"sync/atomic"
)
const maxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8)
// RPCMethodNotFound is the code a peer answers for a method it does not serve.
const RPCMethodNotFound = -32601
// RPCInvalidParams is the code a peer answers for a request whose params the
// contract does not accept, such as a field the method does not define.
const RPCInvalidParams = -32602
// RPCError is a JSON-RPC 2.0 error object.
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (e *RPCError) Error() string {
return fmt.Sprintf("rpc error %d: %s", e.Code, e.Message)
}
type rpcEnvelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
// RPCRequestHandler handles inbound JSON-RPC requests from the peer.
type RPCRequestHandler func(ctx context.Context, params json.RawMessage) (any, error)
// RPCConn implements bidirectional Content-Length framed JSON-RPC 2.0 over
// stdio pipes with a single writer goroutine and bounded queue (§8).
type RPCConn struct {
r *bufio.Reader
w io.Writer
writeCh chan []byte
closeCh chan struct{}
closeOnce sync.Once
nextID atomic.Uint64
mu sync.Mutex
pending map[string]chan rpcEnvelope
handlers map[string]RPCRequestHandler
inboundSem chan struct{}
closed bool
doneCh chan struct{}
}
// NewRPCConn starts reader and single-writer goroutines over r and w.
func NewRPCConn(r io.Reader, w io.Writer) *RPCConn {
c := &RPCConn{
r: bufio.NewReaderSize(r, 64*1024),
w: w,
writeCh: make(chan []byte, 64),
closeCh: make(chan struct{}),
pending: make(map[string]chan rpcEnvelope),
handlers: make(map[string]RPCRequestHandler),
inboundSem: make(chan struct{}, 32),
doneCh: make(chan struct{}),
}
go c.writeLoop()
go c.readLoop()
return c
}
// Handle registers a handler for inbound peer requests of method.
func (c *RPCConn) Handle(method string, h RPCRequestHandler) {
c.mu.Lock()
c.handlers[method] = h
c.mu.Unlock()
}
// Call sends a JSON-RPC 2.0 request and waits for the response or ctx cancellation.
func (c *RPCConn) Call(ctx context.Context, method string, params any, out any) error {
idNum := c.nextID.Add(1)
idKey := strconv.FormatUint(idNum, 10)
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
env := rpcEnvelope{
JSONRPC: "2.0",
ID: json.RawMessage(idKey),
Method: method,
Params: rawParams,
}
payload, err := json.Marshal(env)
if err != nil {
return err
}
respCh := make(chan rpcEnvelope, 1)
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return errors.New("rpc connection closed")
}
c.pending[idKey] = respCh
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, idKey)
c.mu.Unlock()
}()
if err := c.enqueue(ctx, payload); err != nil {
return err
}
select {
case resp, ok := <-respCh:
if !ok {
return errors.New("rpc connection closed while awaiting response")
}
if resp.Error != nil {
return resp.Error
}
if out != nil && len(resp.Result) > 0 && string(resp.Result) != "null" {
return json.Unmarshal(resp.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
case <-c.closeCh:
return errors.New("rpc connection closed")
case <-c.doneCh:
return errors.New("rpc connection closed")
}
}
// Notify sends a JSON-RPC 2.0 notification (no response expected).
func (c *RPCConn) Notify(ctx context.Context, method string, params any) error {
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
env := rpcEnvelope{
JSONRPC: "2.0",
Method: method,
Params: rawParams,
}
payload, err := json.Marshal(env)
if err != nil {
return err
}
return c.enqueue(ctx, payload)
}
func (c *RPCConn) enqueue(ctx context.Context, payload []byte) error {
select {
case c.writeCh <- payload:
return nil
case <-ctx.Done():
return ctx.Err()
case <-c.closeCh:
return errors.New("rpc connection closed")
}
}
func (c *RPCConn) writeLoop() {
for {
select {
case payload := <-c.writeCh:
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(payload))
if _, err := io.WriteString(c.w, header); err != nil {
c.Close()
return
}
if _, err := c.w.Write(payload); err != nil {
c.Close()
return
}
case <-c.closeCh:
return
}
}
}
func (c *RPCConn) readLoop() {
defer func() {
c.Close()
close(c.doneCh)
}()
for {
frame, err := readContentLengthFrame(c.r)
if err != nil {
return
}
var env rpcEnvelope
if err := json.Unmarshal(frame, &env); err != nil {
continue
}
if env.Method != "" {
// Bounded inbound concurrency so a misbehaving sidecar cannot spawn
// unbounded goroutines in the host.
select {
case c.inboundSem <- struct{}{}:
go func(e rpcEnvelope) {
defer func() { <-c.inboundSem }()
c.dispatchInbound(e)
}(env)
case <-c.closeCh:
return
}
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
c.mu.Lock()
ch := c.pending[key]
delete(c.pending, key)
if ch != nil {
select {
case ch <- env:
default:
}
}
c.mu.Unlock()
}
}
}
func (c *RPCConn) dispatchInbound(env rpcEnvelope) {
c.mu.Lock()
h := c.handlers[env.Method]
c.mu.Unlock()
if h == nil {
if len(env.ID) > 0 {
c.sendResponse(env.ID, nil, &RPCError{Code: RPCMethodNotFound, Message: "method not found: " + env.Method})
}
return
}
res, err := h(context.Background(), env.Params)
if len(env.ID) == 0 {
return // notification
}
if err != nil {
// A handler that names a JSON-RPC code keeps it, so a rejected request
// is distinguishable from a failed one.
var rpcErr *RPCError
if errors.As(err, &rpcErr) {
c.sendResponse(env.ID, nil, rpcErr)
return
}
c.sendResponse(env.ID, nil, &RPCError{Code: -32000, Message: err.Error()})
return
}
c.sendResponse(env.ID, res, nil)
}
func (c *RPCConn) sendResponse(id json.RawMessage, result any, rpcErr *RPCError) {
env := rpcEnvelope{
JSONRPC: "2.0",
ID: id,
Error: rpcErr,
}
if rpcErr == nil {
if result == nil {
env.Result = json.RawMessage("null")
} else if b, err := json.Marshal(result); err == nil {
env.Result = b
}
}
if b, err := json.Marshal(env); err == nil {
_ = c.enqueue(context.Background(), b)
}
}
// Close closes the RPC connection and fails all pending outbound calls.
func (c *RPCConn) Close() {
c.closeOnce.Do(func() {
close(c.closeCh)
c.mu.Lock()
c.closed = true
for id := range c.pending {
delete(c.pending, id)
}
c.mu.Unlock()
})
}
func readContentLengthFrame(r *bufio.Reader) ([]byte, error) {
const (
maxHeaderLines = 64
maxHeaderBytes = 8 * 1024
)
contentLen := -1
for lines := 0; ; lines++ {
if lines >= maxHeaderLines {
return nil, errors.New("RPC header line limit exceeded")
}
var rawLine []byte
for {
chunk, isPrefix, err := r.ReadLine()
if err != nil {
return nil, err
}
if len(rawLine)+len(chunk) > maxHeaderBytes {
return nil, errors.New("RPC header line exceeds 8 KiB limit")
}
rawLine = append(rawLine, chunk...)
if !isPrefix {
break
}
}
line := string(rawLine)
if line == "" {
break
}
k, v, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 || n > maxRPCFrameBytes {
return nil, fmt.Errorf("invalid Content-Length %q", v)
}
contentLen = n
}
}
if contentLen < 0 {
return nil, errors.New("missing Content-Length header")
}
buf := make([]byte, contentLen)
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
return buf, nil
}