# System Service Libraries

---

# System Service Libraries

_Peios / Developing for Peios / System Service Libraries_

> Which C library, and matching Rust crate, to use for resolvd, timed, or trustd, or for reading registry documents, registry manuals, and event catalogs.

Peios system services publish C libraries so that your application can ask
them for their state, or ask them to act, without starting a command and
reading its output. Each library has a Rust crate that wraps the same shared
library. For access control, the registry, and events, use the
[Peios SDK](/peios/developing-for-peios/sdk-basics/what-is-the-peios-sdk.md) instead. For sign-in and
account operations, use the
[authentication client](/peios/developing-for-peios/authentication-client/conversations.md).

## Choosing a library

Choose the library for the service or format you need:

| Library | Use it to | Rust crate | Guide |
|---|---|---|---|
| `libresolvd` | Look up names and addresses, read resolver status, and flush the cache | `resolvd-client` | [Using libresolvd](/peios/developing-for-peios/service-libraries/using-libresolvd.md) |
| `libtimed` | Read clock status and sources, follow clock changes, and request time changes | `timed-client` | [Using libtimed](/peios/developing-for-peios/service-libraries/using-libtimed.md) |
| `libtrust` | Read and follow the trusted root certificates, and add or distrust certificates | `trust-client` | [Using libtrust](/peios/developing-for-peios/service-libraries/using-libtrust.md) |
| `libreg`, `libregman`, `libevman` | Parse registry documents, registry manuals, and event catalogs | `peios-reg`, `peios-regman`, `peios-evman` | [Utility Libraries](/peios/developing-for-peios/service-libraries/utility-libraries.md) |

`libresolvd`, `libtimed`, and `libtrust` talk to a running service. The
utility libraries work on documents and need no service.

## What the service decides

The service, not the library, decides what each call can do. It checks the
caller's permissions for the operation, so a call can be refused even when the
library loads and connects. A management call, such as adding a trusted
certificate or flushing the resolver cache, uses your own rights; the library
never raises them.

Each library's major version is part of its shared-library name, such as
`libresolvd.so.1`. A new major version means an incompatible C interface, so
link against the major version your code was written for.

---

# Utility Libraries

_Peios / Developing for Peios / System Service Libraries_

> Shared libraries for registry documents, registry manuals, and event catalogs.

The Peios utility libraries let your application work with the same document
formats as the command-line tools. You can import a registry document, show
configuration help, or look up an event description without starting another
process or interpreting terminal output.

## Choosing a library

| Library | Purpose | Reference |
|---|---|---|
| `libreg` | Parse, export, and apply registry batch documents | `libreg(3)` |
| `libregman` | Parse and search registry manuals | `libregman(3)` |
| `libevman` | Parse, check, and search event catalogs | `libevman(3)` |

Each library has a C interface and a safe Rust wrapper. The runtime package
provides a shared library; its matching development package provides headers
and linking information. The libraries share Peiosutils release versions,
while their ABI major identifies the compatible C interface.

Parsing a registry document doesn't change the registry. Applying it is a
separate operation that uses the caller's access token. A document that parses
successfully can still fail validation or access checks when applied.

Manual and event parsers can return usable records alongside diagnostics.
Check both: a successful library operation doesn't mean every source record
is valid. This lets an editor display the valid content and explain problems
in the same view.

## Ownership across language boundaries

A C operation returns a handle that owns its result or its error. Check the
error accessor, then read the result. Free the handle on either path. Views
returned by the library borrow that handle, so copy anything you need to
retain before freeing it.

The Rust wrappers manage these handles automatically. Registry-manual records
and event-query matches are owned Rust values. A registry document keeps its
library handle alive while you borrow its JSON representation.

The C interfaces accept pointer-and-length spans rather than terminated
strings. This preserves the difference between an absent optional value and
an explicitly empty one. Text is UTF-8; filesystem paths in the manual and
event libraries retain their original Unix bytes.

## Moving from the earlier Rust crates

