builtins

package
v0.0.24 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxJournalQueryEntries is the hard per-invocation entry bound shared by
	// journal builtins and backends.
	MaxJournalQueryEntries = 1000
	// MaxJournalQueryUnits bounds exact unit scopes before any backend work.
	MaxJournalQueryUnits = 32
	// MaxSystemServiceOperands bounds exact unit selectors accepted by one
	// systemctl invocation, including the configured readable set used by
	// list-units.
	MaxSystemServiceOperands = 32
	// MaxSystemServiceNameBytes matches systemd's maximum unit-name payload
	// (UNIT_NAME_MAX minus the terminating NUL).
	MaxSystemServiceNameBytes = 255
	// MaxSystemServiceFieldBytes bounds every string returned by a manager
	// backend before it reaches command formatting.
	MaxSystemServiceFieldBytes = 64 * 1024
)
View Source
const MaxFileRemovalsPerRun = 100

MaxFileRemovalsPerRun is the cumulative number of files that may be removed through CallContext.Remove across an entire Runner.Run call, including every loop iteration, subshell, and pipeline stage. It exists because the per-invocation cap in the rm builtin bounds only a single mistaken glob: `for f in *; do rm "$f"; done` and `find … | xargs -n1 rm` each drive an unbounded number of single-file invocations past it. The run-wide budget is the only limit that matches the threat model of an AI agent writing ordinary loop idioms.

The value is deliberately much larger than the per-invocation cap: a run-wide budget must not break real remediation scripts (rotating a few dozen stale log files is a legitimate cleanup), while still bounding an unattended run to an amount of damage an operator can reason about and recover from. It is a fixed constant rather than a RunnerOption on purpose — one number that every deployment shares is harder to misconfigure than a knob, and no caller has yet shown a bulk-cleanup need that justifies the extra configuration surface. Both the number and the configurability question are open for maintainer sign-off.

View Source
const (
	// SystemdJournaldService is the exact service name used for journal-wide
	// operations such as kernel log reads, disk usage, rotation, and vacuuming.
	SystemdJournaldService = "systemd-journald.service"
)

Variables

View Source
var ErrRemoveBudgetExceeded = errors.New("run-wide file removal budget exceeded")

ErrRemoveBudgetExceeded is returned by CallContext.Remove once the run-wide MaxFileRemovalsPerRun budget is exhausted. The file is not removed. Builtins should stop processing further operands when they see it, since every subsequent removal in the same run will fail the same way.

View Source
var ErrSystemdUnsupported = errors.New("systemd operation is not supported")

ErrSystemdUnsupported reports that the current platform cannot provide a requested systemd operation.

View Source
var ErrVarStorageExceeded = errors.New("variable storage limit exceeded")

ErrVarStorageExceeded is returned by CallContext.SetVar when the assignment would push the runner's total variable storage past its cap. This is a script-aborting condition: AST-level assignments treat it the same way (see interp/vars.go), so state-mutating builtins should propagate it via Result.Exiting=true rather than continuing with status 1, matching bash's resource-cap DoS guard.

Functions

func DefaultRemediationDeniedMessage added in v0.0.24

func DefaultRemediationDeniedMessage(name string) string

DefaultRemediationDeniedMessage returns the stderr text written when a RemediationOnly builtin is invoked in read-only mode and the command does not set RemediationDeniedMessage.

func IsBrokenPipe added in v0.0.11

func IsBrokenPipe(err error) bool

IsBrokenPipe reports whether err is a broken-pipe (EPIPE) error, which occurs when writing to a pipe whose read end has been closed. In bash this triggers SIGPIPE which silently terminates the writer; builtins should use this to suppress error messages on pipe closure.

func IsSupportedSystemdUnitType added in v0.0.24

func IsSupportedSystemdUnitType(unitType string) bool

IsSupportedSystemdUnitType reports whether unitType is part of the fixed systemd unit-type surface shared by systemctl and its manager backend.

func Names

func Names() []string

Names returns a sorted list of all registered builtin command names.

func NoFlags

func NoFlags(fn HandlerFunc) func(*FlagSet) HandlerFunc

NoFlags wraps a HandlerFunc in the MakeFlags format for commands that declare no flags.

func NormalizeBareNumberArg added in v0.0.10

func NormalizeBareNumberArg(args []string, valueFlags []string) []string

NormalizeBareNumberArg rewrites legacy -N shorthand (e.g. -5) to -n N so that pflag can parse it. Only a bare -<digits> token in the first argument position is rewritten; -<digits> appearing later in the argument list is left unchanged (matching GNU head/tail behavior where the obsolete form is only accepted as the first option). Processing stops at "--".

When the first argument is a value-taking flag (-n, -c, --lines, --bytes), the second argument is its value and must not be rewritten — even if it looks like -<digits> (e.g. "head -n -9223372036854775809").

valueFlags lists the flags that consume the next argument as a value (e.g. []string{"-n", "-c", "--lines", "--bytes"}).

func SafeOperand added in v0.0.24

func SafeOperand(s string) string

SafeOperand escapes control characters in s — newlines, tabs, ESC, and other non-printable bytes — so the result can be interpolated into a single-quoted error message (e.g. "cmd: extra operand '%s'") without letting a crafted operand forge additional diagnostic lines or inject terminal/log control sequences into stderr. It also escapes Unicode line/ paragraph separators (U+2028, U+2029) and format characters (e.g. the bidi override U+202E), since unicode.IsControl doesn't cover those but Unicode-aware log viewers still act on them to split or visually reorder the diagnostic. It intentionally does not escape the single quote itself or otherwise shell-quote the value; it only neutralizes runes that are dangerous in a raw stderr stream, mirroring the "literal" tier of GNU coreutils' quotearg rather than its full shell-quoting modes.

func UnsupportedSummary added in v0.0.15

func UnsupportedSummary() []string

UnsupportedSummary returns a concise list of intentionally unsupported rshell functionality for display in the top-level help output.

Types

type AllowedPath added in v0.0.23

type AllowedPath struct {
	Path   string
	Access AllowedPathAccess
}

AllowedPath describes one resolved AllowedPaths sandbox root.

type AllowedPathAccess added in v0.0.23

type AllowedPathAccess string

AllowedPathAccess is the configured filesystem access level for one AllowedPaths root.

const (
	AllowedPathReadOnly  AllowedPathAccess = "read-only"
	AllowedPathReadWrite AllowedPathAccess = "read-write"
)

type CallContext

