rpc

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package rpc defines the JSON-RPC 2.0 wire types and method/event constants shared between shardflowd's server and shardflow's client.

Index

Constants

View Source
const (
	CodeParseError     = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternalError  = -32603
)

JSON-RPC 2.0 standard error codes.

View Source
const (
	CodeUnknownTarget   = -32000
	CodeOutOfCIDR       = -32001
	CodeGatewayIsSelf   = -32002
	CodeIfaceDown       = -32003
	CodePcapPathInvalid = -32004
)

ShardFlow-specific error codes (range -32000..-32099 per §5.1).

View Source
const (
	MethodScan        = "Scan"
	MethodDevicesList = "Devices.List"
	MethodDevicesGet  = "Devices.Get"
	MethodPolicySet   = "Policy.Set"
	MethodPolicyClear = "Policy.Clear"
	MethodPolicyList  = "Policy.List"
	MethodStats       = "Stats"
	MethodSessionGet  = "Session.Get"
)

Method names, exported as constants so client and server can't drift.

View Source
const (
	EventDeviceDiscovered = "device.discovered"
	EventDeviceUpdated    = "device.updated"
	EventDeviceEvicted    = "device.evicted"
	EventPolicyApplied    = "policy.applied"
	EventCountersTick     = "counters.tick"
	EventPcapRotated      = "pcap.rotated"
	EventIfaceDown        = "iface.down"
	EventIfaceUp          = "iface.up"
)

Event method names.

Variables

This section is empty.

Functions

func BuildHandlers

func BuildHandlers(d *HandlerDeps) map[string]Handler

BuildHandlers returns the method table from a HandlerDeps. The deps are taken by pointer so the embedded applyMu is shared across closures.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a JSON-RPC 2.0 client that demuxes responses from server-pushed events.

func Dial

func Dial(sockPath string) (*Client, error)

Dial connects to a daemon at sockPath.

func (*Client) Call

func (c *Client) Call(ctx context.Context, method string, params any, out any) error

Call invokes method with params (any JSON-encodable value or nil) and decodes the response into out (pointer or nil).

func (*Client) Close

func (c *Client) Close() error

Close terminates the connection.

func (*Client) Dropped

func (c *Client) Dropped() uint64

Dropped returns the cumulative count of events the client had to discard because the consumer wasn't draining Events() fast enough. Monotonically increasing; non-zero values indicate the UI is missing state updates.

func (*Client) Events

func (c *Client) Events() <-chan Event

Events returns a channel of server-pushed events. The channel is closed when the underlying connection is lost (including when Close is called).

type DeviceDTO

type DeviceDTO struct {
	MAC      string `json:"mac"`
	IP       string `json:"ip"`
	Hostname string `json:"hostname"`
	Vendor   string `json:"vendor"`          // OUI vendor (silicon maker)
	Model    string `json:"model,omitempty"` // SSDP SERVER (firmware/device kind)
	LastSeen string `json:"last_seen"`       // RFC 3339; time.Time also marshals OK but string keeps the wire stable
	Policy   string `json:"policy,omitempty"`
}

DeviceDTO is the wire form of devicestore.Device. Necessary because net.HardwareAddr and net.IP marshal as base64 byte arrays in JSON, while every consumer (CLI table, --json, TUI, integration tests) expects the dotted/colon string form. Wire conversion happens in the RPC handlers.

type Error

type Error struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

Error is the JSON-RPC 2.0 error object.

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Event is a server-initiated notification frame (no ID per JSON-RPC §4.1).

type Handler

type Handler func(ctx context.Context, params json.RawMessage) (result any, err *Error)

Handler is a method handler.

type HandlerDeps

type HandlerDeps struct {
	Store    *devicestore.Store
	Compiler *policycompiler.Compiler
	Scanner  func(ctx context.Context) error // a single-shot scan

	// GwMAC and GwIP are the LAN gateway, looked up at daemon startup and
	// passed in here so handlers don't have to re-resolve. Used to build
	// the Target tuple for new policies.
	GwMAC net.HardwareAddr
	GwIP  net.IP

	// Broadcaster pushes a server-initiated event to all connected clients.
	// Concretely this is bound to *Server.Broadcast in the daemon main; it
	// is a function rather than the server struct itself so handlers don't
	// need to know about the transport.
	Broadcaster func(method string, params any)

	// ActivePoisons returns the current count of in-flight poisons (used
	// by Stats). The daemon main wires this to arpengine.Engine.Active.
	ActivePoisons func() int

	// DefaultPcapDir is applied when Policy.Set's pcap_dir is empty. If
	// also empty the handler rejects the request with InvalidParams.
	DefaultPcapDir string

	// Session returns the operator's current connection state (iface,
	// gateway, WiFi association, scan diagnostics). Provided as a
	// callback rather than a snapshot field so the daemon can update
	// scan counters/poison counts without re-wiring deps. Optional —
	// handlers tolerate Session==nil and respond with an empty DTO.
	Session func() SessionDTO
	// contains filtered or unexported fields
}