Use `peios-reg`, `peios-regman`, and `peios-evman` for application code. They
call the corresponding shared library. The earlier Rust-only crates exposed
implementation types directly; changing only a dependency name doesn't adapt
those types to the new ownership model.

The implementation crates `registry-docs`, `registry-manual`, and
`event-catalogue` are internal to Peiosutils. Keep application integrations on
the public wrappers or C interfaces so an implementation change doesn't
require a matching change in every consumer.

---

# Using libresolvd

_Peios / Developing for Peios / System Service Libraries_

> Operations, ownership, errors, and Rust access for libresolvd ABI 1.

`libresolvd.so.1` provides the public C interface for resolvd. The
`resolvd-client` crate wraps the same shared library and returns owned Rust
values. Internal implementation crates do not replace this public boundary.

## Operations

The library reads resolver status, looks up addresses, resolves DNS record
types, performs reverse lookups, and flushes the cache. Replies retain their
source, interface, and server information. A successful library exchange can
still contain a DNS failure outcome; check the typed answer before using its
records. Flushing requires the caller's existing control permission.

The shared library is `libresolvd.so.1`. It is separate from the platform's
`libresolv` library and from `libnss_peios_net.so.2`, which provides the glibc
name-service interface. Applications do not link the NSS module directly.

## Linking and ownership

Include `<peios/resolvd.h>` and use the `resolvd` pkg-config module. The
installed header and `libresolvd(3)` describe individual functions and data
layouts. `peios_resolvd_abi_version()` returns the ABI major version, 1.

Each operation returns an owned result, including failures. Check
`peios_resolvd_result_error()` before reading a view, and release the result
exactly once with `peios_resolvd_result_free()`. Error codes are POSIX
numbers;
human-readable diagnostic wording is not a stable identifier. Reading the
stored error does not set thread-local `errno`.

Strings are UTF-8 spans with explicit byte lengths, without terminating NUL
bytes. Input spans are borrowed for the call and must remain live, aligned,
and initialized. A null pointer with zero length represents absent optional
text; a non-null pointer with zero length represents present empty text.
Returned strings, arrays, and nested views belong to the result. Copy what
you need before freeing it. Handles from another library are not valid here.

## Connections and failure

Each ordinary daemon operation opens its own filesystem Unix socket. The
system default is `/run/resolvd/resolv.sock`; clients can select another
socket for a
private service instance or a test.

A positive timeout in milliseconds bounds connection, sending, and receiving
together. A full connection queue can fail immediately. A transport error
does not establish whether a requested change was applied. The library does
not automatically replay operations after an uncertain failure.

## Rust access

Use `Client::system(Duration)` for the installed daemon or
`Client::new(path, Duration)` for an explicit socket. The wrapper copies
result views into Rust values and releases C results through `Drop`.
Select a matching source revision of `resolvd-client` and link the installed
shared library; the crate is not a precompiled Rust ABI package.

---

# Using libtimed

_Peios / Developing for Peios / System Service Libraries_

> Operations, ownership, errors, and Rust access for libtimed ABI 1.

`libtimed.so.1` provides the public C interface for timed. The
`timed-client` crate wraps the same shared library and returns owned Rust
values. Internal implementation crates do not replace this public boundary.

## Operations

The library reads status and sources, subscribes to clock snapshots, requests
configuration reloads, and requests manual time changes. The daemon checks
permissions and whether its operating mode allows a manual change.

Configuration helpers parse a server entry, check zone-name syntax, verify an
installed zone, and read zone and country lists. Zone-name syntax alone does
not establish that the zone is installed. Zone files and metadata must be
regular files of at most 16 MiB; aliases to regular files are supported.
Missing or unreadable metadata produces an empty list. These helpers do not
change the registry or the system clock.

## Linking and ownership

Include `<peios/timed.h>` and use the `timed` pkg-config module. The
installed header and `libtimed(3)` describe individual functions and data
layouts. `peios_timed_abi_version()` returns the ABI major version, 1.

Each operation returns an owned result, including failures. Check
`peios_timed_result_error()` before reading a view, and release the result
exactly once with `peios_timed_result_free()`. Error codes are POSIX numbers;
human-readable diagnostic wording is not a stable identifier. Reading the
stored error does not set thread-local `errno`.

Strings are UTF-8 spans with explicit byte lengths, without terminating NUL
bytes. Input spans are borrowed for the call and must remain live, aligned,
and initialized. A null pointer with zero length represents absent optional
text; a non-null pointer with zero length represents present empty text.
Returned strings, arrays, and nested views belong to the result. Copy what
you need before freeing it. Handles from another library are not valid here.

## Connections and failure

Each ordinary daemon operation opens its own filesystem Unix socket. The
system default is `/run/timed/time.sock`; clients can select another socket
for a
private service instance or a test.

A positive timeout in milliseconds bounds connection, sending, and receiving
together. A full connection queue can fail immediately. A transport error
does not establish whether a requested change was applied. The library does
not automatically replay operations after an uncertain failure.

## Rust access

Use `Client::system(Duration)` for the installed daemon or
`Client::new(path, Duration)` for an explicit socket. The wrapper copies
result views into Rust values and releases C results through `Drop`.
Select a matching source revision of `timed-client` and link the installed
shared library; the crate is not a precompiled Rust ABI package.

## Subscriptions

A subscription is owned separately from each returned snapshot. Calls and
freeing on one subscription must not overlap. A receive timeout retains
partial framing so a later call can continue. Other transport or protocol
errors close the stream; create a new subscription explicitly if needed.
The Rust wrapper requires mutable access to receive the next snapshot.

---

# Using libtrust

_Peios / Developing for Peios / System Service Libraries_

> Operations, ownership, errors, and Rust access for libtrust ABI 1.

`libtrust.so.1` provides the public C interface for trustd. The
`trust-client` crate wraps the same shared library and returns owned Rust
values. Internal implementation crates do not replace this public boundary.

## Operations

The library reads status and complete root snapshots, subscribes to changes,
and requests recomposition. Snapshot chunks must belong to one generation;
the library rejects incomplete or mixed-generation results.

Certificate helpers decode, inspect, and vet candidate roots. Decoding or
inspecting a certificate does not make it trusted. Other helpers need no
daemon: they compute a certificate's SHA-256 fingerprint, convert between
DER and PEM, normalize a fingerprint as typed, and resolve a whole
fingerprint or an unambiguous prefix of at least eight digits against a
list of fingerprints. `peios_trust_default_control_security()` returns the
descriptor trustd checks against when the `ControlSecurity` value is
absent. Management operations add
or remove registry entries, record or remove distrust, and configure
compatibility output using the caller's own rights. An access probe is not
an authority token: the actual operation can still fail.

Registry writes and daemon recomposition are separate operations. Request a
reload after management changes when immediate recomposition is required,
and handle either operation's error. A failed reload does not roll back a
completed registry write.

## Linking and ownership

Include `<peios/trust.h>` and use the `trust` pkg-config module. The
installed header and `libtrust(3)` describe individual functions and data
layouts. `peios_trust_abi_version()` returns the ABI major version, 1.

Each operation returns an owned result, including failures. Check
`peios_trust_result_error()` before reading a view, and release the result
exactly once with `peios_trust_result_free()`. Error codes are POSIX numbers;
human-readable diagnostic wording is not a stable identifier. Reading the
stored error does not set thread-local `errno`.

`peios_trust_result_failure()` gives the kind of failure, which is also
stable:

| Constant | Failure |
|---|---|
| `PEIOS_TRUST_FAILURE_NONE` | The operation succeeded |
| `PEIOS_TRUST_FAILURE_OTHER` | Any other failure, such as an unreachable daemon or an ambiguous prefix |
| `PEIOS_TRUST_FAILURE_DENIED` | The caller's rights refused the change |
| `PEIOS_TRUST_FAILURE_NOT_FOUND` | No such root, addition, distrust entry, or matching fingerprint |
| `PEIOS_TRUST_FAILURE_MALFORMED` | The bytes are not a certificate |
| `PEIOS_TRUST_FAILURE_NOT_A_CA` | The certificate is not a certificate authority's |
| `PEIOS_TRUST_FAILURE_EXPIRED` | The certificate has expired |
| `PEIOS_TRUST_FAILURE_NO_CERTIFICATE` | PEM text holds no certificate block |

Strings are UTF-8 spans with explicit byte lengths, without terminating NUL
bytes. Input spans are borrowed for the call and must remain live, aligned,
and initialized. A null pointer with zero length represents absent optional
text; a non-null pointer with zero length represents present empty text.
Returned strings, arrays, and nested views belong to the result. Copy what
you need before freeing it. Handles from another library are not valid here.

## Connections and failure

Each ordinary daemon operation opens its own filesystem Unix socket. The
system default is `/run/trustd/trust.sock`; clients can select another socket
for a
private service instance or a test.

A positive timeout in milliseconds bounds connection, sending, and receiving
together. A full connection queue can fail immediately. A transport error
does not establish whether a requested change was applied. The library does
not automatically replay operations after an uncertain failure.

## Rust access

Use `Client::system(Duration)` for the installed daemon or
`Client::new(path, Duration)` for an explicit socket. The wrapper copies
result views into Rust values and releases C results through `Drop`. Its
`Error` carries the POSIX `code`, the failure's `kind` as an `ErrorKind`,
and the diagnostic `message`. The crate also exports the registry key and
value names trustd reads, and the certificate `Details` and `Parsed` types.
Select a matching source revision of `trust-client` and link the installed
shared library; the crate is not a precompiled Rust ABI package.

## Subscriptions

A subscription is owned separately from each returned snapshot. Calls and
freeing on one subscription must not overlap. A receive timeout retains
partial framing so a later call can continue. Other transport or protocol
errors close the stream; create a new subscription explicitly if needed.
The Rust wrapper requires mutable access to receive the next snapshot.

---

# Reading Registry Documents

_Peios / Developing for Peios / System Service Libraries_

> Parse a registry batch document in a C application without changing the registry.

Use `libreg` to read a registry batch document without applying it. This is
useful for an importer that shows a document before asking the user to apply
its changes.

## Before you start

- Install matching `libreg` and `libreg-devel` packages.
- Install a C compiler and `pkg-config`.
- Supply a UTF-8 JSON document in the registry batch format.

## Parse the document

1. Include `peios/reg.h` and create a span containing the JSON bytes. This
   example uses an empty batch, so it needs no live registry access:

   ```c
   #include <peios/reg.h>
   #include <stdio.h>

   int main(void) {
       const char json[] = "{\"keys\":[]}";
       peios_reg_bytes input = {
           .data = (const uint8_t *)json,
           .len = sizeof(json) - 1,
       };
       peios_reg_document *document = peios_reg_document_parse(input);
       int error = peios_reg_document_error(document);
       if (error == 0) {
           peios_reg_bytes output = peios_reg_document_json(document);
           fwrite(output.data, 1, output.len, stdout);
           putchar('\n');
       }
       peios_reg_document_free(document);
       return error == 0 ? 0 : 1;
   }
   ```

2. Save the example as `read-document.c`, then compile it against the
   installed library:

   ```sh
   cc read-document.c -o read-document $(pkg-config --cflags --libs reg)
   ```

## Check the result

Run `./read-document`. It prints the empty batch and exits successfully:

```json
{"keys":[]}
```

The handle owns the returned JSON bytes. The example writes them before
freeing the handle. For an application that retains the document in another
format, copy those bytes while the handle is still alive.

See `libreg(3)` for export, apply, errors, and lifetime requirements. Parsing
alone doesn't check whether you have permission to apply a document.