type CallContext struct {
	Stdout io.Writer
	Stderr io.Writer
	Stdin  io.Reader

	// InLoop is true when the builtin runs inside a for loop.
	InLoop bool

	// LastExitCode is the exit code from the previous command.
	LastExitCode uint8

	// OpenFile opens a file within the shell's path restrictions.
	OpenFile func(ctx context.Context, path string, flags int, mode os.FileMode) (io.ReadWriteCloser, error)

	// ReadDir reads a directory within the shell's path restrictions.
	// Entries are returned sorted by name. Used by builtins like ls
	// that need deterministic sorted output.
	ReadDir func(ctx context.Context, path string) ([]fs.DirEntry, error)

	// OpenDir opens a directory within the shell's path restrictions for
	// incremental reading via ReadDir(n). Caller must close the handle.
	OpenDir func(ctx context.Context, path string) (fs.ReadDirFile, error)

	// IsDirEmpty checks whether a directory is empty by reading at most
	// one entry. More efficient than reading all entries.
	IsDirEmpty func(ctx context.Context, path string) (bool, error)

	// ReadDirLimited reads directory entries, skipping the first offset entries
	// and returning up to maxRead entries sorted by name within the read window.
	// Returns (entries, truncated, error). When truncated is true, the directory
	// contained more entries beyond the returned set.
	ReadDirLimited func(ctx context.Context, path string, offset, maxRead int) ([]fs.DirEntry, bool, error)

	// StatFile returns file info within the shell's path restrictions (follows symlinks).
	StatFile func(ctx context.Context, path string) (fs.FileInfo, error)

	// FileSystemStat returns filesystem-wide metadata for the filesystem
	// containing path. The path is resolved within the shell's path
	// restrictions and symlinks are followed.
	FileSystemStat func(ctx context.Context, path string) (FileSystemInfo, error)

	// LstatFile returns file info within the shell's path restrictions (does not follow symlinks).
	LstatFile func(ctx context.Context, path string) (fs.FileInfo, error)

	// ReadlinkFile returns the destination of a symbolic link within the
	// shell's path restrictions.
	ReadlinkFile func(ctx context.Context, path string) (string, error)

	// AccessFile checks whether the file at path is accessible with the given mode
	// within the shell's path restrictions. Mode: 0x04=read, 0x02=write, 0x01=execute.
	AccessFile func(ctx context.Context, path string, mode uint32) error

	// Truncate sets the size of the file at path within the shell's path
	// restrictions. When create is true, a missing file is created (mode
	// 0666 & ~umask); when create is false, a missing file returns
	// os.ErrNotExist. Negative sizes are rejected. Only available in
	// remediation mode; nil otherwise.
	Truncate func(ctx context.Context, path string, size int64, create bool) error

	// TruncateToZeroIfAtLeast truncates path to zero bytes within the shell's
	// path restrictions when its pre-truncation size is at least minSize.
	// When dryRun is true, it performs the same write-target validation and
	// eligibility check without mutating the file. The size check and truncate
	// share one fd to avoid path-swap races. Missing files are not created.
	// Only available in remediation mode; nil otherwise.
	TruncateToZeroIfAtLeast func(ctx context.Context, path string, minSize int64, dryRun bool) (sizeBefore int64, truncated bool, err error)

	// Remove deletes the file at path within the shell's path restrictions.
	// Directories are always rejected with an error; any other non-directory
	// entry (regular file, symlink, FIFO, socket, device node) may be
	// removed. A symlink argument removes the link itself, not its referent.
	// Only available in remediation mode; nil otherwise.
	//
	// Removals are charged against a cumulative per-run budget of
	// MaxFileRemovalsPerRun files, shared across every invocation, loop
	// iteration, subshell, and pipeline stage in one Runner.Run call. Once the
	// budget is exhausted, Remove returns ErrRemoveBudgetExceeded without
	// touching the file. Failed removals are not charged.
	Remove func(ctx context.Context, path string) error

	// RemediationMode reports whether the shell is running in remediation mode.
	// When false (read-only mode), write-capable builtins such as truncate are
	// not available. Used by the help builtin to partition commands correctly.
	RemediationMode bool

	// PortableErr normalizes an OS error to a POSIX-style message.
	PortableErr func(err error) string

	// Now is the time captured at the start of each Run() call. Builtins
	// should use this instead of calling time.Now() directly, so the time
	// source is consistent across all commands in a single run.
	//
	// Note: this means all builtins within one Run() share the same reference
	// time, whereas bash evaluates each command against its own invocation
	// time. This is an intentional trade-off for consistency within a script
	// run.
	//
	// Run() always sets this before dispatching any builtin; Reset() clears
	// it, so it is always re-set by the next Run() call. The zero value
	// (time.Time{}) is reserved as the unset sentinel; callers constructing
	// CallContext directly (e.g. in tests) must set this to a non-zero value
	// before invoking builtins that use time predicates (find -mmin/-mtime,
	// ls -l).
	Now time.Time

	// FileIdentity extracts canonical file identity from FileInfo.
	// On Unix: dev+inode from Stat_t. On Windows: volume serial + file index
	// via GetFileInformationByHandle. The path parameter is needed on Windows
	// where FileInfo.Sys() lacks identity fields; Unix ignores it.
	FileIdentity func(path string, info fs.FileInfo) (FileID, bool)

	// CommandAllowed reports whether a command name is permitted under the
	// current shell policy. Used by the help builtin to list only executable
	// commands.
	CommandAllowed func(name string) bool

	// AuthorizeSystemd reports whether every operation may be performed under
	// the current shell policy. Implementations must authorize the complete
	// list before a builtin performs any operation so compound requests cannot
	// partially execute.
	AuthorizeSystemd func(operations ...SystemdOperation) error

	// AuthorizeSystemServices is the deprecated unit-only authorization
	// capability retained for compatibility with callers built against the
	// original service allowlist API.
	AuthorizeSystemServices func(action SystemServiceAction, services ...string) error

	// ReadableSystemServices returns the exact, sorted unit selectors granted
	// the read action. The returned slice is a defensive copy. Restricted
	// enumeration commands use this capability instead of listing every unit on
	// the configured systemd target.
	ReadableSystemServices func() []string

	// AllowedSystemServicesList returns the effective, exact unit/action grant
	// pairs sorted by unit and canonical action order. The returned slice is a
	// defensive copy. Used by the help builtin to surface the active systemd
	// capability policy without exposing a mutable authorization map.
	AllowedSystemServicesList func() []SystemdOperation

	// AllowedPathsList returns the resolved absolute paths and configured
	// access modes of the AllowedPaths sandbox roots. An empty/nil slice means
	// no allowed paths are configured, which blocks all filesystem access.
	// Used by the help builtin to surface the active sandbox roots.
	AllowedPathsList func() []AllowedPath

	// WorkDir returns the shell's current working directory (absolute path).
	// Used by builtins that need to compute absolute paths for sub-operations.
	WorkDir func() string

	// HostPrefix returns the configured host-mount prefix used by
	// container-style sandboxes to translate host-absolute paths
	// (e.g. /var/log/pods/...) into the prefixed paths the sandbox can
	// open (e.g. /mnt/host/var/log/pods/...). Returns "" when no prefix
	// is configured. Builtins that resolve absolute symlink targets
	// (e.g. pwd -P) use this to keep their output consistent with what
	// the sandbox itself accepts.
	HostPrefix func() string

	// CanonicalizeRootPrefix translates a configured AllowedPaths root
	// prefix in absPath to that root's canonical (symlink-resolved)
	// form. Used by `pwd -P` so that when the sandbox root is itself a
	// symlink (e.g. /tmp/link -> /tmp/real), the printed path reflects
	// the resolution that os.Root has already followed implicitly. If
	// absPath is outside every root or the matching root is not a
	// symlink, the input is returned unchanged.
	CanonicalizeRootPrefix func(absPath string) string

	// ChangeDir mutates the shell's working directory. The supplied path
	// must be absolute. Implementations validate that the target exists,
	// is a directory, and lies inside AllowedPaths; on any failure the
	// previous working directory is preserved and an error is returned.
	// On success, $OLDPWD is set to the previous directory and $PWD is
	// set to absDir. Used exclusively by the cd builtin.
	ChangeDir func(absDir string) error

	// LookupEnvVar reads an environment variable from the shell's
	// overlay environment. Returns (value, true) if the variable is
	// set, ("", false) otherwise. The cd builtin uses this to resolve
	// $HOME (no-arg form) and $OLDPWD (the `cd -` form) without
	// requiring a full WriteEnviron handle on every CallContext.
	LookupEnvVar func(name string) (string, bool)

	// RunCommand executes a builtin command within the shell's sandbox.
	// dir overrides the working directory for path resolution.
	// Returns the command's exit code.
	RunCommand func(ctx context.Context, dir string, name string, args []string) (uint8, error)

	// RunCommandWithStdin is like RunCommand but lets the caller supply a
	// stdin reader for the child. Used by xargs to give children empty
	// stdin (matching POSIX behavior of redirecting child stdin from
	// /dev/null) while still reading items from the parent's stdin itself.
	// If nil, callers should fall back to RunCommand.
	RunCommandWithStdin func(ctx context.Context, dir string, name string, args []string, stdin io.Reader) (uint8, error)

	// SetVar assigns a value to a shell variable in the calling shell's
	// scope. Returns an error if the value exceeds the per-variable size
	// limit or if the total variable-storage cap would be exceeded.
	// Used by builtins that mutate parent-shell state, such as read.
	SetVar func(name, value string) error

	// GetVar returns the value of a shell variable. The bool reports
	// whether the variable was set; an unset variable returns ("", false).
	// Used by builtins that need to consult shell state, such as read
	// reading IFS for field-splitting.
	GetVar func(name string) (value string, ok bool)

	// Proc provides access to the proc filesystem for the ps and lsof
	// builtins. The path is fixed at construction time and cannot be
	// overridden by callers.
	Proc *ProcProvider

	// Systemd contains structured backends for systemd-aware builtins. Target
	// paths and transports are fixed by trusted runner configuration.
	Systemd *SystemdServices
}

CallContext provides the capabilities available to builtin commands. It is created by the Runner for each builtin invocation.

func (*CallContext) Errf

func (c *CallContext) Errf(format string, a ...any)

Errf writes a formatted string to stderr.

func (*CallContext) Out

func (c *CallContext) Out(s string)

Out writes a string to stdout.

func (*CallContext) Outf

func (c *CallContext) Outf(format string, a ...any)

Outf writes a formatted string to stdout.

type Command

type Command struct {
	Name        string
	Description string
	Help        string
	MakeFlags   func(*FlagSet) HandlerFunc

	// NormalizeArgs, if non-nil, rewrites raw argument slices before pflag
	// parsing. This allows commands to support legacy flag syntax that pflag
	// cannot handle natively (e.g. head/tail -5 → -n 5).
	NormalizeArgs func(args []string) []string

	// RemediationOnly marks a builtin as only available in remediation mode.
	// The interpreter refuses to dispatch such a command — before flag
	// parsing, so --help is refused too — when the shell is in read-only
	// mode, and the help builtin moves it to the disabled list. Builtins
	// keep their own equivalent check as defence in depth; the dispatch
	// gate is what makes the flag load-bearing for future builtins.
	RemediationOnly bool

	// RemediationDeniedMessage overrides the stderr text written by the
	// dispatch-level read-only refusal. It must end with a newline. When
	// empty, DefaultRemediationDeniedMessage is used. Only meaningful
	// together with RemediationOnly.
	RemediationDeniedMessage string
}

Command pairs a builtin name with its flag-declaring factory. MakeFlags registers any flags on the provided FlagSet and returns the bound handler. Commands that accept no flags may ignore fs via NoFlags.

func (Command) Register

func (c Command) Register()

Register adds the Command to the builtin registry. For each invocation the framework creates a fresh *FlagSet, passes it to MakeFlags so the command can register its flags, parses the raw args, writes any error to stderr (exit 1), and then calls the bound handler with positional args only.

If MakeFlags registers no flags (e.g. via NoFlags), the framework skips parsing entirely and passes all raw args to the handler unchanged. This lets commands like echo treat flag-shaped literals (e.g. -n) correctly.

type CommandMeta

type CommandMeta struct {
	Name            string
	Description     string
	Help            string
	HasFlags        bool // true when MakeFlags registers at least one flag
	RemediationOnly bool // true when the command requires remediation mode

	// RemediationDeniedMessage is the stderr text the interpreter writes
	// when the command is dispatched in read-only mode. Non-empty exactly
	// when RemediationOnly is true.
	RemediationDeniedMessage string
}

CommandMeta holds metadata about a registered builtin command.

func Meta

func Meta(name string) (CommandMeta, bool)

Meta returns the metadata for a registered builtin command.

type FeatureMeta added in v0.0.15

type FeatureMeta struct {
	Name        string
	Description string
	Supported   []string
	Unsupported []string
	Notes       []string
}

FeatureMeta holds metadata for an rshell language/runtime feature exposed by the help builtin. The list is maintained in Go code so `help` output stays deterministic and can be validated against builtin command names.

func Feature added in v0.0.15

func Feature(name string) (FeatureMeta, bool)

Feature returns the metadata for a named rshell feature. The returned FeatureMeta's Supported/Unsupported/Notes slices are independent copies — callers may freely mutate them without affecting the registry.

func Features added in v0.0.15

func Features() []FeatureMeta

Features returns rshell features in display order. The returned slice and each FeatureMeta's Supported/Unsupported/Notes slices are independent copies — callers may freely mutate them without affecting the registry.

type FileID

type FileID struct {
	Dev uint64
	Ino uint64
}

FileID is a comparable file identity for cycle detection. On Unix: device + inode. On Windows: volume serial + file index. Used as map key for visited-set tracking.

type FileSystemInfo added in v0.0.24

type FileSystemInfo struct {
	ID          uint64
	IDAvailable bool

	NameMax          uint64
	NameMaxAvailable bool

	TypeID          uint64
	TypeIDAvailable bool
	TypeName        string

	IOBlockSize          uint64
	FundamentalBlockSize uint64
	Blocks               uint64
	BlocksFree           uint64
	BlocksAvailable      uint64

	Files          uint64
	FilesFree      uint64
	FilesAvailable bool
}

FileSystemInfo is the normalized subset of filesystem metadata exposed to builtins such as stat. Availability flags distinguish unsupported values from legitimate zero counts.

type Flag

type Flag = pflag.Flag

Flag is a type alias for pflag.Flag, exposed so command files can use FlagSet.Visit without importing pflag directly.

type FlagSet

type FlagSet = pflag.FlagSet

FlagSet is a type alias for pflag.FlagSet. Command files receive a *FlagSet from the framework without needing to import pflag directly (the builtins package is always allowed by the import allowlist).

type HandlerFunc

type HandlerFunc func(ctx context.Context, callCtx *CallContext, args []string) Result

HandlerFunc is the bound handler called by the framework after flags are parsed. args contains only the positional (non-flag) arguments.

func Lookup

func Lookup(name string) (HandlerFunc, bool)

Lookup returns the handler for a builtin command.

type JournalCleaner added in v0.0.24

type JournalCleaner interface {
	VacuumJournal(ctx context.Context, request JournalVacuumRequest) (JournalVacuumResult, error)
}

JournalCleaner performs request-bounded cleanup of archived journal files.

type JournalEntry added in v0.0.24

type JournalEntry struct {
	Timestamp  time.Time
	Hostname   string
	Identifier string
	PID        string
	Message    string
}

JournalEntry contains only the fields a journalctl builtin may expose. The backend deliberately does not return arbitrary journal fields.

type JournalQuery added in v0.0.24

type JournalQuery struct {
	Units       []string
	Kernel      bool
	CurrentBoot bool
	Since       time.Time
	MaxEntries  int
}

JournalQuery is the bounded, structured query accepted by the trusted journal backend. Callers cannot provide raw journal matches or paths.

type JournalReader added in v0.0.24

type JournalReader interface {
	ReadJournal(ctx context.Context, query JournalQuery, yield func(JournalEntry) error) error
}

JournalReader reads a bounded journal query and yields entries oldest first.

type JournalRotator added in v0.0.24

type JournalRotator interface {
	RotateJournal(ctx context.Context) error
}

JournalRotator synchronously archives the active journals for the selected target. Implementations return only after journald reports completion.

type JournalStorageReader added in v0.0.24

type JournalStorageReader interface {
	JournalDiskUsage(ctx context.Context) (JournalUsage, error)
}

JournalStorageReader exposes read-only journal storage metadata.

type JournalUsage added in v0.0.24

type JournalUsage struct {
	Bytes uint64
	Files int
}

JournalUsage is the allocated storage consumed by the selected target's active and archived journal files.

type JournalVacuumRequest added in v0.0.24

type JournalVacuumRequest struct {
	Now      time.Time
	Before   time.Time
	MaxBytes uint64
	DryRun   bool
}

JournalVacuumRequest contains only bounded cleanup predicates. Before is an absolute archive mtime cutoff. MaxBytes is a target for the total allocated journal bytes of the selected target (active plus archived, the same set JournalDiskUsage reports); only archives at or before the cutoff may ever be deleted to approach it.

type JournalVacuumResult added in v0.0.24

type JournalVacuumResult struct {
	Files          int
	Bytes          uint64
	RemainingBytes uint64
}

JournalVacuumResult reports the cleanup selected or completed without exposing host paths or journal filenames. RemainingBytes is the total allocated journal storage that remains (or would remain, for a dry run) after the reported deletions, so callers can see when a size target could not be reached without deleting protected files.

type ProcProvider added in v0.0.6

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

ProcProvider gives builtins controlled access to the proc filesystem. The path is fixed at construction time and cannot be overridden by callers.

func NewProcProvider added in v0.0.6

func NewProcProvider(path string) *ProcProvider

NewProcProvider returns a ProcProvider for the given proc filesystem path. If path is empty, DefaultProcPath ("/proc") is used.

func (*ProcProvider) GetByPIDs added in v0.0.6

func (p *ProcProvider) GetByPIDs(ctx context.Context, pids []int) ([]procinfo.ProcInfo, error)

GetByPIDs returns process info for the given PIDs.

func (*ProcProvider) GetByPIDsWithMetrics added in v0.0.24

func (p *ProcProvider) GetByPIDsWithMetrics(ctx context.Context, pids []int, metrics procinfo.Metrics) ([]procinfo.ProcInfo, error)

GetByPIDsWithMetrics returns process info for the given PIDs and requests optional resource measurements from the platform backend.

func (*ProcProvider) GetSession added in v0.0.6

func (p *ProcProvider) GetSession(ctx context.Context) ([]procinfo.ProcInfo, error)

GetSession returns processes in the current process session.

func (*ProcProvider) GetSessionWithMetrics added in v0.0.24

func (p *ProcProvider) GetSessionWithMetrics(ctx context.Context, metrics procinfo.Metrics) ([]procinfo.ProcInfo, error)

GetSessionWithMetrics returns current-session processes and requests optional resource measurements from the platform backend.

func (*ProcProvider) ListAll added in v0.0.6

func (p *ProcProvider) ListAll(ctx context.Context) ([]procinfo.ProcInfo, error)

ListAll returns all running processes.

func (*ProcProvider) ListAllWithMetrics added in v0.0.24

func (p *ProcProvider) ListAllWithMetrics(ctx context.Context, metrics procinfo.Metrics) ([]procinfo.ProcInfo, error)

ListAllWithMetrics returns all running processes and requests optional resource measurements from the platform backend.

func (*ProcProvider) ListOpenFiles added in v0.0.24

func (p *ProcProvider) ListOpenFiles(ctx context.Context, pids []int, filter procfd.ProcessFilter) ([]procfd.OpenFile, error)

ListOpenFiles returns open file descriptors for the given PIDs (nil or empty selects every process), restricted to processes filter accepts (nil filter matches every process). Linux only; returns procfd.ErrNotSupported on other platforms.

func (*ProcProvider) ProcPath added in v0.0.8

func (p *ProcProvider) ProcPath() string

ProcPath returns the configured proc filesystem path (e.g. "/proc" or "/host/proc").

func (*ProcProvider) ReadKernelFile added in v0.0.8

func (p *ProcProvider) ReadKernelFile(name string) (string, error)

ReadKernelFile reads a single-line value from a /proc/sys/kernel/ pseudo-file. name is the filename relative to sys/kernel/ (e.g. "ostype", "hostname"). The returned value is trimmed of trailing whitespace.

func (*ProcProvider) ReadMaps added in v0.0.24

func (p *ProcProvider) ReadMaps(ctx context.Context, pid int, extended bool) (string, []procmaps.Mapping, error)

ReadMaps returns the short process name and current memory mappings for pid, for the pmap builtin. When extended is true, per-mapping RSS and Dirty are populated if the platform backend supports it.

type Result

type Result struct {
	// Code is the exit status code.
	Code uint8

	// Exiting signals that the shell should exit (set by the "exit" builtin).
	Exiting bool

	// BreakN > 0 means break out of N enclosing loops.
	BreakN int

	// ContinueN > 0 means continue from N enclosing loops.
	ContinueN int
}

Result captures the outcome of executing a builtin command.

type SystemServiceAction added in v0.0.23

type SystemServiceAction string

SystemServiceAction identifies an operation that a builtin may perform on an explicitly configured systemd unit. The historical "Service" name is retained for API compatibility; grants may name any exact unit type, such as .service, .timer, or .socket.