HandlerDeps is the bundle the daemon constructs to wire the RPC handlers.

func (*HandlerDeps) MarkShuttingDown

func (d *HandlerDeps) MarkShuttingDown()

MarkShuttingDown blocks new Policy.Set/Policy.Clear handler invocations. Called from the daemon's signal handler before tearing down state.

type PolicyEntryDTO

type PolicyEntryDTO struct {
	MAC      string `json:"mac"`
	Kind     string `json:"kind"` // "drop" | "throttle" | "pcap"
	RateKbit int    `json:"rate_kbit,omitempty"`
	PcapDir  string `json:"pcap_dir,omitempty"`
}

PolicyEntryDTO is the wire form of one policycompiler.Spec.

type PolicyKind

type PolicyKind string

PolicyKind enumerates the three v1 policy types.

const (
	PolicyDrop     PolicyKind = "drop"
	PolicyThrottle PolicyKind = "throttle"
	PolicyPcap     PolicyKind = "pcap"
)

type PolicySpec

type PolicySpec struct {
	// Target accepts either an IPv4 address or a MAC. The daemon resolves
	// IP→MAC at command time via devicestore.
	Target   string     `json:"target"`
	Kind     PolicyKind `json:"kind"`
	RateKbit int        `json:"rate_kbit,omitempty"` // throttle only
	PcapDir  string     `json:"pcap_dir,omitempty"`  // pcap only; empty = default
}

PolicySpec is the params shape for Policy.Set.

type Request

type Request struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id,omitempty"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

Request is a JSON-RPC 2.0 request frame.

type Response

type Response struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      json.RawMessage `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *Error          `json:"error,omitempty"`
}

Response is a JSON-RPC 2.0 response frame. Exactly one of Result or Error is set.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a JSON-RPC 2.0 server with broadcast-event support.

Broadcast model: each connected client gets a writer goroutine that drains its own bounded send queue. Broadcast appends to the queue and never blocks on slow/dead peers — a hung Unix socket on client A cannot stall events to client B. On Write error the client is pruned. On queue overflow event broadcasts are dropped (counted), while RPC responses force-disconnect the client (response loss desyncs the request stream).

func NewServer

func NewServer(h map[string]Handler) *Server

NewServer constructs a Server with the given method table.

func (*Server) Broadcast

func (s *Server) Broadcast(method string, params any)

Broadcast sends a notification to every connected client. Non-blocking: queues onto each client's send channel, drops on overflow rather than stalling the caller. Dropped events are counted per client.

func (*Server) DroppedEvents

func (s *Server) DroppedEvents() uint64

DroppedEvents returns the total events dropped across all live clients since their connections opened. Used by the daemon to emit a periodic warning when consumers can't keep up.

func (*Server) HasClients

func (s *Server) HasClients() bool

HasClients reports whether any clients are currently connected. The daemon uses this to skip purely informational broadcasts (the 1 Hz counters tick) when nobody is listening — saves ~3500 idle Marshal+ queue ops per hour with zero observable behaviour change.

func (*Server) Listen

func (s *Server) Listen(ctx context.Context, path string) error

Listen binds the Unix socket at path and serves until ctx is cancelled or Stop is called. The socket is created with mode 0600 (owner-only).

func (*Server) Stop

func (s *Server) Stop() error

Stop closes the listener; in-flight connections drain naturally.

type SessionDTO

type SessionDTO struct {
	Iface   string `json:"iface"`
	MAC     string `json:"mac"`
	IP      string `json:"ip"`
	CIDR    string `json:"cidr"` // e.g. "10.0.0.42/24"
	Gateway string `json:"gateway"`
	GwMAC   string `json:"gw_mac"`

	Wireless   bool    `json:"wireless"`
	SSID       string  `json:"ssid,omitempty"`
	BSSID      string  `json:"bssid,omitempty"`
	SignalDBm  int     `json:"signal_dbm,omitempty"`
	TxRateMbit float64 `json:"tx_rate_mbit,omitempty"`
	FreqMHz    int     `json:"freq_mhz,omitempty"`

	PoisonsActive       int    `json:"poisons_active"`
	ArpWriteFailures    int    `json:"arp_write_failures"`
	ApIsolationLikely   bool   `json:"ap_isolation_likely"`
	SendRedirectsActive bool   `json:"send_redirects_active"`
	ForwardingEnabled   bool   `json:"forwarding_enabled"`
	DevicesTotal        int    `json:"devices_total"`
	LastScanAt          string `json:"last_scan_at,omitempty"` // RFC 3339
	LastScanReplies     int    `json:"last_scan_replies"`      // unique reply MACs
}

SessionDTO describes the operator's connection at a moment in time: the network they're pentesting (iface, IP, gateway, optionally WiFi SSID/BSSID/signal) plus diagnostic counters from the most recent scan.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL