Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios

SDK Basics

Single-page view · as markdown

The Peios C SDK

Peios / Developing for Peios / SDK Basics

The Peios C software development kit (SDK) provides libraries for programs that use Peios security, registry, and event services. Use libpeios for application services and librsi for a registry storage backend.

Both libraries expose a C application binary interface (ABI). C++ and other languages can call that interface without depending on the libraries' internal Rust implementation.

Choosing a library #

The libraries have separate roles and can be linked into the same program:

LibraryRoleHeaderLink option
libpeiosSecurity, registry clients, and events<peios.h>-lpeios
librsiRegistry storage backends<rsi.h>-lrsi

The internal peios-cabi crate supplies allocation, error handling, and system-call helpers. Applications do not link it directly.

The SDK repository releases these components together. The shared objects retain separate compatibility boundaries: libpeios.so.0 and librsi.so.0. A package version identifies a release; the shared object's SONAME identifies its binary interface. An SDK release does not imply a kernel release.

Portable data and kernel services #

Security identifiers, access control lists, security descriptors, and MessagePack values can be built and parsed in userspace. These operations do not need a running Peios kernel.

Opening tokens, accessing registry keys, and sending or receiving kernel events require the corresponding Peios kernel services. Building a program on a development host does not establish that these operations work there.

The SDK pins kernel headers and shared semantic crates when it is built. That source pin identifies the build input. It is not a requirement to run that exact kernel commit, and it does not establish compatibility with every kernel version.

Starting with C #

Begin with installing and linking, then compile a complete program. Read library conventions before managing buffers or file descriptors.

For a registry backend, start with registry sources. The installed headers own the complete function declarations and parameter contracts. The SDK reference explains how to use those contracts.

Installing and Linking

Peios / Developing for Peios / SDK Basics

Link your application to the library whose services it uses. Install the matching development package when compiling, and the runtime package on machines that run the resulting executable.

Before you start #

Prepare these build inputs:

  • A C or C++ compiler for the target system.
  • The development package for libpeios, librsi, or both.
  • The Peios kernel userspace API headers required by those packages.
  • pkg-config configured to find the target system's package metadata.

Choosing packages #

Each library has the same package split. Replace libpeios with librsi for registry source development:

PackageContentsNeeded for
dev.peios.libpeiosVersioned shared libraryRunning dynamically linked programs
dev.peios.libpeios-develHeaders, linker symlink, and peios.pcCompiling programs
dev.peios.libpeios-staticStatic archiveStatic linking
dev.peios.libpeios-debuginfoSeparate debugging informationDebugging library code
dev.peios.libpeios-debugsourceSource files for debuggingStepping through library code

Use headers and libraries from the same SDK package set. Do not combine headers from an arbitrary kernel checkout with an unrelated library build. The library headers include <pkm/*.h> definitions; the directory name is part of the installed include interface.

Linking an application #

Use the complete first.c program from compiling a first program:

  1. Include <peios.h> or the individual <peios/*.h> headers that the application uses.
  2. Obtain the compiler and linker options from the peios pkg-config module. Put the library options after the source files or object files.
  3. Build the program for the same target as the installed library.

For librsi, use <rsi.h> and the rsi pkg-config module. Applications that serve registry data and also access other Peios services can link both.

Checking the result #

A successful compile confirms that the headers are available. A successful link confirms that the required symbols are present in the selected library. Run the first-program example to check portable data handling.

Calls that access tokens, registry keys, or kernel events need a Peios kernel with the required services. Test those calls on the target system with the privileges and objects described by their guides.

Static linking #

The static package contains libpeios.a or librsi.a. Select that archive explicitly when constructing the linker command. Static linking includes the SDK code in the executable; the application's other dependencies still follow their own linking rules.

Rebuild statically linked applications when adopting an SDK fix. Updating the shared-library package alone does not replace code in those programs.

Debugging static builds #

The packaged static archives retain linker symbols but omit DWARF debugging information. Each library's debug package describes its shared object; it does not supply the missing SDK internals for a statically linked program.

To debug statically linked SDK code, use the unstripped archive the SDK's build gives, or rebuild the matching source with its recorded compiler and dependency inputs. Keep those inputs with the binary so that debugger source paths and layouts match the executable.

Compiling a First Program

Peios / Developing for Peios / SDK Basics

Parse a security descriptor, read its owner, and print the owner's security identifier (SID). This example runs entirely in userspace and does not open tokens or change system security.

Before you start #

Prepare these inputs:

  • A C compiler and pkg-config.
  • The libpeios development package and its matching runtime library.
  • A writable directory for the source and executable.

Creating the program #

Save this complete program as first.c:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <peios/security.h>

int main(void)
{
    /* An SDDL descriptor: owner and group are Administrators (BA), with a
       DACL granting them full access (FA). */
    const char *sddl = "O:BAG:BAD:(A;;FA;;;BA)";

    /* 1. Parse the SDDL text into self-relative SD wire bytes.
          First call probes for the size (cap == 0), then retrieve. */
    ssize_t need = peios_sddl_parse_sd(NULL, 0, sddl);
    if (need < 0) {
        fprintf(stderr, "parse probe failed: %s\n", strerror(errno));
        return 1;
    }

    unsigned char *sd = malloc((size_t)need);
    if (!sd)
        return 1;

    ssize_t sd_len = peios_sddl_parse_sd(sd, (size_t)need, sddl);
    if (sd_len < 0) {
        fprintf(stderr, "parse failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }
    printf("security descriptor: %zd bytes\n", sd_len);

    /* 2. Parse the SD into a zero-copy view. The view borrows `sd` — it
          must stay alive and unmodified until the final read. */
    peios_sd_view view;
    if (peios_sd_parse(sd, (size_t)sd_len, &view) != 0) {
        fprintf(stderr, "sd parse failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }

    /* 3. Pull out the owner SID. On success `owner` points INTO `sd`. */
    const void *owner;
    size_t owner_len;
    if (peios_sd_view_owner(&view, &owner, &owner_len) != 0) {
        fprintf(stderr, "owner lookup failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }

    /* 4. Format the owner SID as its "S-1-…" string. The byte form of a
          SID is bounded, but its string form is variable, so we probe.
          A string length excludes the NUL, so allocate len + 1. */
    ssize_t slen = peios_sid_format(owner, owner_len, NULL, 0);
    if (slen < 0) {
        fprintf(stderr, "sid format probe failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }

    char *str = malloc((size_t)slen + 1);
    if (!str) {
        free(sd);
        return 1;
    }
    if (peios_sid_format(owner, owner_len, str, (size_t)slen + 1) < 0) {
        fprintf(stderr, "sid format failed: %s\n", strerror(errno));
        free(str);
        free(sd);
        return 1;
    }

    printf("owner: %s\n", str);

    /* 5. Free `sd` — every pointer the view returned pointed into
          it, so it had to outlive the last read. */
    free(str);
    free(sd);
    return 0;
}

The Security Descriptor Definition Language (SDDL) string sets the owner and group to Administrators. Its discretionary access control list (DACL) grants that group full file access. Parsing this string does not grant any access to the process running the example.

Building and running #

  1. Compile the source with the package's compiler and linker options:

    cc first.c $(pkg-config --cflags --libs peios) -o first
    
  2. Run the executable:

    ./first
    

Checking the result #

The program prints:

security descriptor: 84 bytes
owner: S-1-5-32-544

The owner SID identifies Administrators. The byte count describes the encoded descriptor produced by this example, including its owner, group, and access control list.

Understanding ownership #

The program probes the output size before allocating each variable-sized buffer. The string allocation adds one byte for the terminating NUL.

The parsed view and owner pointer borrow the descriptor allocation. The program frees that allocation after formatting the owner, so every borrowed pointer remains valid throughout its use.

Read library conventions for the result and ownership rules used by the other SDK functions.

Using the SDK from Rust

Peios / Developing for Peios / SDK Basics

Use the peios crate to access Peios through Rust handles and Result values. The peios-sys crate exposes the underlying unsafe C functions. Both use the public C application binary interface (ABI).

Before you start #

  • Install Rust and Cargo.
  • Install matching libpeios headers and libraries, version 0.5.12 or later.
  • Install pkg-config and libclang for binding generation.
  • Place the peios-rs checkout beside your application for this example.
  • Run token operations on a Peios kernel.

Add the dependency #

  1. Add a local dependency to your application's Cargo.toml:

    [dependencies]
    peios = { path = "../peios-rs/peios" }
    
  2. Create src/main.rs:

    use peios::token::{Token, TokenAccess};
    
    fn main() -> peios::Result<()> {
        let token = Token::open_self(false, TokenAccess::QUERY)?;
        let identity = token.user()?;
        println!("identity: {identity}");
        Ok(())
    }
    
  3. Run cargo run. The token handle closes when it leaves scope.

Check the result #

The program prints the caller's security identifier (SID). A native-call error on another kernel does not indicate a successful Peios access check.

Generate the API reference with cargo doc -p peios --open from the SDK checkout. The repository's docs/building.md covers SDK discovery and host tests.

Linking and types #

Use dynamic linking for ordinary Rust applications. The C static archive contains its own Rust runtime, which can conflict with a Rust executable's runtime. The static feature only selects that archive; it does not remove those conflicts.

The optional uapi feature re-exports kernel types through peios_sys. Those types come from the recorded kernel snapshot. Import them through that re-export when sharing values with these bindings: a separately compiled copy of the same structure has a different Rust type identity.

Names without regard to case #

peios::casefold compares names as the registry compares them: Unicode Simple Case Folding, pinned to Unicode 16.0, with no normalisation. Windows matches names the same way, so use it wherever a program must match names as Windows clients expect, as a file server does. fold folds one character; eq and cmp compare whole names. Code that must build without libpeios, such as a protocol engine tested on another system, can depend on the peios-casefold crate itself, which peios::casefold re-exports.

Identity and event ownership #

A scoped impersonation guard belongs to the thread that creates it. Rust rejects moving or sharing the guard across threads. Keep identity-dependent work on that thread, and call revert when you need to check restoration. Dropping the guard attempts restoration but cannot return an error. Impersonations do not nest: restoration clears the impersonation rather than restoring an earlier impersonated identity.

Events own their type names and payloads. You can retain them after the next read or after closing the reader. A low-level read returns EAGAIN if its slot is empty, overwritten, or changes generation during copying. After a generation change, attach and map the ring again.

Event emission checks names, payload lengths, and batch counts before converting them to the C ABI's fixed-width fields. Values that do not fit return EINVAL. Socket receive calls also reject an unrepresentable handle capacity before allocating its buffer or consuming a message.

Access checks and request identity #

Audit Contexts in Rust explains object descriptions and denial results. Token Messages in Rust covers received-handle ownership, truncation, and explicit peer-identity fallback.

Using the SDK from Go

Peios / Developing for Peios / SDK Basics

Use peios-go to read Peios security formats and call native Peios operations. The module uses Go directly; applications do not need a C compiler or an installed C SDK library at runtime.

Before you start #

  • Install Go 1.26 or later.
  • Place the SDK checkout beside your application for this local example.
  • Run native operations on a Peios kernel. Portable format parsers also work on other systems.

Add the dependency #

  1. Add these entries to your application's go.mod:

    require github.com/peios/peios-go v0.0.0
    replace github.com/peios/peios-go => ../peios-go
    

    The version is a local placeholder. Before publishing your application, use a published commit or release and remove the local replacement.

  2. Create main.go:

    package main
    
    import (
        "fmt"
    
        "github.com/peios/peios-go/security"
    )
    
    func main() {
        descriptor, err := security.ParseSDDL("O:SYG:BAD:(A;;FA;;;BA)")
        if err != nil {
            panic(err)
        }
        wire, err := descriptor.MarshalBinary()
        if err != nil {
            panic(err)
        }
        fmt.Printf("descriptor size: %d bytes\n", len(wire))
    }
    
  3. Run go run . from your application directory.

Check the result #

The program prints the descriptor size. This example parses Security Descriptor Definition Language (SDDL) without changing a system object. Parsing validates structure; the kernel separately checks your authority when you apply a descriptor.

Use go doc github.com/peios/peios-go/security for the package reference. The repository's docs/building.md describes SDK development and tests.

Audited access checks #

Audit Contexts in Go uses the maintained access package and explains how to handle denial separately from an unsuccessful check.

Audit Contexts in Rust

Peios / Developing for Peios / SDK Basics

An audit context names the object behind an access check. The Rust AuditContext type owns the encoded description and lends it to an AccessCheck. The kernel can then include that description in an audit record when the applicable audit policy calls for one.

The description is the daemon's claim, not independently observed identity. It does not grant access or replace the security descriptor. See The Audit Context for the shared format and Access Decisions for the rules governing audited objects.

Build and use a context #

This helper checks a service object using a supplied caller token, descriptor, access mask, and object-specific generic mapping:

use std::os::fd::BorrowedFd;

use peios::access::{AccessCheck, AccessDecision, AuditContext};
use peios::security::{AccessMask, GenericMapping, SecurityDescriptor};

fn check_service(
    caller: BorrowedFd<'_>,
    descriptor: &SecurityDescriptor,
    desired: AccessMask,
    mapping: GenericMapping,
) -> peios::Result<AccessDecision> {
    let context = AuditContext::new("service", &[("name", "jellyfin".into())])?;
    AccessCheck::new(descriptor, desired, mapping)
        .token(caller)
        .audit_context(&context)
        .check()
}

The example names an illustrative service. Replace its name with the actual object being checked, and define asserted object fields in the owning event catalog fragment. Do not label an arbitrary request as another component's object merely because its name is convenient.

A completed check returns an AccessDecision. Inspect allowed: denial is an ordinary decision, not a Rust Err. An error means the check itself could not complete. The check evaluates access; your daemon still enforces the result before performing the operation.

Values and ownership #

Field values convert from &str, u64, u32, i64, i32, bool, &[u8], and &SidRef. A security identifier (SID) uses its binary representation. Use the declared field type rather than converting every value to a string. Leave absent fields out instead of supplying nil or a placeholder value.

The constructor copies the encoding into owned storage. Temporary field slices need not outlive the returned context. AccessCheck borrows that context for the check; as_bytes lends the encoded bytes without transferring ownership.

Invalid kind or key names, repeated keys, and oversized encodings are rejected with EINVAL. Names are single kebab-case segments, and the encoded context is limited to 4096 bytes. Other construction failures remain errors to handle.

Accept an existing encoding #

AuditContext::from_bytes takes a Vec<u8>, validates the encoded context, and adopts it on success. It applies the shared validator's structural rules, which are broader than the scalar-only constructor. Passing validation does not prove that fields are cataloged, truthful, or appropriate for this object.

Keep the caller token and descriptor associated with the same request while constructing and checking the context. Neither a successfully encoded context nor a successful audit write is an authorization decision by itself.

Audit Contexts in Go

Peios / Developing for Peios / SDK Basics

The github.com/peios/peios-go/access package provides portable audit-context encoding and native access checks. Attach the encoded object description to access.Request so the kernel can identify the object in an audit record. The context does not grant authority or replace the security descriptor.

The Audit Context defines the common encoding. Access Decisions explains when a daemon supplies it and how its claims are marked.

Encode and check #

This helper checks an illustrative service using an existing token handle and security descriptor. Native checks require a Peios kernel on Linux/amd64.

package example

import (
	"syscall"

	"github.com/peios/peios-go/access"
	"github.com/peios/peios-go/security"
)

func CheckService(
	caller syscall.Conn,
	descriptor []byte,
	desired security.AccessMask,
	mapping security.GenericMapping,
) (access.Result, error) {
	context, err := access.AuditContext("service", []access.Field{
		{Name: "name", Value: "jellyfin"},
	})
	if err != nil {
		return access.Result{}, err
	}
	return access.Check(access.Request{
		Token:        caller,
		Descriptor:   descriptor,
		Desired:      desired,
		Mapping:      mapping,
		AuditContext: context,
	})
}

Use the actual service name and its object-specific mapping. Define the asserted fields in the owning event catalog fragment. A nil Token selects the calling thread's effective token; it does not mean an anonymous client. Pass the intended caller explicitly when checking another principal's access.

access.Check returns syscall.EACCES for denial, retaining the granted subset and audit outputs in its result. Other errors mean the check could not complete. This differs from the Rust wrapper, which represents denial in AccessDecision.allowed. Do not ignore a Go error because a result was returned.

CheckList returns per-node decisions for an object tree. Inspect each node's Status; a successful call does not mean every node grants the requested access.

Encode values deliberately #

Each access.Field pairs a name with a value. The encoder accepts strings, booleans, byte slices, and signed or unsigned integer types. Pass a SID's Bytes() result for a binary security identifier, not the SID object or its text form. Floating-point values, nested objects, and nil are not constructor field values.

Names are single kebab-case segments, repeated keys are rejected, and the encoded context is limited to 4096 bytes. An empty field list emits only the object kind. The encoder returns access.ErrAuditContext for invalid context structure and can also return an encoding error.

The returned byte slice owns its encoding. Keep its contents unchanged until the check completes. Do not reuse it concurrently as a mutable work buffer.

Validate an existing map #

Call access.ValidateAuditContext when another encoder built the bytes. Its structural validation is broader than the scalar-field constructor; it is not proof that the values match the catalog or describe the real object.

Both native check variants validate a non-nil Request.AuditContext before calling the kernel. Nil omits the context; a non-nil empty slice is invalid. For a daemon-owned object that requires an audit context, omission is not a substitute for handling an encoding error.

The historical libp-go/sd constructors and CheckRequest examples do not apply to this API. Use access.AuditContext, access.Field, and access.Request from the maintained module.

Token Messages in Rust

Peios / Developing for Peios / SDK Basics

The Rust socket helpers send and receive per-message identity with file descriptors. ReceivedMessage owns each received descriptor, including its optional token, so rejecting a message can release those resources by dropping it. The request bytes remain in the caller's receive buffer.

Use Per-Message Identity for the shared interface contract. A conveyed token identifies the authority the sender could convey; it does not authorize every requested operation.

Send one identity with a request #

For a connected socket and an existing user token, the sending call is:

use std::os::fd::AsFd;
use peios::socket;

let sent = socket::send_message(
    jobs.as_fd(), request, Some(user_token.as_fd()), &[], 0,
)?;

The caller retains its descriptors. Check the returned byte count according to the transport's framing rules. On a stream, a partial write is not a complete request. Do not blindly replay the whole request and its ancillary data after a partial write.

Receive and reject incomplete requests #

This helper requires an attached identity and rejects truncation. The application chooses an 8-descriptor bound; choose a bound appropriate to your own protocol and validate the number and purpose of descriptors after receipt.

use std::error::Error;
use std::os::fd::{BorrowedFd, OwnedFd};

use peios::socket;
use peios::token::{ImpersonationLevel, Token};

fn receive_identity(
    connection: BorrowedFd<'_>,
    buffer: &mut [u8],
) -> Result<(usize, Token, Vec<OwnedFd>), Box<dyn Error>> {
    let message = socket::recv_message(connection, buffer, 8, 0)?;
    if message.truncated || message.control_truncated {
        return Err("incomplete request or ancillary data".into());
    }
    if message.len == 0 {
        return Err("empty request or closed stream".into());
    }
    let identity = match message.token {
        Some(token) => token,
        None => return Err("this protocol requires an attached identity".into()),
    };
    if identity.impersonation_level()? < ImpersonationLevel::Impersonation {
        return Err("identity cannot be used to act for this caller".into());
    }
    Ok((message.len, identity, message.fds))
}

This is an identity/ownership helper, not a stream message decoder. A stream read can contain only part of the application's frame. Reassemble and validate the frame before interpreting its contents. Do not use zero-length data as an identity-only request with this helper.

Returning an error drops descriptors already received. Moving the token or OwnedFd values out transfers their ownership to the caller; those handles close when their new owners drop them. Do not close their raw descriptor numbers separately. Received handles are close-on-exec.

The example requires at least the local impersonation level because its server intends to act for the caller. An identification-only protocol needs its own explicit contract. Checking the level does not enter impersonation or perform an access check.

Choose fallback identity explicitly #

A protocol can instead specify that an absent attached token means the connected peer's primary token. In that case, obtain the peer process handle from the kernel and open the token through it:

use std::os::fd::AsFd;
use peios::socket;
use peios::token::{Token, TokenAccess};

let peer = socket::peer_pidfd(connection.as_fd())?;
let identity = Token::open_process(
    peer.as_fd(), TokenAccess::QUERY | TokenAccess::DUPLICATE,
)?;

This is the connected peer's primary identity, not necessarily the identity of a client that peer represents. Do not substitute a process number named in the payload. Do not use fallback after truncation, an invalid attached token, or a failed token query; those are failures rather than absence.

Apply the protocol's level and authorization checks to a fallback token too. Opening a primary token does not convert it into an impersonation token or enter impersonation. If acting under it is required, use the token duplication and scoped impersonation interfaces described by the SDK.

A scoped impersonation guard stays on its creating thread. It does not carry identity safely across arbitrary async task migration. Explicitly revert when you need to handle restoration failure; dropping the guard cannot report it.

Peios Learn — documentation for Peios software.

Built with Trail.