const (
	SystemServiceRead    SystemServiceAction = "read"
	SystemServiceClean   SystemServiceAction = "clean"
	SystemServiceStart   SystemServiceAction = "start"
	SystemServiceStop    SystemServiceAction = "stop"
	SystemServiceReload  SystemServiceAction = "reload"
	SystemServiceRestart SystemServiceAction = "restart"
	SystemServiceEnable  SystemServiceAction = "enable"
	SystemServiceDisable SystemServiceAction = "disable"
)

type SystemServiceController added in v0.0.24

type SystemServiceController interface {
	RunSystemServiceJobs(ctx context.Context, action SystemServiceJobAction, services []string) error
	EnableSystemServices(ctx context.Context, services []string) error
	DisableSystemServices(ctx context.Context, services []string) error
}

SystemServiceController performs only fixed unit operations. Job methods return after systemd reports completion for every requested unit.

type SystemServiceJobAction added in v0.0.24

type SystemServiceJobAction string

SystemServiceJobAction is the fixed set of runtime jobs exposed by the restricted systemctl backend.

const (
	SystemServiceJobStart   SystemServiceJobAction = "start"
	SystemServiceJobStop    SystemServiceJobAction = "stop"
	SystemServiceJobReload  SystemServiceJobAction = "reload"
	SystemServiceJobRestart SystemServiceJobAction = "restart"
)

type SystemServiceListRequest added in v0.0.24

type SystemServiceListRequest struct {
	Services        []string
	IncludeInactive bool
}

SystemServiceListRequest selects exact pre-authorized units for bounded list-units output. IncludeInactive permits loading inactive configured units; false restricts the result to units already loaded by systemd.

type SystemServiceState added in v0.0.24

type SystemServiceState struct {
	Name          string
	CanonicalName string
	Description   string
	LoadState     string
	ActiveState   string
	SubState      string
	UnitFileState string
	MainPID       uint32
	Result        string
	JobID         uint32
}

SystemServiceState is the fixed, bounded unit state exposed to the restricted systemctl builtin. The historical "Service" name is retained for API compatibility. Name preserves the exact authorized selector; CanonicalName is used only to validate manager replies and is not an arbitrary D-Bus object path.

type SystemServiceStateReader added in v0.0.24

type SystemServiceStateReader interface {
	ListSystemServices(ctx context.Context, request SystemServiceListRequest) ([]SystemServiceState, error)
	InspectSystemServices(ctx context.Context, services []string) ([]SystemServiceState, error)
}

SystemServiceStateReader exposes fixed unit state without a generic property, object-path, or transport API.

type SystemdOperation added in v0.0.24

type SystemdOperation struct {
	Service string
	Action  SystemServiceAction
}

SystemdOperation is one unit action that must be authorized before a builtin interacts with systemd.

type SystemdServices added in v0.0.24

type SystemdServices struct {
	Journal        JournalReader
	JournalStorage JournalStorageReader
	JournalCleaner JournalCleaner
	JournalRotator JournalRotator
	ServiceState   SystemServiceStateReader
	ServiceControl SystemServiceController
}

SystemdServices contains the trusted backends available to systemd-aware builtins. Additional manager and journal-maintenance interfaces can be added here without exposing transports to command implementations.

Directories

Path Synopsis
Package breakcmd implements the break builtin command.
Package breakcmd implements the break builtin command.
Package cat implements the cat builtin command.
Package cat implements the cat builtin command.
Package cd implements the cd builtin command.
Package cd implements the cd builtin command.
Package continuecmd implements the continue builtin command.
Package continuecmd implements the continue builtin command.
Package cut implements the cut builtin command.
Package cut implements the cut builtin command.
Package df implements the df builtin command.
Package df implements the df builtin command.
Package du implements the du builtin command.
Package du implements the du builtin command.
Package echo implements the echo builtin command.
Package echo implements the echo builtin command.
Package exit implements the exit builtin command.
Package exit implements the exit builtin command.
Package falsecmd implements the false builtin command.
Package falsecmd implements the false builtin command.
Package find implements the find builtin command.
Package find implements the find builtin command.
Package free implements the free builtin command.
Package free implements the free builtin command.
Package grep implements the grep builtin command.
Package grep implements the grep builtin command.
Package head implements the head builtin command.
Package head implements the head builtin command.
Package help implements the help builtin command.
Package help implements the help builtin command.
internal
diskstats
Package diskstats reads mounted-filesystem usage information from the kernel and presents it as a normalised cross-platform Mount struct.
Package diskstats reads mounted-filesystem usage information from the kernel and presents it as a normalised cross-platform Mount struct.
flagparser
Package flagparser bridges between pflag and the GNU-getopt wording that rshell builtins are expected to match.
Package flagparser bridges between pflag and the GNU-getopt wording that rshell builtins are expected to match.
meminfo
Package meminfo reads host memory and swap usage from the kernel and presents it as a normalised cross-platform Info struct.
Package meminfo reads host memory and swap usage from the kernel and presents it as a normalised cross-platform Info struct.
procfd
Package procfd provides Linux open-file-descriptor enumeration for the lsof builtin.
Package procfd provides Linux open-file-descriptor enumeration for the lsof builtin.
procinfo
Package procinfo provides OS-specific process information for the ps builtin.
Package procinfo provides OS-specific process information for the ps builtin.
procmaps
Package procmaps reads per-process virtual memory mappings for the pmap builtin and presents them as a normalised cross-platform slice of Mapping.
Package procmaps reads per-process virtual memory mappings for the pmap builtin and presents them as a normalised cross-platform slice of Mapping.
procnetroute
Package procnetroute reads the Linux IPv4 routing table from /proc/net/route.
Package procnetroute reads the Linux IPv4 routing table from /proc/net/route.
procnetsocket
Package procnetsocket reads Linux socket state from /proc/net/.
Package procnetsocket reads Linux socket state from /proc/net/.
procpath
Package procpath provides the single canonical default path to the Linux proc filesystem.
Package procpath provides the single canonical default path to the Linux proc filesystem.
procsyskernel
Package procsyskernel reads Linux kernel information from /proc/sys/kernel/.
Package procsyskernel reads Linux kernel information from /proc/sys/kernel/.
sizeparse
Package sizeparse parses coreutils-style non-negative byte sizes.
Package sizeparse parses coreutils-style non-negative byte sizes.
sysinfo
Package sysinfo provides cross-platform access to system uptime and load average data.
Package sysinfo provides cross-platform access to system uptime and load average data.
vmstat
Package vmstat reads virtual-memory, swap, IO-paging, and CPU pressure counters from the kernel and presents them as a normalised cross-platform Stats struct.
Package vmstat reads virtual-memory, swap, IO-paging, and CPU pressure counters from the kernel and presents them as a normalised cross-platform Stats struct.
winnet
Package winnet provides socket enumeration for Windows via iphlpapi.dll.
Package winnet provides socket enumeration for Windows via iphlpapi.dll.
winpoll
Package winpoll provides a non-consuming readability probe for Windows file handles.
Package winpoll provides a non-consuming readability probe for Windows file handles.
Package ip implements the ip builtin command.
Package ip implements the ip builtin command.
Package journalctl implements a bounded systemd journal query builtin.
Package journalctl implements a bounded systemd journal query builtin.
Package logrotate implements a remediation-mode log truncation builtin.
Package logrotate implements a remediation-mode log truncation builtin.
Package ls implements the ls builtin command.
Package ls implements the ls builtin command.
Package lsof implements the lsof builtin command.
Package lsof implements the lsof builtin command.
Package ping implements the ping builtin command.
Package ping implements the ping builtin command.
Package pmap implements the pmap builtin command.
Package pmap implements the pmap builtin command.
Package printf implements the printf builtin command.
Package printf implements the printf builtin command.
Package ps implements the ps builtin command.
Package ps implements the ps builtin command.
Package pwd implements the pwd builtin command.
Package pwd implements the pwd builtin command.
Package read implements the read builtin command.
Package read implements the read builtin command.
Package rm implements the rm builtin command.
Package rm implements the rm builtin command.
Package sed implements the sed builtin command.
Package sed implements the sed builtin command.
Package sort implements the sort builtin command.
Package sort implements the sort builtin command.
Package ss implements the ss builtin command.
Package ss implements the ss builtin command.
Package stat implements the stat filesystem-status builtin.
Package stat implements the stat filesystem-status builtin.
Package strings_cmd implements the strings builtin command.
Package strings_cmd implements the strings builtin command.
Package systemctl implements a capability-bounded systemd unit manager.
Package systemctl implements a capability-bounded systemd unit manager.
Package tail implements the tail builtin command.
Package tail implements the tail builtin command.
Package testcmd implements the POSIX test and [ builtin commands.
Package testcmd implements the POSIX test and [ builtin commands.
Package testutil provides shared test helpers for builtin command tests.
Package testutil provides shared test helpers for builtin command tests.
Package tr implements the tr builtin command.
Package tr implements the tr builtin command.
Package truecmd implements the true builtin command.
Package truecmd implements the true builtin command.
Package truncate implements the truncate builtin command.
Package truncate implements the truncate builtin command.
Package uname implements the uname builtin command.
Package uname implements the uname builtin command.
Package uniq implements the uniq builtin command.
Package uniq implements the uniq builtin command.
Package uptime implements the uptime builtin command.
Package uptime implements the uptime builtin command.
Package vmstat implements the vmstat builtin command.
Package vmstat implements the vmstat builtin command.
Package wc implements the wc builtin command.
Package wc implements the wc builtin command.
Package xargs implements the xargs builtin command.
Package xargs implements the xargs builtin command.

Jump to

Keyboard shortcuts

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