Skip to content

armgit / janas

Public Imported from GitHub
0

37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.

Release 2026-10-03: janas-system - this computer for the model; a layout that comes back untranslated asked once more

camauri8dc7bf6a745c
diff --git a/ChangeLog.md b/ChangeLog.md
index d751ef6..3622a9e 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,6 +2,13 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-02] - janas-system: this computer
+
+- **janas-system**, an MCP service that only reads and reaches no network: how the computer is (the processor and the kernel's share of it, the memory and the swap, on Linux the pressure, every disk, the battery and its wear, the temperatures a device), what fills a directory (8 seconds and 64 levels at most, never across filesystems or links; "at least" when the time runs out), the programs using the most processor or memory or those of a name, the errors of the logs (the same message but for its numbers counted once, the latest read first) and the services that failed, the updates by the package manager's last list (apt, dnf, pacman; nothing fetched), the network interfaces, the Wi-Fi signal, the gateway. Run over the protocol on the development laptop; `tests/test_system_parse.c` checks the reading of Linux's texts and the layouts.
+- **A Windows part** for it, on the Win32 API (memory, processor, drives, power, processes, event log, services, IP Helper, WLAN): compiled and linked with MinGW-w64 and run under Wine; not yet on Windows, and Janas itself is not built for Windows yet.
+- **A layout that comes back untranslated is asked once more** in `janas-chat`, the model told so: Qwen3.6-35B-A3B gave janas-system's status back as it was the first time; run again, it came in Italian.
+- **The services run a program the same way**: `janas-git`'s runner (no shell, no terminal, a time limit) moves to `src/services/common/run.c`.
+
## [2026-10-02] - The services under one directory
- **The MCP services in `src/services/`**: each in `src/services/<service>/` (flights, git, github, maps, prices, weather, wiki), what they share in `src/services/common/` (the geography's tables, the GET over HTTPS, where the user is, the layouts of the answers). The programs keep their names.
diff --git a/README.md b/README.md
index e413bf3..ca1577b 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,7 @@ Everything the engine does is chosen from what it measures, so another machine w
- **`janas-prices`:** prices and finance, for information: currencies at the ECB's rates, crypto-assets, shares (with a free key of yours), inflation, central banks' rates, electricity where it is open data, the cheapest fuel near a place in Italy, France, Spain and Austria ([docs/services/prices.md](docs/services/prices.md)).
- **`janas-github`:** a project on GitHub: its issues and pull requests (the new ones since you last asked), its latest releases, its recent commits, what it is; it only reads, with the gh command's token when you have one ([docs/services/github.md](docs/services/github.md)).
- **`janas-git`:** the git repositories of your computer: what has changed, the commits, the branches, a diff; and a commit, pull, push or switch of branch, each shown whole and asked of you first; nothing that throws work away ([docs/services/git.md](docs/services/git.md)).
+- **`janas-system`:** this computer: how it is (memory, processor, disks, battery, temperatures), what fills a directory, the programs running, the errors of its logs, the updates, the network; it only reads, and none of its tools reaches the network ([docs/services/system.md](docs/services/system.md)).
- **`janas-wiki`:** Wikipedia when you ask for it: its search, a page shown to you as it is (the introduction, then the section asked for) while the model reads only a note of it, and the pages about what lies around a place ([docs/services/wiki.md](docs/services/wiki.md)).
- **`janas-server`:** the model behind an HTTP API that follows OpenAI's, so that clients written for it can use a model running on this machine: chat and completions with tools, JSON output held to a schema and log-probabilities, the Responses API with its conversations, embeddings and moderations, a chat page of its own to try it from a browser ([below](#using-it-over-http)), and code completion for VSCodium and VS Code ([docs/code-completion.md](docs/code-completion.md)).
- **`janas-bench`:** measures the machine, fills its profile and writes a report.
@@ -298,7 +299,7 @@ printf 'Explain mixture of experts in one paragraph.\n/quit\n' \
### Janas's services
-The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-git`, `janas-github`, `janas-maps`, `janas-prices`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?", "how do I get to Palermo by train?", "are there new issues on Janas?", "what has changed in this repository?", "where is diesel cheapest near here?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).
+The chat starts by itself the services of Janas it finds beside it - `janas-flights`, `janas-git`, `janas-github`, `janas-maps`, `janas-prices`, `janas-system`, `janas-weather` and `janas-wiki` - and the model uses their tools when a question needs them, without being told: ask "which flights are over the Tyrrhenian Sea now?", "what's the weather like?", "how do I get to Palermo by train?", "are there new issues on Janas?", "what has changed in this repository?", "where is diesel cheapest near here?", "what is filling my disk?" or "show me Wikipedia's page on Zeffirelli" (with no place, where you are: `JANAS_LOCATION`, or a guess from the internet connection). `--no-services` starts none. How they work, their keys, and how to use them in Claude Code and other clients: [docs/services](docs/services/README.md).
**The services' tools are given when they are needed.** Written into the system message, the tools of three services made it four thousand tokens, over a minute of a large model before the first message, and every service more made it longer. The system message now holds a catalog, a line a service, and the model opens a service when a question needs it: that service's instructions and tools come back as the answer of the call, its tools can be called from then on, and the next reply is held to be a call (a small model told to call one made the answer up instead). With Qwen3.6-35B-A3B the system message went from 4,057 tokens to 616, and opening the weather costs about a thousand tokens, once in a conversation, when the first question about the weather comes. `--all-tools` writes them all into the system message as before.
diff --git a/docs/services/README.md b/docs/services/README.md
index 04a8398..c6fcfc1 100644
--- a/docs/services/README.md
+++ b/docs/services/README.md
@@ -1,6 +1,6 @@
# Janas's services
-A service of Janas is a program that brings data of the world - flights, the weather, roads and places, an encyclopedia, prices and finance, GitHub's projects, the git repositories of your computer - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.
+A service of Janas is a program that brings data of the world - flights, the weather, roads and places, an encyclopedia, prices and finance, GitHub's projects, the git repositories of your computer, the computer itself - to a model, as tools of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP). Each one is an MCP server of its own, over its standard input and output, so that any MCP client can use it: `janas-chat`, and the assistants of others.
| Service | What it answers | Key |
|---|---|---|
@@ -9,6 +9,7 @@ A service of Janas is a program that brings data of the world - flights, the wea
| [`janas-github`](github.md) | a project's issues and pull requests (the new ones), its latest releases, its recent commits, what it is | none; the gh command's token when you have one |
| [`janas-maps`](maps.md) | a route by car, bike or on foot, step by step; journeys by public transport; what is near a place; where an address is | none |
| [`janas-prices`](prices.md) | for information: currencies, crypto-assets, shares, inflation, central banks' rates, electricity, the cheapest fuel near a place | none; a free one of your own for shares |
+| [`janas-system`](system.md) | this computer: how it is (memory, processor, disks, battery, temperatures), what fills a directory, the programs running, the errors, the updates, the network | none; nothing reaches the network |
| [`janas-weather`](weather.md) | the weather now (a model's and a station's), the forecast, the sea and its waves, the warnings in force | none |
| [`janas-wiki`](wiki.md) | Wikipedia's search, its pages as text, the pages about what lies around a place | none |
diff --git a/docs/services/system.md b/docs/services/system.md
new file mode 100644
index 0000000..66b2a57
--- /dev/null
+++ b/docs/services/system.md
@@ -0,0 +1,64 @@
+# janas-system
+
+This computer for `janas-chat` or any other MCP client (see [the services](README.md)): how it is, its disks and what fills a directory, the programs running, its errors, its updates, its network. It only reads, and none of its tools reaches the network: what it reads leaves the computer only in its answers.
+
+## The tools
+
+- **`system_status`** - the name of the computer and its system, how long it has been on; the processor (its share in use over half a second, and how much of it the kernel's; the load where the system tells it); the memory and the swap; on Linux the time the programs waited for the processor, the memory and the disks (pressure), when it is high; every disk's space, those 90% full told; the battery (its charge, its state, the time left or to full, its capacity against what it was new); the temperatures, one a device (the processor and its hottest core, a disk, the memory, the Wi-Fi card, the motherboard), those within 10 °C of their critical limit told.
+- **`system_disks`** - the disks: each filesystem once, its device, its type, its space. With a path (`path`, `~` for the home), what fills that directory, biggest first: each entry's size, the directories' summed over what they hold, with their files counted.
+- **`system_processes`** - the programs that use the most processor (`by`: `cpu`) or memory (`memory`), or those whose name has a text (`name`: is a program running?): each with its process number, its user, its share of the whole processor over half a second, its memory, how long it has been running. A program's name only, never its arguments.
+- **`system_errors`** - the errors of the system's logs since the computer started or in the last hours (`hours`), the same message of the same program counted once with its latest time, and the services that failed.
+- **`system_updates`** - the updates of the installed packages, those for security counted, by the list the package manager last fetched (and when that was), with the command that fetches it again.
+- **`system_network`** - the network interfaces, their state and addresses, the speed of a cable, the Wi-Fi signal, what each has received and sent; the gateway and the name servers.
+
+## Where it reads
+
+| | Linux | Windows |
+|---|---|---|
+| memory, processor | `/proc` | `GlobalMemoryStatusEx`, `GetSystemTimes` |
+| disks | `/proc/self/mountinfo`, `statvfs` | the drives, `GetDiskFreeSpaceEx` |
+| battery | `/sys/class/power_supply` | `GetSystemPowerStatus` (its wear is not told) |
+| temperatures | `/sys/class/hwmon` | not told: they need WMI and an administrator |
+| processes | `/proc/<pid>` | Tool Help, `GetProcessTimes` |
+| errors | `journalctl` (priority error and above), `systemctl --failed` (the system's and the user's) | the event log (System and Application, levels critical and error), the services set to start by themselves and stopped with an error |
+| updates | `apt list --upgradable`, `dnf check-update --cacheonly`, `pacman -Qu`: what they already know, nothing fetched | not read: they are Windows Update's (the answer says where to look) |
+| network | `getifaddrs`, `/sys/class/net`, `/proc/net/wireless`, `/proc/net/route`, `/etc/resolv.conf` | IP Helper, the WLAN API |
+
+- **Within limits.** What fills a directory is read for 8 seconds at most, 64 levels deep at most, never across to another filesystem nor through a symbolic link (on Windows, a junction or a mounted volume); when the time runs out the answer says the sizes are at least those. On Linux a size is the space the files take on the disk; on Windows, their lengths. A file of more names than one (hard links) is counted at each.
+- **The logs as you may read them.** Without the groups `adm` or `systemd-journal`, `journalctl` shows only your own programs' and session's messages: the answer says so, and asks for nothing more. The latest are read first; when there are more than 2,000, or more than a megabyte of them, the answer says the count is at least that. A message is its first line (a core dump's modules and stack are for the log's own reader), and the same text but for its numbers (a process's number, a time) is counted once.
+- **Nothing that needs root**, nothing run through a shell: the programs it starts run with their arguments as they are, without a terminal, with a time limit (as `janas-git`'s).
+- **Nothing changed.** To stop a program or install the updates, the model tells you how.
+
+## The answers
+
+Every answer is data with a layout (see [the services](README.md)): `janas-chat` shows you the whole of it in your language - every disk, process, error, package - and gives the model only a brief, from which it answers in a line or two; for the status, it is told to say only what is wrong (a disk nearly full, memory short, a temperature near its limit, a worn battery), or that all is well. Sizes, percentages and times are worked out by the service, so that the model does no sums.
+
+## Running it
+
+```sh
+janas-system
+```
+
+It speaks MCP over its standard input and output and writes what it does on its standard error. In other clients:
+
+```sh
+claude mcp add system -- /path/to/janas-system
+```
+
+```json
+{"mcpServers": {"system": {"command": "/path/to/janas-system"}}}
+```
+
+A client that sends its model's requests to a server elsewhere sends there the briefs too: the names of the programs running, the paths in your home, the lines of the logs.
+
+## Windows
+
+Janas is not built for Windows yet. `janas-system`'s Windows part is written for the Win32 API, and has been compiled and linked with MinGW-w64; it has not been run on Windows.
+
+## What has been run
+
+2 October 2026, on the development laptop (Debian 13), over the protocol, in the release build: the status (with the machine busy with other work, the load at 17 to 25), the disks, what fills the home (the time ran out after 8 seconds, at 55.6 GB), the processes by processor, by memory and by name, the errors since the start and in the last 2 hours, the updates (96, 95 for security, by apt's list), the network, a path that does not exist. The parsing of Linux's texts and the layouts are checked by `tests/test_system_parse.c`, on texts of that machine; those of dnf and pacman are written from their documentation, as no such system was at hand.
+
+In `janas-chat` with Qwen3.6-35B-A3B, the same night, in Italian, on a pipe: "Come sta il computer?" (all is well, it said), "Cosa occupa spazio nella home?", "Quali programmi usano più memoria?", "Gira Firefox?", "Ci sono errori nelle ultime ore?" (it took the last 24 hours), "Ci sono aggiornamenti?": each answered from its tool, the lists shown in Italian. The status's layout came back from the model untranslated, and was refused (English was shown); `janas-chat` now asks once more when that happens, and run again, the status came in Italian.
+
+The Windows part, under Wine 10 in a prefix of its own: the status, the processes, the errors of the last 24 hours, the network and what fills `C:\windows` came back without errors; Wine gives no event log and no Wi-Fi signal of its own, so those were not tried.
diff --git a/src/chat/layout.c b/src/chat/layout.c
index 7983c80..005533c 100644
--- a/src/chat/layout.c
+++ b/src/chat/layout.c
@@ -417,36 +417,47 @@ static char *translated(const char *name, const char *en)
struct coded c;
if (!translator || encode(en, &c) != 0)
return NULL;
- struct janas_buf ask = {0};
const char *terms = glossary_terms(lang, name);
- janas_buf_printf(&ask, "Translate into %s%s%s:\n\n%.*s", lang_name(lang),
- terms ? ", with these terms: " : "", terms ? terms : "",
- (int)c.text.n, c.text.p);
- char *ans = NULL;
- int r = ask.oom ? -1 : translator(name, SYSTEM, ask.p, &ans);
- janas_buf_free(&ask);
char *out = NULL;
- if (r == 0 && ans) {
- unwrap(ans);
- /* the text given back as it came: the 35B did so with GitHub's
- issues, translating only the words. Not kept, so that it is
- asked again the next time. */
- const char *w = strstr(ans, "=== words");
- const char *cw = strstr(c.text.p, "\n=== words");
- size_t an = w ? (size_t)(w - ans) : strlen(ans);
- size_t cn = cw ? (size_t)(cw - c.text.p) : c.text.n;
- while (an && (ans[an - 1] == '\n' || ans[an - 1] == ' '))
- an--;
- while (cn && (c.text.p[cn - 1] == '\n' || c.text.p[cn - 1] == ' '))
- cn--;
- if (an == cn && memcmp(ans, c.text.p, cn) == 0)
- snprintf(why, sizeof why, "the text came back untranslated");
- else
- out = decode(&c, ans, why, sizeof why);
- } else {
- snprintf(why, sizeof why, "no answer");
+ /* the text given back as it came: the 35B did so with GitHub's issues
+ and with janas-system's status, dense with markers, translating only
+ the words. Asked once more, told so; else not kept, so that it is
+ asked again the next time. */
+ for (int again = 0; again < 2 && !out; again++) {
+ struct janas_buf ask = {0};
+ janas_buf_printf(&ask, "%sTranslate into %s%s%s:\n\n%.*s",
+ again ? "The text came back as it was, untranslated: "
+ "this time translate every word of it, "
+ "between the markers too. "
+ : "",
+ lang_name(lang), terms ? ", with these terms: " : "",
+ terms ? terms : "", (int)c.text.n, c.text.p);
+ char *ans = NULL;
+ int r = ask.oom ? -1 : translator(name, SYSTEM, ask.p, &ans);
+ janas_buf_free(&ask);
+ int same = 0;
+ if (r == 0 && ans) {
+ unwrap(ans);
+ const char *w = strstr(ans, "=== words");
+ const char *cw = strstr(c.text.p, "\n=== words");
+ size_t an = w ? (size_t)(w - ans) : strlen(ans);
+ size_t cn = cw ? (size_t)(cw - c.text.p) : c.text.n;
+ while (an && (ans[an - 1] == '\n' || ans[an - 1] == ' '))
+ an--;
+ while (cn && (c.text.p[cn - 1] == '\n' || c.text.p[cn - 1] == ' '))
+ cn--;
+ same = an == cn && memcmp(ans, c.text.p, cn) == 0;
+ if (same)
+ snprintf(why, sizeof why, "the text came back untranslated");
+ else
+ out = decode(&c, ans, why, sizeof why);
+ } else {
+ snprintf(why, sizeof why, "no answer");
+ }
+ free(ans);
+ if (!same)
+ break; /* asked again only for that */
}
- free(ans);
coded_free(&c);
if (out && !janas_tpl_same_shape(en, strlen(en), out, strlen(out), why,
sizeof why)) {
diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.c
index d894a9c..8b971bb 100644
--- a/src/chat/mcp_chat.c
+++ b/src/chat/mcp_chat.c
@@ -50,6 +50,9 @@ static const struct {
{"prices", "prices and finance, for information: currencies, "
"crypto-assets, shares, inflation, central banks' rates, "
"electricity, the cheapest fuel near a place"},
+ {"system", "this computer: how it is (memory, processor, disks, "
+ "battery, temperatures), what fills a folder, the programs "
+ "running, the errors, the updates, the network"},
{"weather", "the weather now and the forecast, the sea and its waves, "
"weather warnings"},
{"wiki", "Wikipedia, when the user asks for it: a page shown to the "
diff --git a/src/services/common/run.c b/src/services/common/run.c
new file mode 100644
index 0000000..865a39d
--- /dev/null
+++ b/src/services/common/run.c
@@ -0,0 +1,127 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * run.c - a program run by a service (see run.h): no shell, no terminal,
+ * a time limit for it and what it started.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "run.h"
+
+static double now_ms(void)
+{
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return (double)t.tv_sec * 1e3 + (double)t.tv_nsec / 1e6;
+}
+
+int janas_run(const char *dir, const char *const *argv, const char *const *env,
+ int timeout_ms, struct janas_buf *out, struct janas_buf *err,
+ char *why, size_t why_len)
+{
+ const char *name = strrchr(argv[0], '/');
+ name = name ? name + 1 : argv[0];
+ int po[2], pe[2];
+ if (pipe2(po, O_CLOEXEC) != 0) {
+ snprintf(why, why_len, "no pipe: %s", strerror(errno));
+ return -1;
+ }
+ if (pipe2(pe, O_CLOEXEC) != 0) {
+ close(po[0]);
+ close(po[1]);
+ snprintf(why, why_len, "no pipe: %s", strerror(errno));
+ return -1;
+ }
+ pid_t pid = fork();
+ if (pid < 0) {
+ snprintf(why, why_len, "cannot start %s: %s", name, strerror(errno));
+ close(po[0]), close(po[1]), close(pe[0]), close(pe[1]);
+ return -1;
+ }
+ if (pid == 0) {
+ setsid(); /* no terminal: nothing can be asked of the user */
+ int nul = open("/dev/null", O_RDONLY);
+ if (nul >= 0)
+ dup2(nul, 0);
+ dup2(po[1], 1);
+ dup2(pe[1], 2);
+ if (dir && chdir(dir) != 0)
+ _exit(126);
+ for (size_t i = 0; env && env[i]; i++)
+ putenv((char *)env[i]);
+ execvp(argv[0], (char *const *)argv);
+ _exit(127);
+ }
+ close(po[1]);
+ close(pe[1]);
+ struct pollfd fd[2] = {{.fd = po[0], .events = POLLIN},
+ {.fd = pe[0], .events = POLLIN}};
+ struct janas_buf *to[2] = {out, err};
+ double end = now_ms() + timeout_ms;
+ int open_n = 2, late = 0;
+ while (open_n) {
+ int left = (int)(end - now_ms());
+ if (left <= 0) {
+ late = 1;
+ break;
+ }
+ if (poll(fd, 2, left) < 0) {
+ if (errno == EINTR)
+ continue;
+ break;
+ }
+ for (int i = 0; i < 2; i++) {
+ if (fd[i].fd < 0 || !(fd[i].revents & (POLLIN | POLLHUP | POLLERR)))
+ continue;
+ char chunk[8192];
+ ssize_t r = read(fd[i].fd, chunk, sizeof chunk);
+ if (r > 0 && to[i]->n < JANAS_RUN_OUT_MAX)
+ janas_buf_put(to[i], chunk, (size_t)r);
+ else if (r == 0 || (r < 0 && errno != EINTR)) {
+ close(fd[i].fd);
+ fd[i].fd = -1;
+ open_n--;
+ }
+ }
+ }
+ for (int i = 0; i < 2; i++)
+ if (fd[i].fd >= 0)
+ close(fd[i].fd);
+ if (late)
+ kill(-pid, SIGKILL); /* it and what it started */
+ int st = 0;
+ while (waitpid(pid, &st, 0) < 0 && errno == EINTR)
+ ;
+ janas_buf_put(out, "", 1);
+ out->n--;
+ janas_buf_put(err, "", 1);
+ err->n--;
+ if (late) {
+ snprintf(why, why_len, "%s took over %d s and was stopped", name,
+ timeout_ms / 1000);
+ return -1;
+ }
+ if (!WIFEXITED(st)) {
+ snprintf(why, why_len, "%s stopped by a signal", name);
+ return -1;
+ }
+ if (WEXITSTATUS(st) == 127) {
+ snprintf(why, why_len, "%s is not installed", name);
+ return -1;
+ }
+ if (WEXITSTATUS(st) == 126) {
+ snprintf(why, why_len, "cannot enter %s", dir);
+ return -1;
+ }
+ return WEXITSTATUS(st);
+}
diff --git a/src/services/common/run.h b/src/services/common/run.h
new file mode 100644
index 0000000..04947c3
--- /dev/null
+++ b/src/services/common/run.h
@@ -0,0 +1,31 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * run.h - a program run by a service (run.c): with its arguments as they
+ * are, no shell between; in a session of its own, without a terminal and
+ * with nothing on its input, so that a question it asks (a password)
+ * fails at once instead of waiting for an answer nobody can give; with a
+ * time limit, after which it and what it started are stopped. POSIX only.
+ */
+#ifndef JANAS_SERVICES_RUN_H
+#define JANAS_SERVICES_RUN_H
+
+#include <stddef.h>
+
+#include "llm/json.h"
+
+#define JANAS_RUN_OUT_MAX (1u << 20) /* of each stream kept */
+
+/*
+ * argv[0] (looked for in PATH) with argv (NULL-ended), in the directory
+ * dir (NULL: where the service runs), with env added to the environment
+ * ("NAME=value", NULL-ended; NULL: none), at most timeout_ms. Its output
+ * into out, what it wrote on its error stream into err, each cut at
+ * JANAS_RUN_OUT_MAX and ended by a 0 not counted. Its exit status, or -1
+ * when it could not be run or took too long (the reason in why).
+ */
+int janas_run(const char *dir, const char *const *argv, const char *const *env,
+ int timeout_ms, struct janas_buf *out, struct janas_buf *err,
+ char *why, size_t why_len);
+
+#endif
diff --git a/src/services/git/run.c b/src/services/git/run.c
index be3b7d7..229cc7d 100644
--- a/src/services/git/run.c
+++ b/src/services/git/run.c
@@ -1,138 +1,30 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
/*
- * run.c - janas-git runs git (see git.h): with its arguments as they are,
- * no shell between; in a session of its own, without a terminal, so that
- * a password asked (ssh, https) fails at once instead of waiting for an
- * answer nobody can give; with a time limit, after which git and what it
- * started are stopped.
+ * run.c - janas-git runs git (see git.h) as the services run a program
+ * (services/common/run.h): no shell, no terminal, so that a password asked
+ * (ssh, https) fails at once, and a time limit; with git's own settings
+ * for that.
*/
-#define _GNU_SOURCE
-#include <errno.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <signal.h>
#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/wait.h>
-#include <time.h>
-#include <unistd.h>
#include "git.h"
-
-#define OUT_MAX (1u << 20)
-
-static double now_ms(void)
-{
- struct timespec t;
- clock_gettime(CLOCK_MONOTONIC, &t);
- return (double)t.tv_sec * 1e3 + (double)t.tv_nsec / 1e6;
-}
+#include "services/common/run.h"
int gt_run(const char *dir, const char *const *argv, int timeout_ms,
struct janas_buf *out, struct janas_buf *err, char *why,
size_t why_len)
{
+ static const char *const env[] = {
+ "GIT_TERMINAL_PROMPT=0", "GIT_EDITOR=true",
+ "GIT_OPTIONAL_LOCKS=0", /* status takes no lock */
+ "LC_ALL=C", /* git's words, in English */
+ NULL};
const char *av[64];
size_t n = 0;
av[n++] = "git";
for (size_t i = 0; argv[i] && n < 63; i++)
av[n++] = argv[i];
av[n] = NULL;
- int po[2], pe[2];
- if (pipe2(po, O_CLOEXEC) != 0) {
- snprintf(why, why_len, "no pipe: %s", strerror(errno));
- return -1;
- }
- if (pipe2(pe, O_CLOEXEC) != 0) {
- close(po[0]);
- close(po[1]);
- snprintf(why, why_len, "no pipe: %s", strerror(errno));
- return -1;
- }
- pid_t pid = fork();
- if (pid < 0) {
- snprintf(why, why_len, "cannot start git: %s", strerror(errno));
- close(po[0]), close(po[1]), close(pe[0]), close(pe[1]);
- return -1;
- }
- if (pid == 0) {
- setsid(); /* no terminal: nothing can be asked of the user */
- int nul = open("/dev/null", O_RDONLY);
- if (nul >= 0)
- dup2(nul, 0);
- dup2(po[1], 1);
- dup2(pe[1], 2);
- if (chdir(dir) != 0)
- _exit(126);
- setenv("GIT_TERMINAL_PROMPT", "0", 1);
- setenv("GIT_EDITOR", "true", 1);
- setenv("GIT_OPTIONAL_LOCKS", "0", 1); /* status takes no lock */
- setenv("LC_ALL", "C", 1); /* git's words, in English */
- execvp("git", (char *const *)av);
- _exit(127);
- }
- close(po[1]);
- close(pe[1]);
- struct pollfd fd[2] = {{.fd = po[0], .events = POLLIN},
- {.fd = pe[0], .events = POLLIN}};
- struct janas_buf *to[2] = {out, err};
- double end = now_ms() + timeout_ms;
- int open_n = 2, late = 0;
- while (open_n) {
- int left = (int)(end - now_ms());
- if (left <= 0) {
- late = 1;
- break;
- }
- if (poll(fd, 2, left) < 0) {
- if (errno == EINTR)
- continue;
- break;
- }
- for (int i = 0; i < 2; i++) {
- if (fd[i].fd < 0 || !(fd[i].revents & (POLLIN | POLLHUP | POLLERR)))
- continue;
- char chunk[8192];
- ssize_t r = read(fd[i].fd, chunk, sizeof chunk);
- if (r > 0 && to[i]->n < OUT_MAX)
- janas_buf_put(to[i], chunk, (size_t)r);
- else if (r == 0 || (r < 0 && errno != EINTR)) {
- close(fd[i].fd);
- fd[i].fd = -1;
- open_n--;
- }
- }
- }
- for (int i = 0; i < 2; i++)
- if (fd[i].fd >= 0)
- close(fd[i].fd);
- if (late)
- kill(-pid, SIGKILL); /* git and what it started (ssh) */
- int st = 0;
- while (waitpid(pid, &st, 0) < 0 && errno == EINTR)
- ;
- janas_buf_put(out, "", 1);
- out->n--;
- janas_buf_put(err, "", 1);
- err->n--;
- if (late) {
- snprintf(why, why_len, "git took over %d s and was stopped",
- timeout_ms / 1000);
- return -1;
- }
- if (!WIFEXITED(st)) {
- snprintf(why, why_len, "git stopped by a signal");
- return -1;
- }
- if (WEXITSTATUS(st) == 127) {
- snprintf(why, why_len, "git is not installed");
- return -1;
- }
- if (WEXITSTATUS(st) == 126) {
- snprintf(why, why_len, "cannot enter %s", dir);
- return -1;
- }
- return WEXITSTATUS(st);
+ return janas_run(dir, av, env, timeout_ms, out, err, why, why_len);
}
diff --git a/src/services/system/data.c b/src/services/system/data.c
new file mode 100644
index 0000000..4ec8244
--- /dev/null
+++ b/src/services/system/data.c
@@ -0,0 +1,335 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * data.c - what janas-system read, as the data of its layouts (see
+ * system.h, layouts.c and services/common/template.h). Every field is
+ * written, even empty: a layout looks a name up in the item, then in what
+ * holds it. Sizes, percentages and times are worked out here, rounded, so
+ * that neither the layout nor the model does sums: a size is {"v": 12.5,
+ * "u": "GB"} (of 1024, as the file managers count).
+ */
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+
+#include "system.h"
+
+void sy_jstr(struct janas_buf *b, const char *key, const char *v)
+{
+ if (!v)
+ v = "";
+ janas_buf_printf(b, ", \"%s\": ", key);
+ janas_json_write_str(b, v, strlen(v));
+}
+
+static double round1(double x)
+{
+ return floor(x * 10 + 0.5) / 10;
+}
+
+static void jsize(struct janas_buf *b, const char *key, uint64_t bytes)
+{
+ static const char *const unit[] = {"B", "KB", "MB", "GB", "TB", "PB"};
+ double v = (double)bytes;
+ int u = 0;
+ while (v >= 1024 && u < 5)
+ v /= 1024, u++;
+ /* 1 decimal below 100, none above */
+ v = v < 100 && u ? round1(v) : floor(v + 0.5);
+ janas_buf_printf(b, ", \"%s\": {\"v\": %g, \"u\": \"%s\"}", key, v,
+ unit[u]);
+}
+
+static int pct(uint64_t part, uint64_t whole)
+{
+ return whole ? (int)((double)part * 100 / (double)whole + 0.5) : 0;
+}
+
+static void jspan(struct janas_buf *b, const char *key, long s)
+{
+ if (s < 0)
+ s = 0;
+ janas_buf_printf(b, ", \"%s\": {\"d\": %ld, \"h\": %ld, \"m\": %ld}", key,
+ s / 86400, s / 3600 % 24, s / 60 % 60);
+}
+
+static void jwhen(struct janas_buf *b, const char *key, long long at)
+{
+ time_t t = (time_t)at, now = time(NULL);
+ struct tm lt, nt;
+#ifdef _WIN32
+ localtime_s(&lt, &t);
+ localtime_s(&nt, &now);
+#else
+ localtime_r(&t, &lt);
+ localtime_r(&now, &nt);
+#endif
+ long ago = at > 0 ? (long)((now - t) / 86400) : 0;
+ janas_buf_printf(
+ b,
+ ", \"%s\": {\"has\": %s, \"day\": %d, \"mon\": %d, "
+ "\"at\": \"%02d:%02d\", \"today\": %s, \"ago_d\": %ld}",
+ key, at > 0 ? "true" : "false", lt.tm_mday, lt.tm_mon + 1, lt.tm_hour,
+ lt.tm_min,
+ lt.tm_yday == nt.tm_yday && lt.tm_year == nt.tm_year ? "true" : "false",
+ ago < 0 ? 0 : ago);
+}
+
+static const char *tf(int v)
+{
+ return v ? "true" : "false";
+}
+
+/* a path with the home as "~" */
+static void jpath(struct janas_buf *b, const char *key, const char *path)
+{
+ const char *home = sy_home();
+ size_t h = strlen(home);
+ char out[1100];
+ if (h > 1 && !strncmp(path, home, h) && (path[h] == '/' || !path[h]))
+ snprintf(out, sizeof out, "~%s", path + h);
+ else
+ sy_put(out, sizeof out, path);
+ sy_jstr(b, key, out);
+}
+
+static void disk(struct janas_buf *b, const struct sy_disk *d, int first)
+{
+ uint64_t used = d->total > d->avail ? d->total - d->avail : 0;
+ int p = pct(used, d->total);
+ janas_buf_puts(b, first ? "{" : ", {");
+ janas_buf_puts(b, "\"mount\": ");
+ janas_json_write_str(b, d->mount, strlen(d->mount));
+ sy_jstr(b, "dev", d->dev);
+ sy_jstr(b, "fs", d->fs);
+ jsize(b, "used", used);
+ jsize(b, "total", d->total);
+ jsize(b, "avail", d->avail);
+ janas_buf_printf(b, ", \"pct\": %d, \"full\": %s, \"ro\": %s}", p,
+ tf(p >= SY_FULL_PCT), tf(d->ro));
+}
+
+void sy_status_data(struct janas_buf *b, const struct sy_status *s)
+{
+ janas_buf_puts(b, "{\"host\": ");
+ janas_json_write_str(b, s->host, strlen(s->host));
+ sy_jstr(b, "os", s->os);
+ sy_jstr(b, "kernel", s->kernel);
+ sy_jstr(b, "cpu", s->cpu);
+ sy_jstr(b, "platform", s->platform);
+ janas_buf_printf(b, ", \"cpus\": %d", s->cpus);
+ jspan(b, "up", s->uptime_s);
+ janas_buf_printf(b,
+ ", \"has_load\": %s, \"load1\": %.2f, \"load5\": %.2f, "
+ "\"load15\": %.2f",
+ tf(s->has_load), s->load[0], s->load[1], s->load[2]);
+ janas_buf_printf(b, ", \"has_cpu\": %s, \"cpu_pct\": %d, \"sys_pct\": %d",
+ tf(s->cpu_pct >= 0), (int)(s->cpu_pct + 0.5),
+ (int)(s->sys_pct + 0.5));
+ uint64_t used =
+ s->mem_total > s->mem_avail ? s->mem_total - s->mem_avail : 0;
+ janas_buf_puts(b, ", \"mem\": {\"x\": 1");
+ jsize(b, "used", used);
+ jsize(b, "total", s->mem_total);
+ jsize(b, "avail", s->mem_avail);
+ janas_buf_printf(b, ", \"pct\": %d}", pct(used, s->mem_total));
+ uint64_t sw =
+ s->swap_total > s->swap_free ? s->swap_total - s->swap_free : 0;
+ janas_buf_printf(b, ", \"swap\": {\"has\": %s", tf(s->swap_total > 0));
+ jsize(b, "used", sw);
+ jsize(b, "total", s->swap_total);
+ janas_buf_printf(b, ", \"pct\": %d}", pct(sw, s->swap_total));
+ janas_buf_printf(
+ b,
+ ", \"psi\": {\"has\": %s, \"cpu\": %g, \"mem\": %g, "
+ "\"io\": %g, \"high\": %s}",
+ tf(s->psi_cpu >= 0), round1(s->psi_cpu > 0 ? s->psi_cpu : 0),
+ round1(s->psi_mem > 0 ? s->psi_mem : 0),
+ round1(s->psi_io > 0 ? s->psi_io : 0),
+ tf(s->psi_cpu >= 20 || s->psi_mem >= 10 || s->psi_io >= 20));
+ int full = 0;
+ janas_buf_puts(b, ", \"disks\": [");
+ for (int i = 0; i < s->disks.n; i++) {
+ disk(b, &s->disks.d[i], i == 0);
+ const struct sy_disk *d = &s->disks.d[i];
+ full += pct(d->total - d->avail, d->total) >= SY_FULL_PCT;
+ }
+ janas_buf_printf(b, "], \"full_n\": %d", full);
+ const struct sy_battery *t = &s->bat;
+ janas_buf_printf(b,
+ ", \"bat\": {\"present\": %s, \"pct\": %d, \"state\": "
+ "\"%s\", \"mains\": %s, \"draining\": %s, "
+ "\"has_time\": %s",
+ tf(t->present), t->pct < 0 ? 0 : t->pct, t->state,
+ tf(t->mains == 1), tf(!strcmp(t->state, "discharging")),
+ tf(t->minutes > 0));
+ jspan(b, "time", t->minutes > 0 ? (long)t->minutes * 60 : 0);
+ janas_buf_printf(b, ", \"health\": %d, \"worn\": %s}",
+ t->health < 0 ? 0 : t->health,
+ tf(t->health >= 0 && t->health < 80));
+ janas_buf_printf(b, ", \"n_temps\": %d, \"temps\": [", s->n_temps);
+ int hot = 0;
+ for (int i = 0; i < s->n_temps; i++) {
+ const struct sy_temp *x = &s->t[i];
+ int h = x->high > 0 && x->c >= x->high - 10;
+ hot += h;
+ janas_buf_printf(b, "%s{\"kind\": \"%s\"", i ? ", " : "", x->kind);
+ sy_jstr(b, "label", x->label);
+ janas_buf_printf(b, ", \"c\": %d, \"high\": %d, \"hot\": %s}",
+ (int)(x->c + 0.5), (int)(x->high + 0.5), tf(h));
+ }
+ janas_buf_printf(b, "], \"hot_n\": %d}", hot);
+}
+
+void sy_disks_data(struct janas_buf *b, const struct sy_disks *d)
+{
+ janas_buf_printf(b, "{\"n\": %d, \"more\": %d, \"disks\": [", d->n,
+ d->more);
+ for (int i = 0; i < d->n; i++)
+ disk(b, &d->d[i], i == 0);
+ janas_buf_puts(b, "]}");
+}
+
+void sy_procs_data(struct janas_buf *b, const struct sy_procs *p)
+{
+ janas_buf_printf(b, "{\"by\": \"%s\"", p->by);
+ sy_jstr(b, "name", p->name);
+ janas_buf_printf(b,
+ ", \"total\": %d, \"matched\": %d, \"n\": %d, \"more\": "
+ "%d, \"items\": [",
+ p->total, p->matched, p->n, p->matched - p->n);
+ for (int i = 0; i < p->n; i++) {
+ const struct sy_proc *x = &p->p[i];
+ janas_buf_printf(b, "%s{\"pid\": %d", i ? ", " : "", x->pid);
+ sy_jstr(b, "pname", x->name);
+ sy_jstr(b, "user", x->user);
+ janas_buf_printf(b, ", \"cpu\": %g", round1(x->cpu_pct));
+ jsize(b, "mem", x->mem);
+ janas_buf_printf(
+ b, ", \"mem_pct\": %g, \"threads\": %d",
+ p->mem_total ? round1((double)x->mem * 100 / (double)p->mem_total)
+ : 0,
+ x->threads);
+ jspan(b, "age", x->age_s);
+ janas_buf_puts(b, "}");
+ }
+ janas_buf_puts(b, "]}");
+}
+
+void sy_errors_data(struct janas_buf *b, const struct sy_errors *e)
+{
+ janas_buf_printf(b,
+ "{\"hours\": %d, \"boot\": %s, \"user_only\": %s, "
+ "\"how\": \"%s\", \"total\": %d, \"cut\": %s, \"n\": %d, "
+ "\"more\": %d",
+ e->hours, tf(e->hours <= 0), tf(e->user_only), e->how,
+ e->total, tf(e->cut), e->n, e->more);
+ janas_buf_puts(b, ", \"items\": [");
+ for (int i = 0; i < e->n; i++) {
+ const struct sy_err *x = &e->e[i];
+ janas_buf_puts(b, i ? ", {\"who\": " : "{\"who\": ");
+ janas_json_write_str(b, x->who, strlen(x->who));
+ sy_jstr(b, "text", x->text);
+ janas_buf_printf(b, ", \"count\": %d, \"again\": %s", x->count,
+ tf(x->count > 1));
+ jwhen(b, "when", x->at);
+ janas_buf_puts(b, "}");
+ }
+ janas_buf_printf(b, "], \"n_failed\": %d, \"more_failed\": %d", e->n_failed,
+ e->more_failed);
+ janas_buf_puts(b, ", \"failed\": [");
+ for (int i = 0; i < e->n_failed; i++) {
+ janas_buf_puts(b, i ? ", {\"unit\": " : "{\"unit\": ");
+ janas_json_write_str(b, e->failed[i], strlen(e->failed[i]));
+ janas_buf_printf(b, ", \"count\": %d, \"again\": %s}", e->failed_n[i],
+ tf(e->failed_n[i] > 1));
+ }
+ janas_buf_puts(b, "]}");
+}
+
+void sy_updates_data(struct janas_buf *b, const struct sy_updates *u)
+{
+ janas_buf_printf(b,
+ "{\"tool\": \"%s\", \"total\": %d, \"n\": %d, \"more\": "
+ "%d, \"security\": %d",
+ u->tool, u->total, u->n, u->total - u->n, u->security);
+ jwhen(b, "checked", u->checked);
+ /* how the list is fetched again: a command, never translated */
+ sy_jstr(b, "refresh",
+ !strcmp(u->tool, "apt") ? "sudo apt update"
+ : !strcmp(u->tool, "dnf") ? "dnf makecache"
+ : !strcmp(u->tool, "pacman") ? "checkupdates (pacman-contrib)"
+ : "");
+ janas_buf_puts(b, ", \"items\": [");
+ for (int i = 0; i < u->n; i++) {
+ const struct sy_update *x = &u->u[i];
+ janas_buf_puts(b, i ? ", {\"pkg\": " : "{\"pkg\": ");
+ janas_json_write_str(b, x->name, strlen(x->name));
+ sy_jstr(b, "to", x->to);
+ sy_jstr(b, "from", x->from);
+ janas_buf_printf(b, ", \"sec\": %s}", tf(x->security));
+ }
+ janas_buf_puts(b, "]}");
+}
+
+void sy_net_data(struct janas_buf *b, const struct sy_net *n)
+{
+ janas_buf_puts(b, "{\"gateway\": ");
+ janas_json_write_str(b, n->gateway, strlen(n->gateway));
+ sy_jstr(b, "gw_iface", n->gw_iface);
+ janas_buf_puts(b, ", \"dns\": [");
+ for (int i = 0; i < n->n_dns; i++) {
+ janas_buf_puts(b, i ? ", " : "");
+ janas_json_write_str(b, n->dns[i], strlen(n->dns[i]));
+ }
+ janas_buf_printf(b,
+ "], \"n_dns\": %d, \"n\": %d, \"more\": %d, \"items\": [",
+ n->n_dns, n->n, n->more);
+ for (int i = 0; i < n->n; i++) {
+ const struct sy_iface *x = &n->i[i];
+ janas_buf_puts(b, i ? ", {\"name\": " : "{\"name\": ");
+ janas_json_write_str(b, x->name, strlen(x->name));
+ janas_buf_printf(b, ", \"kind\": \"%s\", \"state\": \"%s\"", x->kind,
+ x->state);
+ janas_buf_printf(b, ", \"up\": %s", tf(!strcmp(x->state, "up")));
+ janas_buf_puts(b, ", \"addrs\": [");
+ for (int k = 0; k < x->n_addr; k++) {
+ janas_buf_puts(b, k ? ", " : "");
+ janas_json_write_str(b, x->addr[k], strlen(x->addr[k]));
+ }
+ janas_buf_printf(b,
+ "], \"speed\": %ld, \"signal\": %d, \"wifi_pct\": "
+ "%d, \"gw\": %s",
+ x->speed_mbps, x->signal_dbm, x->wifi_pct,
+ tf(!strcmp(x->name, n->gw_iface)));
+ jsize(b, "rx", x->rx);
+ jsize(b, "tx", x->tx);
+ janas_buf_puts(b, "}");
+ }
+ janas_buf_puts(b, "]}");
+}
+
+void sy_usage_data(struct janas_buf *b, const struct sy_usage *u)
+{
+ janas_buf_puts(b, "{\"x\": 1");
+ jpath(b, "path", u->path);
+ jsize(b, "total", u->total);
+ jsize(b, "fs_total", u->fs_total);
+ jsize(b, "fs_avail", u->fs_avail);
+ janas_buf_printf(b,
+ ", \"files\": %ld, \"unread\": %ld, \"cut\": %s, "
+ "\"secs\": %g, \"n\": %d, \"more\": %d, \"items\": [",
+ u->files, u->unread, tf(u->cut), round1(u->secs), u->n,
+ u->more);
+ for (int i = 0; i < u->n; i++) {
+ const struct sy_entry *x = &u->e[i];
+ janas_buf_puts(b, i ? ", {\"entry\": " : "{\"entry\": ");
+ janas_json_write_str(b, x->name, strlen(x->name));
+ janas_buf_printf(b, ", \"dir\": %s, \"files\": %ld", tf(x->dir),
+ x->files);
+ jsize(b, "size", x->bytes);
+ janas_buf_printf(b, ", \"pct\": %d}", pct(x->bytes, u->total));
+ }
+ janas_buf_puts(b, "]}");
+}
diff --git a/src/services/system/layouts.c b/src/services/system/layouts.c
new file mode 100644
index 0000000..c7cbaa1
--- /dev/null
+++ b/src/services/system/layouts.c
@@ -0,0 +1,230 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * layouts.c - the layouts of janas-system's answers (see system.h and
+ * services/common/template.h): the text the user reads, filled with the
+ * data in English here and in the user's language by a client that
+ * translates the layout once (janas-chat), and the brief, all the model
+ * reads of it. Names of programs, paths, messages of the logs and of the
+ * packages stay as they are.
+ */
+#include "system.h"
+
+#define SIZE_USED "{{used.v}} {{used.u}}"
+#define SIZE_TOTAL "{{total.v}} {{total.u}}"
+#define SIZE_AVAIL "{{avail.v}} {{avail.u}}"
+#define WHEN \
+ "{{#when.today}}today{{/when.today}}{{^when.today}}{{when.day}}/" \
+ "{{when.mon}}{{/when.today}} {{when.at}}"
+#define SHOWN \
+ " Shown to the user: do not repeat it; answer in a line or two, in the " \
+ "user's language."
+
+const char SY_STATUS_LAYOUT[] =
+ "{{host}}: {{os}}{{#kernel}}, {{kernel}}{{/kernel}}; on for "
+ "{{#up.d}}{{up.d}} d {{/up.d}}{{up.h}} h {{up.m}} min.\n"
+ "Processor: {{cpu}}, {{cpus}} threads{{#has_cpu}}, {{cpu_pct}}% in "
+ "use{{#sys_pct}} ({{sys_pct}}% by the kernel){{/sys_pct}}{{/has_cpu}}{{#has_load}}; load {{load1}}, {{load5}}, {{load15}} "
+ "(1, 5, 15 min){{/has_load}}.\n"
+ "Memory: {{mem.used.v}} {{mem.used.u}} used of {{mem.total.v}} "
+ "{{mem.total.u}} ({{mem.pct}}%), {{mem.avail.v}} {{mem.avail.u}} "
+ "available{{#swap.has}}; swap: {{swap.used.v}} {{swap.used.u}} of "
+ "{{swap.total.v}} {{swap.total.u}}{{/swap.has}}.\n"
+ "{{#psi.high}}\n"
+ "Waiting, of the last 10 seconds: for the processor {{psi.cpu}}%, for "
+ "memory {{psi.mem}}%, for the disks {{psi.io}}%.\n"
+ "{{/psi.high}}\n"
+ "Disks:\n"
+ "{{#disks}}\n"
+ " {{mount}}: " SIZE_USED " of " SIZE_TOTAL " ({{pct}}%), " SIZE_AVAIL
+ " free{{#full}} - nearly full{{/full}}\n"
+ "{{/disks}}\n"
+ "{{#bat.present}}\n"
+ "Battery: {{bat.pct}}%, {{bat.state|bat}}{{#bat.has_time}}, "
+ "{{#bat.draining}}{{bat.time.h}} h {{bat.time.m}} min "
+ "left{{/bat.draining}}{{^bat.draining}}full in {{bat.time.h}} h "
+ "{{bat.time.m}} min{{/bat.draining}}{{/bat.has_time}}{{#bat.health}}; "
+ "capacity: {{bat.health}}% of what it was new{{/bat.health}}.\n"
+ "{{/bat.present}}\n"
+ "{{#n_temps}}\n"
+ "Temperatures:\n"
+ "{{/n_temps}}\n"
+ "{{#temps}}\n"
+ " {{kind|sensor}}{{#label}} {{label}}{{/label}}: {{c}} °C{{#hot}}, near "
+ "its limit of {{high}} °C{{/hot}}\n"
+ "{{/temps}}\n"
+ "---\n"
+ "bat.charging = charging\n"
+ "bat.discharging = on battery\n"
+ "bat.full = full\n"
+ "bat.idle = plugged in, not charging\n"
+ "bat.unknown = state not told\n"
+ "sensor.cpu = processor\n"
+ "sensor.core = hottest core\n"
+ "sensor.disk = disk\n"
+ "sensor.memory = memory\n"
+ "sensor.wifi = Wi-Fi card\n"
+ "sensor.board = motherboard\n"
+ "sensor.gpu = graphics card\n"
+ "sensor.battery = battery\n"
+ "sensor.chipset = chipset\n"
+ "sensor.other = other sensor\n";
+
+const char SY_STATUS_BRIEF[] =
+ "{{host}} ({{os}}), on {{up.d}} d {{up.h}} h. CPU {{cpu_pct}}% (kernel "
+ "{{sys_pct}}%) of "
+ "{{cpus}} threads{{#has_load}}, load {{load1}}/{{load5}}/"
+ "{{load15}}{{/has_load}}. Memory {{mem.pct}}% used, {{mem.avail.v}} "
+ "{{mem.avail.u}} free{{#swap.has}}, swap {{swap.pct}}%{{/swap.has}}."
+ "{{#psi.high}} Waiting: CPU {{psi.cpu}}%, memory {{psi.mem}}%, disks "
+ "{{psi.io}}%.{{/psi.high}} Disks: {{#disks}}{{mount}} {{pct}}% "
+ "({{avail.v}} {{avail.u}} free{{#full}}, NEARLY FULL{{/full}}); "
+ "{{/disks}}{{#bat.present}}battery {{bat.pct}}% {{bat.state}}{{#bat.worn}}"
+ ", worn ({{bat.health}}%){{/bat.worn}}; {{/bat.present}}{{#temps}}"
+ "{{kind}} {{c}} C{{#hot}} NEAR ITS LIMIT{{/hot}}; {{/temps}}Shown to the "
+ "user: do not repeat it; answer in a line or two, in the user's "
+ "language, telling only what is wrong (a disk nearly full, memory "
+ "short, a temperature near its limit, a worn battery), or that all is "
+ "well.";
+
+const char SY_DISKS_LAYOUT[] =
+ "Disks{{#more}} (the first {{n}}){{/more}}:\n"
+ "{{#disks}}\n"
+ " {{mount}} ({{dev}}, {{fs}}{{#ro}}, read only{{/ro}}): " SIZE_USED
+ " used of " SIZE_TOTAL " ({{pct}}%), " SIZE_AVAIL
+ " free{{#full}} - nearly full{{/full}}\n"
+ "{{/disks}}\n";
+
+const char SY_DISKS_BRIEF[] =
+ "Disks: {{#disks}}{{mount}} " SIZE_USED " of " SIZE_TOTAL
+ " ({{pct}}%{{#full}}, NEARLY FULL{{/full}}); {{/disks}}" SHOWN;
+
+const char SY_USAGE_LAYOUT[] =
+ "{{path}}: {{total.v}} {{total.u}} in {{files}} files{{#cut}}, at "
+ "least: the time ran out after {{secs}} s{{/cut}}; the disk has "
+ "{{fs_avail.v}} {{fs_avail.u}} free of {{fs_total.v}} "
+ "{{fs_total.u}}.\n"
+ "{{#items}}\n"
+ " {{size.v}} {{size.u}} ({{pct}}%) {{entry}}{{#dir}}/, {{files}} "
+ "files{{/dir}}\n"
+ "{{/items}}\n"
+ "{{#more}}\n"
+ " ... and {{more}} more entries.\n"
+ "{{/more}}\n"
+ "{{#unread}}\n"
+ "Directories that could not be read, left out: {{unread}}.\n"
+ "{{/unread}}\n";
+
+const char SY_USAGE_BRIEF[] =
+ "{{path}}: {{total.v}} {{total.u}}{{#cut}} at least (time ran "
+ "out){{/cut}}, disk free {{fs_avail.v}} {{fs_avail.u}}. Biggest: "
+ "{{#items}}{{entry}}{{#dir}}/{{/dir}} {{size.v}} {{size.u}}; "
+ "{{/items}}" SHOWN;
+
+const char SY_PROCS_LAYOUT[] =
+ "{{#name}}Processes with \"{{name}}\" in their name: {{matched}} of "
+ "{{total}}{{/name}}{{^name}}The processes using the most "
+ "{{by|by}}, of {{total}}{{/name}}:\n"
+ "{{#items}}\n"
+ " {{pname}} (pid {{pid}}, {{user}}): processor {{cpu}}%, memory "
+ "{{mem.v}} {{mem.u}} ({{mem_pct}}%), running for "
+ "{{#age.d}}{{age.d}} d {{/age.d}}{{age.h}} h {{age.m}} min\n"
+ "{{/items}}\n"
+ "{{^n}}\n"
+ " none.\n"
+ "{{/n}}\n"
+ "{{#more}}\n"
+ " ... and {{more}} more.\n"
+ "{{/more}}\n"
+ "---\n"
+ "by.cpu = processor\n"
+ "by.memory = memory\n";
+
+const char SY_PROCS_BRIEF[] =
+ "{{#name}}Processes named like {{name}}: {{matched}}.{{/name}}"
+ "{{^name}}Top by {{by}} of {{total}}:{{/name}} {{#items}}{{pname}} "
+ "(pid {{pid}}) CPU {{cpu}}% mem {{mem.v}} {{mem.u}}; {{/items}}"
+ "CPU % is of the whole processor." SHOWN;
+
+const char SY_ERRORS_LAYOUT[] =
+ "{{#boot}}Errors since the computer started{{/boot}}{{^boot}}Errors in "
+ "the last {{hours}} hours{{/boot}}: {{#cut}}at least {{/cut}}{{total}}"
+ "{{#more}}, the latest "
+ "{{n}} kinds shown{{/more}}.\n"
+ "{{#user_only}}\n"
+ "Only those of your own programs and session: the system's need the "
+ "group adm or systemd-journal.\n"
+ "{{/user_only}}\n"
+ "{{#items}}\n"
+ " " WHEN " {{who}}{{#again}} ({{count}} times){{/again}}: {{text}}\n"
+ "{{/items}}\n"
+ "{{#n_failed}}\n"
+ "Services that failed:\n"
+ "{{/n_failed}}\n"
+ "{{#failed}}\n"
+ " {{unit}}{{#again}} ({{count}} times){{/again}}\n"
+ "{{/failed}}\n"
+ "{{^n_failed}}\n"
+ "No service has failed.\n"
+ "{{/n_failed}}\n";
+
+const char SY_ERRORS_BRIEF[] =
+ "{{#boot}}Since boot{{/boot}}{{^boot}}Last {{hours}} h{{/boot}}: "
+ "{{total}} errors{{#user_only}} (user's only){{/user_only}}. "
+ "{{#items}}{{who}} x{{count}}: {{text}}; {{/items}}Failed services: "
+ "{{n_failed}}{{#failed}} {{unit}};{{/failed}} Shown to the user: do not "
+ "repeat the list; answer in a line or two, in the user's language, "
+ "saying which matter, if any.";
+
+const char SY_UPDATES_LAYOUT[] =
+ "{{#total}}Updates available: {{total}}{{#security}}, {{security}} of "
+ "them for security{{/security}}{{#more}} (the first {{n}} "
+ "listed){{/more}}{{/total}}{{^total}}No update available{{/total}}, "
+ "by {{tool}}'s list{{#checked.has}} as of "
+ "{{checked.day}}/"
+ "{{checked.mon}} {{checked.at}}{{#checked.ago_d}}, {{checked.ago_d}} "
+ "days ago{{/checked.ago_d}}{{/checked.has}}.\n"
+ "{{#items}}\n"
+ " {{pkg}} {{#from}}{{from}} -> {{/from}}{{to}}{{#sec}} "
+ "(security){{/sec}}\n"
+ "{{/items}}\n"
+ "{{#refresh}}\n"
+ "The list is the one last fetched; it is fetched again with: "
+ "{{refresh}}\n"
+ "{{/refresh}}\n";
+
+const char SY_UPDATES_BRIEF[] =
+ "{{tool}}: {{total}} updates, {{security}} for security; list as of "
+ "{{checked.day}}/{{checked.mon}}, {{checked.ago_d}} days ago. "
+ "{{#items}}{{pkg}}{{#sec}} (security){{/sec}}; {{/items}}" SHOWN;
+
+const char SY_NET_LAYOUT[] =
+ "{{#items}}\n"
+ "{{name}} ({{kind|iface}}, {{state|link}}){{#gw}}, the way out to the "
+ "internet{{/gw}}:{{#addrs}} {{.}}{{/addrs}}{{^addrs}} no "
+ "address{{/addrs}}\n"
+ "{{#speed}}\n"
+ " speed: {{speed}} Mb/s\n"
+ "{{/speed}}\n"
+ "{{#signal}}\n"
+ " signal: {{signal}} dBm ({{wifi_pct}}%)\n"
+ "{{/signal}}\n"
+ " received {{rx.v}} {{rx.u}}, sent {{tx.v}} {{tx.u}}\n"
+ "{{/items}}\n"
+ "{{#gateway}}Gateway: {{gateway}}{{/gateway}}{{^gateway}}No gateway: "
+ "no way out to the internet{{/gateway}}{{#n_dns}}; name "
+ "servers:{{/n_dns}}{{#dns}} {{.}}{{/dns}}.\n"
+ "---\n"
+ "iface.wifi = Wi-Fi\n"
+ "iface.ethernet = cable\n"
+ "iface.virtual = virtual\n"
+ "link.up = connected\n"
+ "link.down = not connected\n"
+ "link.dormant = waiting\n"
+ "link.lowerlayerdown = not connected\n"
+ "link.unknown = state not told\n";
+
+const char SY_NET_BRIEF[] =
+ "{{#items}}{{name}} {{kind}} {{state}}{{#gw}} (default "
+ "route){{/gw}}{{#addrs}} {{.}}{{/addrs}}{{#signal}}, signal "
+ "{{signal}} dBm{{/signal}}; {{/items}}gateway {{gateway}}." SHOWN;
diff --git a/src/services/system/linux.c b/src/services/system/linux.c
new file mode 100644
index 0000000..547cd50
--- /dev/null
+++ b/src/services/system/linux.c
@@ -0,0 +1,700 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * linux.c - janas-system's backend for Linux (see system.h): /proc and /sys
+ * read as files, journalctl and systemctl for the errors, the package
+ * manager (apt, dnf, pacman) for the updates, each from what it already
+ * knows: nothing is fetched, nothing needs root.
+ */
+#ifdef __linux__
+#define _GNU_SOURCE
+#include <dirent.h>
+#include <errno.h>
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <pwd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/statvfs.h>
+#include <sys/utsname.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "common/sysinfo.h"
+#include "services/common/run.h"
+#include "system.h"
+
+/* a small file of /proc or /sys whole into buf; its length, or -1 */
+static long slurp(const char *path, char *buf, size_t cap)
+{
+ FILE *f = fopen(path, "r");
+ if (!f)
+ return -1;
+ size_t n = fread(buf, 1, cap - 1, f);
+ fclose(f);
+ buf[n] = 0;
+ return (long)n;
+}
+
+static long long num_file(const char *path, long long def)
+{
+ char b[64];
+ return slurp(path, b, sizeof b) > 0 ? atoll(b) : def;
+}
+
+static void str_file(const char *path, char *out, size_t cap)
+{
+ out[0] = 0;
+ if (slurp(path, out, cap) > 0)
+ out[strcspn(out, "\n")] = 0;
+}
+
+/* a large file of /proc (mountinfo, many lines) into b */
+static int slurp_buf(const char *path, struct janas_buf *b)
+{
+ FILE *f = fopen(path, "r");
+ if (!f)
+ return -1;
+ char chunk[8192];
+ size_t n;
+ while ((n = fread(chunk, 1, sizeof chunk, f)) > 0)
+ janas_buf_put(b, chunk, n);
+ fclose(f);
+ janas_buf_put(b, "", 1);
+ return b->oom ? -1 : 0;
+}
+
+const char *sy_home(void)
+{
+ const char *h = getenv("HOME");
+ if (h && *h)
+ return h;
+ struct passwd *pw = getpwuid(getuid());
+ return pw && pw->pw_dir ? pw->pw_dir : "";
+}
+
+static void sleep_ms(int ms)
+{
+ struct timespec t = {.tv_sec = ms / 1000,
+ .tv_nsec = (long)(ms % 1000) * 1000000L};
+ while (nanosleep(&t, &t) != 0 && errno == EINTR)
+ ;
+}
+
+int sy_get_disks(struct sy_disks *d, char *err, size_t err_len)
+{
+ struct janas_buf b = {0};
+ if (slurp_buf("/proc/self/mountinfo", &b) != 0) {
+ janas_buf_free(&b);
+ snprintf(err, err_len, "/proc/self/mountinfo could not be read");
+ return -1;
+ }
+ sy_read_mountinfo(b.p, d);
+ janas_buf_free(&b);
+ for (int i = 0; i < d->n; i++) {
+ struct statvfs v;
+ if (statvfs(d->d[i].mount, &v) == 0) {
+ d->d[i].total = (uint64_t)v.f_blocks * v.f_frsize;
+ d->d[i].avail = (uint64_t)v.f_bavail * v.f_frsize;
+ }
+ }
+ /* the empty ones (a filesystem unreadable) left out */
+ int k = 0;
+ for (int i = 0; i < d->n; i++)
+ if (d->d[i].total)
+ d->d[k++] = d->d[i];
+ d->n = k;
+ return 0;
+}
+
+static void battery(struct sy_battery *b)
+{
+ memset(b, 0, sizeof *b);
+ b->pct = b->minutes = b->health = -1;
+ b->mains = janas_on_mains();
+ snprintf(b->state, sizeof b->state, "unknown");
+ DIR *dir = opendir("/sys/class/power_supply");
+ if (!dir)
+ return;
+ struct dirent *e;
+ char p[512], v[64];
+ while ((e = readdir(dir))) {
+ snprintf(p, sizeof p, "/sys/class/power_supply/%s/type", e->d_name);
+ str_file(p, v, sizeof v);
+ snprintf(p, sizeof p, "/sys/class/power_supply/%s/scope", e->d_name);
+ char scope[32];
+ str_file(p, scope, sizeof scope);
+ if (strcmp(v, "Battery") || !strcmp(scope, "Device"))
+ continue; /* a mouse's battery is not the computer's */
+ char base[400];
+ snprintf(base, sizeof base, "/sys/class/power_supply/%s", e->d_name);
+ b->present = 1;
+ snprintf(p, sizeof p, "%s/capacity", base);
+ b->pct = (int)num_file(p, -1);
+ snprintf(p, sizeof p, "%s/status", base);
+ str_file(p, v, sizeof v);
+ snprintf(b->state, sizeof b->state, "%s",
+ !strcmp(v, "Charging") ? "charging"
+ : !strcmp(v, "Discharging") ? "discharging"
+ : !strcmp(v, "Full") ? "full"
+ : !strcmp(v, "Not charging") ? "idle"
+ : "unknown");
+ /* energy (µWh, µW) or charge (µAh, µA) */
+ long long now, full, design, rate;
+ snprintf(p, sizeof p, "%s/energy_now", base);
+ now = num_file(p, -1);
+ const char *u = now >= 0 ? "energy" : "charge";
+ if (now < 0) {
+ snprintf(p, sizeof p, "%s/charge_now", base);
+ now = num_file(p, -1);
+ }
+ snprintf(p, sizeof p, "%s/%s_full", base, u);
+ full = num_file(p, -1);
+ snprintf(p, sizeof p, "%s/%s_full_design", base, u);
+ design = num_file(p, -1);
+ snprintf(p, sizeof p, "%s/%s", base,
+ u[0] == 'e' ? "power_now" : "current_now");
+ rate = num_file(p, -1);
+ if (rate < 0)
+ rate = -rate; /* some drivers count a discharge below zero */
+ if (rate > 0 && now >= 0 && !strcmp(b->state, "discharging"))
+ b->minutes = (int)(now * 60 / rate);
+ else if (rate > 0 && full > now && !strcmp(b->state, "charging"))
+ b->minutes = (int)((full - now) * 60 / rate);
+ if (design > 0 && full > 0)
+ b->health = (int)(full * 100 / design);
+ break;
+ }
+ closedir(dir);
+}
+
+static int hotter(const void *a, const void *b)
+{
+ double x = ((const struct sy_temp *)a)->c,
+ y = ((const struct sy_temp *)b)->c;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+/* a sensor a device: the processor's package and its hottest core, a
+ disk's composite, the others' first */
+static void temperatures(struct sy_status *s)
+{
+ DIR *dir = opendir("/sys/class/hwmon");
+ if (!dir)
+ return;
+ struct dirent *e;
+ int disks = 0;
+ while ((e = readdir(dir)) && s->n_temps < SY_TEMPS - 1) {
+ if (e->d_name[0] == '.')
+ continue;
+ char base[300], p[400], name[64];
+ snprintf(base, sizeof base, "/sys/class/hwmon/%s", e->d_name);
+ snprintf(p, sizeof p, "%s/name", base);
+ str_file(p, name, sizeof name);
+ const char *kind = sy_sensor_kind(name);
+ /* the package, the composite or Tctl over the others; the first
+ of those */
+ double first = -300, first_high = 0, core = -300, core_high = 0;
+ int rank = 0;
+ for (int i = 1; i <= 64; i++) {
+ snprintf(p, sizeof p, "%s/temp%d_input", base, i);
+ long long mc = num_file(p, -1000000);
+ if (mc == -1000000)
+ continue;
+ char label[64];
+ snprintf(p, sizeof p, "%s/temp%d_label", base, i);
+ str_file(p, label, sizeof label);
+ /* the critical limit, else the maximum (spd5118's maximum is a
+ warning set low) */
+ snprintf(p, sizeof p, "%s/temp%d_crit", base, i);
+ long long hi = num_file(p, 0);
+ if (hi <= 0 || hi > 200000) {
+ snprintf(p, sizeof p, "%s/temp%d_max", base, i);
+ hi = num_file(p, 0);
+ }
+ if (hi > 200000) /* no limit, written as a huge one */
+ hi = 0;
+ double c = (double)mc / 1000;
+ if (!strncmp(label, "Core", 4)) {
+ if (c > core)
+ core = c, core_high = (double)hi / 1000;
+ continue;
+ }
+ int r = !strncmp(label, "Package", 7) ||
+ !strcmp(label, "Composite") ||
+ !strcmp(label, "Tctl")
+ ? 2
+ : 1;
+ if (r > rank)
+ rank = r, first = c, first_high = (double)hi / 1000;
+ }
+ if (first > -300) {
+ struct sy_temp *t = &s->t[s->n_temps++];
+ sy_put(t->kind, sizeof t->kind, kind);
+ if (!strcmp(kind, "disk") && disks++)
+ snprintf(t->label, sizeof t->label, "%d", disks);
+ t->c = first;
+ t->high = first_high;
+ }
+ if (core > -300 && s->n_temps < SY_TEMPS) {
+ struct sy_temp *t = &s->t[s->n_temps++];
+ snprintf(t->kind, sizeof t->kind, "core");
+ t->c = core;
+ t->high = core_high;
+ }
+ }
+ closedir(dir);
+ qsort(s->t, (size_t)s->n_temps, sizeof *s->t, hotter);
+}
+
+static int cpu_ticks(uint64_t *busy, uint64_t *all, uint64_t *sys)
+{
+ char b[512];
+ uint64_t s;
+ return slurp("/proc/stat", b, sizeof b) > 0
+ ? sy_read_cpu_ticks(b, busy, all, sys ? sys : &s)
+ : -1;
+}
+
+static double uptime(void)
+{
+ char b[128];
+ return slurp("/proc/uptime", b, sizeof b) > 0 ? atof(b) : 0;
+}
+
+int sy_get_status(struct sy_status *s, char *err, size_t err_len)
+{
+ memset(s, 0, sizeof *s);
+ snprintf(s->platform, sizeof s->platform, "linux");
+ uint64_t b0 = 0, a0 = 0, s0 = 0, b1 = 0, a1 = 0, s1 = 0;
+ int ticks = cpu_ticks(&b0, &a0, &s0);
+ char buf[4096];
+ if (slurp("/proc/meminfo", buf, sizeof buf) < 0 ||
+ sy_read_meminfo(buf, s) != 0) {
+ snprintf(err, err_len, "/proc/meminfo could not be read");
+ return -1;
+ }
+ gethostname(s->host, sizeof s->host - 1);
+ struct utsname u;
+ if (uname(&u) == 0)
+ sy_put(s->kernel, sizeof s->kernel, u.release);
+ if (slurp("/etc/os-release", buf, sizeof buf) > 0 ||
+ slurp("/usr/lib/os-release", buf, sizeof buf) > 0)
+ sy_read_os_release(buf, s->os, sizeof s->os);
+ janas_cpu_name(s->cpu, sizeof s->cpu);
+ s->cpus = (int)sysconf(_SC_NPROCESSORS_ONLN);
+ if (slurp("/proc/uptime", buf, sizeof buf) > 0)
+ s->uptime_s = atol(buf);
+ s->has_load = slurp("/proc/loadavg", buf, sizeof buf) > 0 &&
+ sy_read_loadavg(buf, s->load) == 0;
+ s->psi_cpu = slurp("/proc/pressure/cpu", buf, sizeof buf) > 0
+ ? sy_read_psi(buf)
+ : -1;
+ s->psi_mem = slurp("/proc/pressure/memory", buf, sizeof buf) > 0
+ ? sy_read_psi(buf)
+ : -1;
+ s->psi_io =
+ slurp("/proc/pressure/io", buf, sizeof buf) > 0 ? sy_read_psi(buf) : -1;
+ char e2[100];
+ sy_get_disks(&s->disks, e2, sizeof e2);
+ battery(&s->bat);
+ temperatures(s);
+ /* the processor over the time all that took, and a little more */
+ sleep_ms(SY_SAMPLE_MS);
+ s->cpu_pct = -1;
+ if (ticks == 0 && cpu_ticks(&b1, &a1, &s1) == 0 && a1 > a0) {
+ s->cpu_pct = (double)(b1 - b0) * 100 / (double)(a1 - a0);
+ s->sys_pct = (double)(s1 - s0) * 100 / (double)(a1 - a0);
+ }
+ return 0;
+}
+
+/* ---- the processes ---- */
+
+struct tick {
+ int pid;
+ uint64_t t;
+};
+
+static int by_pid(const void *a, const void *b)
+{
+ return ((const struct tick *)a)->pid - ((const struct tick *)b)->pid;
+}
+
+static int is_pid(const char *s)
+{
+ if (!*s)
+ return 0;
+ for (; *s; s++)
+ if (*s < '0' || *s > '9')
+ return 0;
+ return 1;
+}
+
+/* every process's ticks, sorted by pid; their count, or -1 */
+static int all_ticks(struct tick **out)
+{
+ DIR *d = opendir("/proc");
+ if (!d)
+ return -1;
+ int n = 0, cap = 512;
+ struct tick *v = malloc((size_t)cap * sizeof *v);
+ struct dirent *e;
+ while (v && (e = readdir(d))) {
+ if (!is_pid(e->d_name))
+ continue;
+ char p[300], b[1024], name[64];
+ snprintf(p, sizeof p, "/proc/%s/stat", e->d_name);
+ uint64_t t, start;
+ int th;
+ if (slurp(p, b, sizeof b) <= 0 ||
+ sy_read_pid_stat(b, name, sizeof name, &t, &th, &start) != 0)
+ continue;
+ if (n == cap) {
+ struct tick *w = realloc(v, (size_t)(cap *= 2) * sizeof *v);
+ if (!w)
+ break;
+ v = w;
+ }
+ v[n].pid = atoi(e->d_name);
+ v[n++].t = t;
+ }
+ closedir(d);
+ if (!v)
+ return -1;
+ qsort(v, (size_t)n, sizeof *v, by_pid);
+ *out = v;
+ return n;
+}
+
+static int ci_has(const char *s, const char *what)
+{
+ size_t n = strlen(what);
+ for (; *s; s++)
+ if (!strncasecmp(s, what, n))
+ return 1;
+ return 0;
+}
+
+static int more_cpu(const void *a, const void *b)
+{
+ double x = ((const struct sy_proc *)a)->cpu_pct,
+ y = ((const struct sy_proc *)b)->cpu_pct;
+ uint64_t m = ((const struct sy_proc *)a)->mem,
+ k = ((const struct sy_proc *)b)->mem;
+ return x < y ? 1 : x > y ? -1 : m < k ? 1 : m > k ? -1 : 0;
+}
+
+static int more_mem(const void *a, const void *b)
+{
+ uint64_t x = ((const struct sy_proc *)a)->mem,
+ y = ((const struct sy_proc *)b)->mem;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+int sy_get_procs(const char *by, const char *name, struct sy_procs *p,
+ char *err, size_t err_len)
+{
+ memset(p, 0, sizeof *p);
+ sy_put(p->by, sizeof p->by, by);
+ sy_put(p->name, sizeof p->name, name ? name : "");
+ p->mem_total = janas_mem_total();
+ struct tick *before = NULL;
+ uint64_t b0 = 0, a0 = 0, b1, a1;
+ cpu_ticks(&b0, &a0, NULL);
+ double up0 = uptime();
+ int n0 = all_ticks(&before);
+ if (n0 < 0) {
+ snprintf(err, err_len, "/proc could not be read");
+ return -1;
+ }
+ sleep_ms(SY_SAMPLE_MS);
+ double all =
+ cpu_ticks(&b1, &a1, NULL) == 0 && a1 > a0 ? (double)(a1 - a0) : 0;
+ long hz = sysconf(_SC_CLK_TCK), page = sysconf(_SC_PAGESIZE);
+ double up = 0;
+ char buf[1024];
+ if (slurp("/proc/uptime", buf, sizeof buf) > 0)
+ up = atof(buf);
+ /* the whole list kept to sort, the first SY_PROCS shown */
+ int cap = 1024, n = 0;
+ struct sy_proc *v = malloc((size_t)cap * sizeof *v);
+ DIR *d = opendir("/proc");
+ struct dirent *e;
+ while (v && d && (e = readdir(d))) {
+ if (!is_pid(e->d_name))
+ continue;
+ char path[300], pname[64];
+ snprintf(path, sizeof path, "/proc/%s/stat", e->d_name);
+ uint64_t t, start;
+ int th;
+ if (slurp(path, buf, sizeof buf) <= 0 ||
+ sy_read_pid_stat(buf, pname, sizeof pname, &t, &th, &start) != 0)
+ continue;
+ if (th == 0) /* a zombie */
+ continue;
+ p->total++;
+ if (name && *name && !ci_has(pname, name))
+ continue;
+ p->matched++;
+ if (n == cap) {
+ struct sy_proc *w = realloc(v, (size_t)(cap *= 2) * sizeof *v);
+ if (!w)
+ break;
+ v = w;
+ }
+ struct sy_proc *x = &v[n++];
+ memset(x, 0, sizeof *x);
+ x->pid = atoi(e->d_name);
+ x->threads = th;
+ sy_put(x->name, sizeof x->name, pname);
+ struct tick k = {.pid = x->pid}, *was = bsearch(&k, before, (size_t)n0,
+ sizeof *before, by_pid);
+ /* /proc/stat counts every CPU's ticks: the share of the whole */
+ if (was && all > 0 && t >= was->t)
+ x->cpu_pct = (double)(t - was->t) * 100 / all;
+ else if (!was && all > 0 && hz > 0 &&
+ (double)start / (double)hz >= up0 - 0.01)
+ x->cpu_pct = (double)t * 100 / all; /* born while measured */
+ snprintf(path, sizeof path, "/proc/%s/statm", e->d_name);
+ char sm[128];
+ if (slurp(path, sm, sizeof sm) > 0) {
+ unsigned long long size, res;
+ if (sscanf(sm, "%llu %llu", &size, &res) == 2)
+ x->mem = res * (uint64_t)page;
+ }
+ x->age_s = hz > 0 ? (long)(up - (double)start / (double)hz) : 0;
+ struct stat st;
+ snprintf(path, sizeof path, "/proc/%s", e->d_name);
+ if (stat(path, &st) == 0) {
+ struct passwd *pw = getpwuid(st.st_uid);
+ if (pw)
+ sy_put(x->user, sizeof x->user, pw->pw_name);
+ else
+ snprintf(x->user, sizeof x->user, "%u", (unsigned)st.st_uid);
+ }
+ }
+ if (d)
+ closedir(d);
+ free(before);
+ if (!v) {
+ snprintf(err, err_len, "out of memory");
+ return -1;
+ }
+ qsort(v, (size_t)n, sizeof *v, strcmp(by, "memory") ? more_cpu : more_mem);
+ p->n = n < SY_PROCS ? n : SY_PROCS;
+ memcpy(p->p, v, (size_t)p->n * sizeof *v);
+ free(v);
+ return 0;
+}
+
+/* ---- the errors ---- */
+
+int sy_get_errors(int hours, struct sy_errors *e, char *err, size_t err_len)
+{
+ memset(e, 0, sizeof *e);
+ e->hours = hours;
+ snprintf(e->how, sizeof e->how, "journal");
+ static const char *const env[] = {"LC_ALL=C", "SYSTEMD_COLORS=0",
+ "SYSTEMD_PAGER=", NULL};
+ char since[48], why[300];
+ if (hours > 0)
+ snprintf(since, sizeof since, "--since=-%dh", hours);
+ else
+ snprintf(since, sizeof since, "--boot");
+ const char *av[] = {"journalctl",
+ "--priority=0..3",
+ since,
+ "--no-pager",
+ "--output=json",
+ "--reverse", /* the latest first: a cut drops the
+ oldest */
+ "--output-fields=MESSAGE,SYSLOG_IDENTIFIER,"
+ "_SYSTEMD_UNIT,_SYSTEMD_USER_UNIT",
+ "--lines=2000",
+ NULL};
+ struct janas_buf out = {0}, er = {0};
+ int rc = janas_run(NULL, av, env, SY_RUN_MS, &out, &er, why, sizeof why);
+ if (rc < 0) {
+ janas_buf_free(&out);
+ janas_buf_free(&er);
+ snprintf(err, err_len, "the journal could not be read: %s", why);
+ return -1;
+ }
+ sy_read_journal(out.p ? out.p : "", out.n, e);
+ e->cut = out.n >= JANAS_RUN_OUT_MAX || e->total >= 2000;
+ /* without the groups adm or systemd-journal, only the user's own */
+ e->user_only = er.p && strstr(er.p, "not seeing messages") != NULL;
+ janas_buf_free(&out);
+ janas_buf_free(&er);
+ sy_err_order(e);
+ for (int user = 0; user < 2; user++) {
+ const char *sv[] = {"systemctl", user ? "--user" : "--system",
+ "--failed", "--plain",
+ "--no-legend", "--no-pager",
+ NULL};
+ struct janas_buf o = {0}, x = {0};
+ if (janas_run(NULL, sv, env, SY_RUN_MS, &o, &x, why, sizeof why) >= 0)
+ sy_read_failed(o.p ? o.p : "", e);
+ janas_buf_free(&o);
+ janas_buf_free(&x);
+ }
+ return 0;
+}
+
+/* ---- the updates ---- */
+
+static int has_program(const char *name)
+{
+ const char *path = getenv("PATH");
+ char dir[4096];
+ snprintf(dir, sizeof dir, "%s",
+ path && *path ? path : "/usr/local/bin:/usr/bin:/bin");
+ for (char *s = strtok(dir, ":"); s; s = strtok(NULL, ":")) {
+ char p[4200];
+ snprintf(p, sizeof p, "%s/%s", s, name);
+ if (access(p, X_OK) == 0)
+ return 1;
+ }
+ return 0;
+}
+
+static long long mtime(const char *path)
+{
+ struct stat st;
+ return stat(path, &st) == 0 ? (long long)st.st_mtime : 0;
+}
+
+int sy_get_updates(struct sy_updates *u, char *err, size_t err_len)
+{
+ memset(u, 0, sizeof *u);
+ static const char *const env[] = {"LC_ALL=C", NULL};
+ char why[300];
+ struct janas_buf out = {0}, er = {0};
+ int rc;
+ if (has_program("apt")) {
+ const char *av[] = {"apt", "list", "--upgradable", NULL};
+ rc = janas_run(NULL, av, env, SY_RUN_MS, &out, &er, why, sizeof why);
+ if (rc >= 0)
+ sy_read_apt(out.p ? out.p : "", u);
+ u->checked = mtime("/var/cache/apt/pkgcache.bin");
+ } else if (has_program("dnf")) {
+ /* from the metadata it has: --cacheonly fetches nothing */
+ const char *av[] = {"dnf", "check-update", "--cacheonly", "--quiet",
+ NULL};
+ rc = janas_run(NULL, av, env, SY_RUN_MS, &out, &er, why, sizeof why);
+ if (rc == 0 || rc == 100) {
+ sy_read_dnf(out.p ? out.p : "", u);
+ rc = 0;
+ }
+ snprintf(u->tool, sizeof u->tool, "dnf");
+ } else if (has_program("pacman")) {
+ /* against the database as last synchronised */
+ const char *av[] = {"pacman", "-Qu", NULL};
+ rc = janas_run(NULL, av, env, SY_RUN_MS, &out, &er, why, sizeof why);
+ if (rc == 0 || rc == 1) { /* 1: nothing to update */
+ sy_read_pacman(out.p ? out.p : "", u);
+ rc = 0;
+ }
+ snprintf(u->tool, sizeof u->tool, "pacman");
+ u->checked = mtime("/var/lib/pacman/sync");
+ } else {
+ snprintf(err, err_len,
+ "no package manager known here (apt, dnf, pacman)");
+ return -1;
+ }
+ janas_buf_free(&out);
+ janas_buf_free(&er);
+ if (rc < 0) {
+ snprintf(err, err_len, "%s", why);
+ return -1;
+ }
+ return 0;
+}
+
+/* ---- the network ---- */
+
+int sy_get_net(struct sy_net *n, char *err, size_t err_len)
+{
+ memset(n, 0, sizeof *n);
+ struct ifaddrs *ifs;
+ if (getifaddrs(&ifs) != 0) {
+ snprintf(err, err_len, "the interfaces could not be read: %s",
+ strerror(errno));
+ return -1;
+ }
+ char wireless[2048] = "";
+ slurp("/proc/net/wireless", wireless, sizeof wireless);
+ for (struct ifaddrs *a = ifs; a; a = a->ifa_next) {
+ if (a->ifa_flags & IFF_LOOPBACK)
+ continue;
+ int i = 0;
+ while (i < n->n && strcmp(n->i[i].name, a->ifa_name))
+ i++;
+ if (i == n->n) {
+ if (n->n == SY_IFACES) {
+ n->more++;
+ continue;
+ }
+ struct sy_iface *x = &n->i[n->n++];
+ sy_put(x->name, sizeof x->name, a->ifa_name);
+ char p[300], v[32];
+ snprintf(p, sizeof p, "/sys/class/net/%s/wireless", x->name);
+ struct stat st;
+ int wifi = stat(p, &st) == 0;
+ snprintf(p, sizeof p, "/sys/class/net/%s/device", x->name);
+ int dev = stat(p, &st) == 0;
+ snprintf(x->kind, sizeof x->kind, "%s",
+ wifi ? "wifi"
+ : dev ? "ethernet"
+ : "virtual");
+ snprintf(p, sizeof p, "/sys/class/net/%s/operstate", x->name);
+ str_file(p, v, sizeof v);
+ sy_put(x->state, sizeof x->state, v[0] ? v : "unknown");
+ snprintf(p, sizeof p, "/sys/class/net/%s/speed", x->name);
+ long long sp = num_file(p, 0);
+ x->speed_mbps = sp > 0 ? (long)sp : 0;
+ snprintf(p, sizeof p, "/sys/class/net/%s/statistics/rx_bytes",
+ x->name);
+ x->rx = (uint64_t)num_file(p, 0);
+ snprintf(p, sizeof p, "/sys/class/net/%s/statistics/tx_bytes",
+ x->name);
+ x->tx = (uint64_t)num_file(p, 0);
+ if (wifi)
+ sy_read_wireless(wireless, x->name, &x->signal_dbm,
+ &x->wifi_pct);
+ }
+ struct sy_iface *x = &n->i[i];
+ if (!a->ifa_addr || x->n_addr == SY_ADDRS)
+ continue;
+ int fam = a->ifa_addr->sa_family;
+ if (fam != AF_INET && fam != AF_INET6)
+ continue;
+ char host[64];
+ if (getnameinfo(a->ifa_addr,
+ fam == AF_INET ? sizeof(struct sockaddr_in)
+ : sizeof(struct sockaddr_in6),
+ host, sizeof host, NULL, 0, NI_NUMERICHOST) != 0)
+ continue;
+ sy_put(x->addr[x->n_addr++], sizeof x->addr[0], host);
+ }
+ freeifaddrs(ifs);
+ /* the virtual ones down and without addresses are noise */
+ int k = 0;
+ for (int i = 0; i < n->n; i++)
+ if (strcmp(n->i[i].kind, "virtual") || n->i[i].n_addr)
+ n->i[k++] = n->i[i];
+ n->n = k;
+ char buf[8192];
+ if (slurp("/proc/net/route", buf, sizeof buf) > 0)
+ sy_read_route(buf, n->gateway, sizeof n->gateway, n->gw_iface,
+ sizeof n->gw_iface);
+ if (slurp("/etc/resolv.conf", buf, sizeof buf) > 0)
+ sy_read_resolv(buf, n);
+ return 0;
+}
+#endif
diff --git a/src/services/system/main.c b/src/services/system/main.c
new file mode 100644
index 0000000..7e27aef
--- /dev/null
+++ b/src/services/system/main.c
@@ -0,0 +1,65 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * main.c - janas-system: this computer as an MCP server over stdio, for
+ * janas-chat (which starts it by itself) and any other MCP client. It
+ * only reads, and nothing it reads leaves the computer but in its answers:
+ * how the computer is, its disks and what fills a directory, its
+ * processes, its errors, its updates, its network.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "common/mcp_server.h"
+#include "system.h"
+
+#ifndef JANAS_VERSION
+#define JANAS_VERSION "unknown"
+#endif
+
+static const char INSTRUCTIONS[] =
+ "Use these tools by yourself when the user asks about this computer: "
+ "how it is or why it is slow, the disks and their space, what fills a "
+ "folder, which programs use the processor or the memory, whether a "
+ "program is running, the errors, the updates, the network; never name "
+ "them. They only read: to change something (stop a program, install "
+ "updates), tell the user how to do it.";
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "usage: janas-system\n"
+ "An MCP server over stdio: a client starts it and calls its\n"
+ "tools - system_status, system_disks (with a path, what fills\n"
+ "it), system_processes, system_errors, system_updates and\n"
+ "system_network. They only read; none reaches the network.\n"
+ "janas-chat starts it by itself when it is beside it.\n"
+ "Configured in a client as, for instance:\n"
+ " {\"mcpServers\": {\"system\": {\"command\": "
+ "\"janas-system\"}}}\n");
+}
+
+int main(int argc, char **argv)
+{
+ for (int i = 1; i < argc; i++) {
+ usage();
+ return strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0 ? 0
+ : 2;
+ }
+ struct janas_mcps srv = {.name = "janas-system",
+ .version = JANAS_VERSION,
+ .instructions = INSTRUCTIONS,
+ .tools_list = sy_tools_list,
+ .tools_call = sy_tools_call};
+ if (janas_mcps_open(&srv) != 0) {
+ fprintf(stderr, "janas-system: cannot set its output aside\n");
+ return 1;
+ }
+ fprintf(stderr,
+ "janas-system %s: ready, 6 tools (system_status, system_disks, "
+ "system_processes, system_errors, system_updates, "
+ "system_network)\n",
+ JANAS_VERSION);
+ janas_mcps_run(&srv);
+ return 0;
+}
diff --git a/src/services/system/read.c b/src/services/system/read.c
new file mode 100644
index 0000000..b716660
--- /dev/null
+++ b/src/services/system/read.c
@@ -0,0 +1,516 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * read.c - janas-system reads the texts of Linux (see system.h): /proc's
+ * files, journalctl's and systemctl's output, the package managers' lists.
+ * Plain C over text, nothing read from the system here: the tests give it
+ * texts kept from a machine.
+ */
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "system.h"
+
+void sy_put(char *out, size_t cap, const char *s)
+{
+ size_t n = strlen(s);
+ if (n >= cap)
+ n = cap - 1;
+ memcpy(out, s, n);
+ out[n] = 0;
+}
+
+/* the text after "key:" on its line, or NULL */
+static const char *after(const char *t, const char *key)
+{
+ size_t k = strlen(key);
+ for (const char *p = t; p && *p;) {
+ if (!strncmp(p, key, k))
+ return p + k;
+ p = strchr(p, '\n');
+ p = p ? p + 1 : NULL;
+ }
+ return NULL;
+}
+
+static uint64_t kib(const char *t, const char *key)
+{
+ const char *p = after(t, key);
+ return p ? strtoull(p, NULL, 10) * 1024 : 0;
+}
+
+/* a field of a line into out, at most cap - 1 bytes; the rest after it */
+static const char *word(const char *p, char *out, size_t cap)
+{
+ while (*p == ' ' || *p == '\t')
+ p++;
+ size_t n = 0;
+ while (*p && *p != ' ' && *p != '\t' && *p != '\n') {
+ if (n + 1 < cap)
+ out[n++] = *p;
+ p++;
+ }
+ out[n] = 0;
+ return p;
+}
+
+static void copy(char *out, size_t cap, const char *s, size_t n)
+{
+ if (n >= cap)
+ n = cap - 1;
+ memcpy(out, s, n);
+ out[n] = 0;
+}
+
+int sy_read_meminfo(const char *t, struct sy_status *s)
+{
+ s->mem_total = kib(t, "MemTotal:");
+ s->mem_avail = kib(t, "MemAvailable:");
+ s->swap_total = kib(t, "SwapTotal:");
+ s->swap_free = kib(t, "SwapFree:");
+ return s->mem_total ? 0 : -1;
+}
+
+int sy_read_cpu_ticks(const char *t, uint64_t *busy, uint64_t *all,
+ uint64_t *sys)
+{
+ if (strncmp(t, "cpu ", 4))
+ return -1;
+ /* user nice system idle iowait irq softirq steal (guest is in user) */
+ uint64_t v[8] = {0};
+ const char *p = t + 4;
+ for (int i = 0; i < 8; i++) {
+ char *e;
+ v[i] = strtoull(p, &e, 10);
+ if (e == p)
+ break;
+ p = e;
+ }
+ *all = 0;
+ for (int i = 0; i < 8; i++)
+ *all += v[i];
+ *busy = *all - v[3] - v[4];
+ *sys = v[2] + v[5] + v[6];
+ return 0;
+}
+
+int sy_read_loadavg(const char *t, double load[3])
+{
+ return sscanf(t, "%lf %lf %lf", &load[0], &load[1], &load[2]) == 3 ? 0 : -1;
+}
+
+double sy_read_psi(const char *t)
+{
+ const char *p = t ? strstr(t, "some avg10=") : NULL;
+ return p ? atof(p + 11) : -1;
+}
+
+int sy_read_pid_stat(const char *t, char *name, size_t cap, uint64_t *ticks,
+ int *threads, uint64_t *start)
+{
+ /* "pid (name) state ..."; the name may hold spaces and parentheses */
+ const char *a = strchr(t, '('), *z = strrchr(t, ')');
+ if (!a || !z || z < a)
+ return -1;
+ copy(name, cap, a + 1, (size_t)(z - a - 1));
+ /* after ")": state is field 3; utime 14, stime 15, threads 20, start
+ 22 */
+ const char *p = z + 1;
+ uint64_t f[23] = {0};
+ for (int i = 3; i <= 22 && *p; i++) {
+ while (*p == ' ')
+ p++;
+ if (i > 3)
+ f[i] = strtoull(p, NULL, 10);
+ while (*p && *p != ' ')
+ p++;
+ }
+ *ticks = f[14] + f[15];
+ *threads = (int)f[20];
+ *start = f[22];
+ return 0;
+}
+
+/* the filesystems that hold files on a disk or a share */
+static int real_fs(const char *fs)
+{
+ static const char *const ok[] = {
+ "ext2", "ext3", "ext4", "xfs", "btrfs", "vfat",
+ "exfat", "ntfs", "ntfs3", "f2fs", "zfs", "jfs",
+ "reiserfs", "hfsplus", "nfs", "nfs4", "cifs", "smb3",
+ "fuseblk", "bcachefs", "apfs", NULL};
+ for (int i = 0; ok[i]; i++)
+ if (!strcmp(fs, ok[i]))
+ return 1;
+ return 0;
+}
+
+/* mountinfo writes a space in a path as \040 */
+static void unescape(char *s)
+{
+ char *w = s;
+ for (char *r = s; *r; r++) {
+ if (r[0] == '\\' && r[1] >= '0' && r[1] <= '3' && isdigit(r[2]) &&
+ isdigit(r[3])) {
+ *w++ = (char)((r[1] - '0') * 64 + (r[2] - '0') * 8 + (r[3] - '0'));
+ r += 3;
+ } else
+ *w++ = *r;
+ }
+ *w = 0;
+}
+
+int sy_read_mountinfo(const char *t, struct sy_disks *d)
+{
+ memset(d, 0, sizeof *d);
+ for (const char *line = t; line && *line;) {
+ const char *end = strchr(line, '\n');
+ size_t len = end ? (size_t)(end - line) : strlen(line);
+ char l[2048];
+ copy(l, sizeof l, line, len);
+ line = end ? end + 1 : NULL;
+ /* id parent maj:min root mount options [optional...] - fs source
+ super-options */
+ char id[16], parent[16], dev_no[32], root[512], mount[512], opts[256];
+ const char *p = word(l, id, sizeof id);
+ p = word(p, parent, sizeof parent);
+ p = word(p, dev_no, sizeof dev_no);
+ p = word(p, root, sizeof root);
+ p = word(p, mount, sizeof mount);
+ p = word(p, opts, sizeof opts);
+ const char *dash = strstr(p, " - ");
+ if (!dash)
+ continue;
+ char fs[32], source[256];
+ p = word(dash + 3, fs, sizeof fs);
+ word(p, source, sizeof source);
+ if (!real_fs(fs))
+ continue;
+ unescape(mount);
+ unescape(source);
+ int seen = 0; /* a device mounted twice (btrfs subvolumes, binds) */
+ for (int i = 0; i < d->n; i++)
+ seen |= !strcmp(d->d[i].dev, source);
+ if (seen)
+ continue;
+ if (d->n == SY_DISKS) {
+ d->more++;
+ continue;
+ }
+ struct sy_disk *k = &d->d[d->n++];
+ sy_put(k->mount, sizeof k->mount, mount);
+ sy_put(k->dev, sizeof k->dev, source);
+ sy_put(k->fs, sizeof k->fs, fs);
+ k->ro = !strncmp(opts, "ro", 2) && (opts[2] == ',' || !opts[2]);
+ }
+ return 0;
+}
+
+/* the same text but for its numbers (a process's id, a time, a count) */
+static int same_but_numbers(const char *a, const char *b)
+{
+ while (*a && *b) {
+ if (isdigit((unsigned char)*a) && isdigit((unsigned char)*b)) {
+ while (isdigit((unsigned char)*a))
+ a++;
+ while (isdigit((unsigned char)*b))
+ b++;
+ } else if (*a++ != *b++)
+ return 0;
+ }
+ return !*a && !*b;
+}
+
+void sy_err_add(struct sy_errors *e, long long at, const char *who,
+ const char *text)
+{
+ e->total++;
+ /* its first line: the rest (a core dump's modules and stack) is for
+ the log's own reader */
+ char t[240];
+ while (*text == ' ' || *text == '\n')
+ text++;
+ size_t first = strcspn(text, "\n");
+ copy(t, sizeof t, text, first);
+ for (char *c = t; *c; c++)
+ if (*c == '\r' || *c == '\t')
+ *c = ' ';
+ for (int i = 0; i < e->n; i++)
+ if (!strcmp(e->e[i].who, who) && same_but_numbers(e->e[i].text, t)) {
+ e->e[i].count++;
+ if (at > e->e[i].at) { /* the latest's words */
+ e->e[i].at = at;
+ sy_put(e->e[i].text, sizeof e->e[i].text, t);
+ }
+ return;
+ }
+ if (e->n == SY_ERRS) { /* the oldest out, the newest in */
+ int old = 0;
+ for (int i = 1; i < e->n; i++)
+ if (e->e[i].at < e->e[old].at)
+ old = i;
+ if (e->e[old].at > at) {
+ e->more++;
+ return;
+ }
+ e->more += e->e[old].count;
+ e->e[old] = e->e[--e->n];
+ }
+ struct sy_err *x = &e->e[e->n++];
+ x->at = at;
+ x->count = 1;
+ sy_put(x->who, sizeof x->who, who);
+ sy_put(x->text, sizeof x->text, t);
+}
+
+static int later_first(const void *a, const void *b)
+{
+ long long x = ((const struct sy_err *)a)->at,
+ y = ((const struct sy_err *)b)->at;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+void sy_err_order(struct sy_errors *e)
+{
+ qsort(e->e, (size_t)e->n, sizeof *e->e, later_first);
+}
+
+int sy_read_journal(const char *t, size_t n, struct sy_errors *e)
+{
+ const char *end = t + n;
+ for (const char *line = t; line < end;) {
+ const char *nl = memchr(line, '\n', (size_t)(end - line));
+ size_t len = nl ? (size_t)(nl - line) : (size_t)(end - line);
+ char why[100];
+ struct janas_json_doc *d =
+ len ? janas_json_parse(line, len, why, sizeof why) : NULL;
+ line = nl ? nl + 1 : end;
+ if (!d)
+ continue;
+ const struct janas_json *r = janas_json_root(d);
+ const char *msg = janas_json_str(janas_json_get(r, "MESSAGE"));
+ const char *ts =
+ janas_json_str(janas_json_get(r, "__REALTIME_TIMESTAMP"));
+ /* who: the program, else its unit */
+ const char *who =
+ janas_json_str(janas_json_get(r, "SYSLOG_IDENTIFIER"));
+ if (!who || !*who)
+ who = janas_json_str(janas_json_get(r, "_SYSTEMD_USER_UNIT"));
+ if (!who || !*who)
+ who = janas_json_str(janas_json_get(r, "_SYSTEMD_UNIT"));
+ if (msg) /* a message of bytes not text comes as a list: left out */
+ sy_err_add(e, ts ? atoll(ts) / 1000000 : 0, who ? who : "", msg);
+ janas_json_free(d);
+ }
+ return 0;
+}
+
+int sy_read_failed(const char *t, struct sy_errors *e)
+{
+ for (const char *line = t; line && *line;) {
+ char unit[256];
+ const char *p = line;
+ while (*p == ' ' || *p == '*' || (unsigned char)*p >= 0x80)
+ p++; /* the mark of a failed unit, "●" */
+ word(p, unit, sizeof unit);
+ line = strchr(line, '\n');
+ line = line ? line + 1 : NULL;
+ if (!unit[0])
+ continue;
+ /* the instances of a template, "[email protected]", counted once */
+ char *at = strchr(unit, '@');
+ if (at) {
+ char *dot = strrchr(at, '.');
+ memmove(at + 1, dot ? dot : at + strlen(at),
+ strlen(dot ? dot : at + strlen(at)) + 1);
+ }
+ int i = 0;
+ while (i < e->n_failed && strcmp(e->failed[i], unit))
+ i++;
+ if (i < e->n_failed) {
+ e->failed_n[i]++;
+ continue;
+ }
+ if (e->n_failed == SY_FAILED) {
+ e->more_failed++;
+ continue;
+ }
+ sy_put(e->failed[i], sizeof e->failed[i], unit);
+ e->failed_n[i] = 1;
+ e->n_failed++;
+ }
+ return 0;
+}
+
+static void update_add(struct sy_updates *u, const char *name, const char *to,
+ const char *from, int security)
+{
+ u->total++;
+ u->security += security;
+ if (u->n == SY_UPDATES)
+ return;
+ struct sy_update *x = &u->u[u->n++];
+ sy_put(x->name, sizeof x->name, name);
+ sy_put(x->to, sizeof x->to, to);
+ sy_put(x->from, sizeof x->from, from);
+ x->security = security;
+}
+
+int sy_read_apt(const char *t, struct sy_updates *u)
+{
+ /* "name/suite version arch [upgradable from: old]" */
+ for (const char *line = t; line && *line;) {
+ char l[1024];
+ const char *nl = strchr(line, '\n');
+ copy(l, sizeof l, line, nl ? (size_t)(nl - line) : strlen(line));
+ line = nl ? nl + 1 : NULL;
+ char *slash = strchr(l, '/'), *from = strstr(l, "[upgradable from: ");
+ if (!slash || !from || slash > from)
+ continue;
+ *slash = 0;
+ char suite[128], ver[64];
+ const char *p = word(slash + 1, suite, sizeof suite);
+ word(p, ver, sizeof ver);
+ char *old = from + 18, *close = strchr(old, ']');
+ if (close)
+ *close = 0;
+ update_add(u, l, ver, old, strstr(suite, "-security") != NULL);
+ }
+ snprintf(u->tool, sizeof u->tool, "apt");
+ return 0;
+}
+
+int sy_read_dnf(const char *t, struct sy_updates *u)
+{
+ /* after a blank line: "name.arch version repo"; "Obsoleting
+ Packages" ends the list */
+ for (const char *line = t; line && *line;) {
+ char l[1024];
+ const char *nl = strchr(line, '\n');
+ copy(l, sizeof l, line, nl ? (size_t)(nl - line) : strlen(line));
+ line = nl ? nl + 1 : NULL;
+ if (!strncmp(l, "Obsoleting", 10))
+ break;
+ char name[128], ver[64], repo[64];
+ const char *p = word(l, name, sizeof name);
+ p = word(p, ver, sizeof ver);
+ word(p, repo, sizeof repo);
+ char *dot = strrchr(name, '.');
+ if (!repo[0] || !dot || !isdigit((unsigned char)ver[0]))
+ continue;
+ *dot = 0;
+ update_add(u, name, ver, "", 0);
+ }
+ snprintf(u->tool, sizeof u->tool, "dnf");
+ return 0;
+}
+
+int sy_read_pacman(const char *t, struct sy_updates *u)
+{
+ for (const char *line = t; line && *line;) {
+ char l[1024];
+ const char *nl = strchr(line, '\n');
+ copy(l, sizeof l, line, nl ? (size_t)(nl - line) : strlen(line));
+ line = nl ? nl + 1 : NULL;
+ char name[128], old[64], arrow[8], ver[64];
+ const char *p = word(l, name, sizeof name);
+ p = word(p, old, sizeof old);
+ p = word(p, arrow, sizeof arrow);
+ word(p, ver, sizeof ver);
+ if (strcmp(arrow, "->") || !ver[0])
+ continue;
+ update_add(u, name, ver, old, 0);
+ }
+ snprintf(u->tool, sizeof u->tool, "pacman");
+ return 0;
+}
+
+int sy_read_wireless(const char *t, const char *iface, int *dbm, int *pct)
+{
+ char key[80];
+ snprintf(key, sizeof key, "%s:", iface);
+ for (const char *line = t; line && *line;) {
+ const char *p = line;
+ while (*p == ' ')
+ p++;
+ if (!strncmp(p, key, strlen(key))) {
+ int status;
+ double link, level;
+ if (sscanf(p + strlen(key), "%x %lf %lf", (unsigned *)&status,
+ &link, &level) != 3)
+ return -1;
+ *dbm = (int)level;
+ *pct = (int)(link * 100 / 70 + 0.5); /* the quality is of 70 */
+ if (*pct > 100)
+ *pct = 100;
+ return 0;
+ }
+ line = strchr(line, '\n');
+ line = line ? line + 1 : NULL;
+ }
+ return -1;
+}
+
+int sy_read_route(const char *t, char *gw, size_t gw_cap, char *iface,
+ size_t iface_cap)
+{
+ for (const char *line = t; line && *line;) {
+ char ifc[64];
+ unsigned dest, via, flags;
+ if (sscanf(line, "%63s %x %x %x", ifc, &dest, &via, &flags) == 4 &&
+ dest == 0 && (flags & 2)) { /* RTF_GATEWAY */
+ /* in the host's order: little-endian, the first byte first */
+ snprintf(gw, gw_cap, "%u.%u.%u.%u", via & 255, (via >> 8) & 255,
+ (via >> 16) & 255, via >> 24);
+ snprintf(iface, iface_cap, "%s", ifc);
+ return 0;
+ }
+ line = strchr(line, '\n');
+ line = line ? line + 1 : NULL;
+ }
+ return -1;
+}
+
+int sy_read_resolv(const char *t, struct sy_net *n)
+{
+ for (const char *line = t; line && *line;) {
+ char key[32], v[64];
+ if (sscanf(line, "%31s %63s", key, v) == 2 &&
+ !strcmp(key, "nameserver") && n->n_dns < 3)
+ sy_put(n->dns[n->n_dns++], sizeof n->dns[0], v);
+ line = strchr(line, '\n');
+ line = line ? line + 1 : NULL;
+ }
+ return 0;
+}
+
+int sy_read_os_release(const char *t, char *out, size_t cap)
+{
+ const char *p = after(t, "PRETTY_NAME=");
+ if (!p)
+ return -1;
+ if (*p == '"')
+ p++;
+ size_t n = strcspn(p, "\"\n");
+ copy(out, cap, p, n);
+ return 0;
+}
+
+const char *sy_sensor_kind(const char *h)
+{
+ static const struct {
+ const char *name, *kind;
+ } K[] = {{"coretemp", "cpu"}, {"k10temp", "cpu"}, {"zenpower", "cpu"},
+ {"cpu_thermal", "cpu"}, {"nvme", "disk"}, {"drivetemp", "disk"},
+ {"spd5118", "memory"}, {"jc42", "memory"}, {"iwlwifi", "wifi"},
+ {"ath", "wifi"}, {"mt7", "wifi"}, {"amdgpu", "gpu"},
+ {"nouveau", "gpu"}, {"radeon", "gpu"}, {"i915", "gpu"},
+ {"xe", "gpu"}, {"acpitz", "board"}, {"pch_", "chipset"},
+ {"BAT", "battery"}};
+ for (size_t i = 0; i < sizeof K / sizeof *K; i++)
+ if (!strncmp(h, K[i].name, strlen(K[i].name)))
+ return K[i].kind;
+ return "other";
+}
diff --git a/src/services/system/system.h b/src/services/system/system.h
new file mode 100644
index 0000000..9657773
--- /dev/null
+++ b/src/services/system/system.h
@@ -0,0 +1,253 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * system.h - janas-system, this computer as an MCP service: how it is
+ * (memory, processor, disks, battery, temperatures), what runs on it, its
+ * errors, its updates, its network, what fills a directory. It only reads.
+ *
+ * What its parts share. The system is read by one backend a platform,
+ * behind the sy_get_* calls: linux.c (from /proc and /sys, journalctl,
+ * systemctl and the package manager) and windows.c (from the Win32 API);
+ * usage.c walks a directory. read.c reads the texts of Linux (no system
+ * here: the tests read kept texts), data.c and layouts.c write the
+ * answers as data with a layout, tools.c offers the tools.
+ */
+#ifndef JANAS_SYSTEM_H
+#define JANAS_SYSTEM_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "llm/json.h"
+
+#define SY_DISKS 16
+#define SY_TEMPS 12
+#define SY_PROCS 15
+#define SY_ERRS 30
+#define SY_FAILED 12
+#define SY_UPDATES 40
+#define SY_IFACES 12
+#define SY_ADDRS 4
+#define SY_USAGE 20
+
+#define SY_SAMPLE_MS 500 /* between the two readings of the processor */
+#define SY_USAGE_MS 8000 /* at most, to walk a directory */
+#define SY_USAGE_DEPTH 64 /* levels at most below it */
+#define SY_FULL_PCT 90 /* a disk this full is told */
+#define SY_RUN_MS 20000 /* a program run (journalctl, apt) at most */
+
+struct sy_disk {
+ char mount[256], dev[128], fs[32];
+ uint64_t total, avail; /* bytes; avail: what the user may write */
+ int ro;
+};
+
+struct sy_disks {
+ struct sy_disk d[SY_DISKS];
+ int n, more;
+};
+
+/* kind: cpu, core (the hottest core), disk, memory, wifi, board, gpu,
+ battery, chipset, other */
+struct sy_temp {
+ char kind[12], label[64];
+ double c, high; /* high: the sensor's critical limit (else its maximum),
+ 0 when none */
+};
+
+struct sy_battery {
+ int present, pct; /* pct -1: not told */
+ int mains; /* 1 on mains, 0 not, -1 not known */
+ char state[16]; /* charging, discharging, full, idle, unknown */
+ int minutes; /* to empty or to full, -1 when not known */
+ int health; /* % of the design capacity left, -1 */
+};
+
+struct sy_status {
+ char host[64], os[128], kernel[96], cpu[128], platform[12];
+ long uptime_s;
+ int has_load, cpus;
+ double load[3];
+ double cpu_pct; /* of the whole processor, over SY_SAMPLE_MS */
+ double sys_pct; /* of it, the kernel's */
+ uint64_t mem_total, mem_avail, swap_total, swap_free;
+ double psi_cpu, psi_mem, psi_io; /* % of time waited, 10 s; -1 none */
+ struct sy_disks disks;
+ struct sy_battery bat;
+ struct sy_temp t[SY_TEMPS];
+ int n_temps;
+};
+
+struct sy_proc {
+ int pid, threads;
+ char name[64], user[32];
+ double cpu_pct; /* of the whole processor */
+ uint64_t mem; /* resident, bytes */
+ long age_s;
+};
+
+struct sy_procs {
+ struct sy_proc p[SY_PROCS];
+ int n, total, matched;
+ char by[8]; /* cpu or memory */
+ char name[64]; /* the name asked, "" for all */
+ uint64_t mem_total;
+};
+
+struct sy_err {
+ long long at; /* seconds since 1970, the latest */
+ char who[64], text[240];
+ int count;
+};
+
+struct sy_errors {
+ struct sy_err e[SY_ERRS];
+ int n, more, total;
+ char failed[SY_FAILED][96];
+ int failed_n[SY_FAILED]; /* instances of a template unit (name@...) */
+ int n_failed, more_failed;
+ int hours, user_only;
+ int cut; /* the log read only in part: total is at least that */
+ char how[16]; /* journal, eventlog */
+};
+
+struct sy_update {
+ char name[96], to[64], from[64];
+ int security;
+};
+
+struct sy_updates {
+ struct sy_update u[SY_UPDATES];
+ int n, total, security;
+ long long checked; /* when the list was last fetched, 0 not known */
+ char tool[16]; /* apt, dnf, pacman */
+};
+
+struct sy_iface {
+ char name[64], kind[12], state[12]; /* kind: wifi, ethernet, virtual */
+ char addr[SY_ADDRS][64];
+ int n_addr;
+ long speed_mbps; /* 0 when not told */
+ int signal_dbm, wifi_pct; /* 0 when not wireless */
+ uint64_t rx, tx; /* bytes since the start */
+};
+
+struct sy_net {
+ struct sy_iface i[SY_IFACES];
+ int n, more;
+ char gateway[64], gw_iface[64];
+ char dns[3][64];
+ int n_dns;
+};
+
+struct sy_entry {
+ char name[256];
+ uint64_t bytes;
+ long files;
+ int dir;
+};
+
+struct sy_usage {
+ char path[1024];
+ struct sy_entry e[SY_USAGE];
+ int n, more;
+ uint64_t total, fs_total, fs_avail;
+ long files, unread; /* unread: directories that could not be read */
+ int cut; /* the time ran out: sizes are at least these */
+ double secs;
+};
+
+/* ---- the backend: linux.c or windows.c (and usage.c) ---- */
+
+int sy_get_status(struct sy_status *s, char *err, size_t err_len);
+int sy_get_disks(struct sy_disks *d, char *err, size_t err_len);
+/* by "cpu" or "memory"; name: only the processes whose name has it */
+int sy_get_procs(const char *by, const char *name, struct sy_procs *p,
+ char *err, size_t err_len);
+int sy_get_errors(int hours, struct sy_errors *e, char *err, size_t err_len);
+int sy_get_updates(struct sy_updates *u, char *err, size_t err_len);
+int sy_get_net(struct sy_net *n, char *err, size_t err_len);
+/* path: a directory (NULL: the home); its entries by size */
+int sy_get_usage(const char *path, struct sy_usage *u, char *err,
+ size_t err_len);
+/* the user's home directory, or "" */
+const char *sy_home(void);
+
+/* ---- read.c: the texts of Linux ---- */
+
+/* s into out, cut to cap - 1 bytes */
+void sy_put(char *out, size_t cap, const char *s);
+
+/* /proc/meminfo into mem_* and swap_* */
+int sy_read_meminfo(const char *t, struct sy_status *s);
+/* /proc/stat's first line: ticks busy, in all, and the kernel's (system,
+ interrupts) */
+int sy_read_cpu_ticks(const char *t, uint64_t *busy, uint64_t *all,
+ uint64_t *sys);
+/* /proc/loadavg */
+int sy_read_loadavg(const char *t, double load[3]);
+/* /proc/pressure/<x>: the "some avg10", -1 when not there */
+double sy_read_psi(const char *t);
+/* /proc/<pid>/stat: its name, its ticks (user and system), threads and
+ start (ticks after the boot) */
+int sy_read_pid_stat(const char *t, char *name, size_t cap, uint64_t *ticks,
+ int *threads, uint64_t *start);
+/* /proc/self/mountinfo: the filesystems on a disk (or a network share),
+ each device once */
+int sy_read_mountinfo(const char *t, struct sy_disks *d);
+/* journalctl -o json, a line an entry, the latest last */
+int sy_read_journal(const char *t, size_t n, struct sy_errors *e);
+/* systemctl --failed --plain --no-legend */
+int sy_read_failed(const char *t, struct sy_errors *e);
+/* apt list --upgradable, in LC_ALL=C */
+int sy_read_apt(const char *t, struct sy_updates *u);
+/* dnf check-update: a package a line, "name.arch version repo" */
+int sy_read_dnf(const char *t, struct sy_updates *u);
+/* pacman -Qu: "name old -> new" */
+int sy_read_pacman(const char *t, struct sy_updates *u);
+/* /proc/net/wireless: the signal of iface (dBm) and its quality (%) */
+int sy_read_wireless(const char *t, const char *iface, int *dbm, int *pct);
+/* /proc/net/route: the default gateway */
+int sy_read_route(const char *t, char *gw, size_t gw_cap, char *iface,
+ size_t iface_cap);
+/* resolv.conf's name servers */
+int sy_read_resolv(const char *t, struct sy_net *n);
+/* os-release's PRETTY_NAME */
+int sy_read_os_release(const char *t, char *out, size_t cap);
+/* the kind of a hwmon sensor from its name ("coretemp": cpu), "" to leave
+ it out */
+const char *sy_sensor_kind(const char *hwmon_name);
+/* one error more into e: the same text from the same program counted */
+void sy_err_add(struct sy_errors *e, long long at, const char *who,
+ const char *text);
+/* the latest errors first */
+void sy_err_order(struct sy_errors *e);
+
+/* ---- data.c ---- */
+
+void sy_jstr(struct janas_buf *b, const char *key, const char *v);
+void sy_status_data(struct janas_buf *b, const struct sy_status *s);
+void sy_disks_data(struct janas_buf *b, const struct sy_disks *d);
+void sy_procs_data(struct janas_buf *b, const struct sy_procs *p);
+void sy_errors_data(struct janas_buf *b, const struct sy_errors *e);
+void sy_updates_data(struct janas_buf *b, const struct sy_updates *u);
+void sy_net_data(struct janas_buf *b, const struct sy_net *n);
+void sy_usage_data(struct janas_buf *b, const struct sy_usage *u);
+
+/* ---- layouts.c ---- */
+
+extern const char SY_STATUS_LAYOUT[], SY_STATUS_BRIEF[];
+extern const char SY_DISKS_LAYOUT[], SY_DISKS_BRIEF[];
+extern const char SY_PROCS_LAYOUT[], SY_PROCS_BRIEF[];
+extern const char SY_ERRORS_LAYOUT[], SY_ERRORS_BRIEF[];
+extern const char SY_UPDATES_LAYOUT[], SY_UPDATES_BRIEF[];
+extern const char SY_NET_LAYOUT[], SY_NET_BRIEF[];
+extern const char SY_USAGE_LAYOUT[], SY_USAGE_BRIEF[];
+
+/* ---- tools.c ---- */
+
+void sy_tools_list(void *ctx, struct janas_buf *b);
+int sy_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b);
+
+#endif
diff --git a/src/services/system/tools.c b/src/services/system/tools.c
new file mode 100644
index 0000000..57bca48
--- /dev/null
+++ b/src/services/system/tools.c
@@ -0,0 +1,206 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * tools.c - janas-system's tools (see system.h). They only read, and say
+ * so (readOnlyHint); none of them reaches the network (openWorldHint
+ * false): how the computer is, its disks and what fills a directory, its
+ * processes, its errors, its updates, its network.
+ */
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "common/mcp_server.h"
+#include "services/common/template.h"
+#include "system.h"
+
+#define READS \
+ "\"annotations\": {\"readOnlyHint\": true, \"openWorldHint\": false}"
+#define NO_ARGS \
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {}, " \
+ "\"additionalProperties\": false}"
+
+void sy_tools_list(void *ctx, struct janas_buf *b)
+{
+ (void)ctx;
+ janas_buf_puts(
+ b,
+ "\"tools\": [{\"name\": \"system_status\", \"title\": \"This "
+ "computer\", \"description\": \"How this computer is: processor, "
+ "memory, disks, battery, temperatures, how long it has been on. For "
+ "'how is the computer', 'why is it slow'.\", " NO_ARGS ", " READS "}, "
+ "{\"name\": \"system_disks\", \"title\": \"Disks\", "
+ "\"description\": \"The disks and their free space; with a path, "
+ "what fills that directory, biggest first.\", \"inputSchema\": "
+ "{\"type\": \"object\", \"properties\": {\"path\": {\"type\": "
+ "\"string\", \"description\": \"a directory (~ for the home); leave "
+ "it out for the disks\"}}, \"additionalProperties\": false}, " READS
+ "}, "
+ "{\"name\": \"system_processes\", \"title\": \"Processes\", "
+ "\"description\": \"The programs running that use the most "
+ "processor or memory, or those of a name (is a program running?).\", "
+ "\"inputSchema\": {\"type\": \"object\", \"properties\": {\"by\": "
+ "{\"type\": \"string\", \"enum\": [\"cpu\", \"memory\"]}, \"name\": "
+ "{\"type\": \"string\", \"description\": \"part of a program's "
+ "name\"}}, \"additionalProperties\": false}, " READS "}, "
+ "{\"name\": \"system_errors\", \"title\": \"Errors\", "
+ "\"description\": \"The errors in the system's logs and the "
+ "services that failed.\", \"inputSchema\": {\"type\": \"object\", "
+ "\"properties\": {\"hours\": {\"type\": \"number\", \"description\": "
+ "\"the last hours; leave it out for since the computer "
+ "started\"}}, \"additionalProperties\": false}, " READS "}, "
+ "{\"name\": \"system_updates\", \"title\": \"Updates\", "
+ "\"description\": \"The updates available for the installed "
+ "packages, by the list the package manager last fetched.\", " NO_ARGS
+ ", " READS "}, "
+ "{\"name\": \"system_network\", \"title\": \"Network\", "
+ "\"description\": \"The network interfaces, their addresses, the "
+ "Wi-Fi signal, the gateway and the name servers.\", " NO_ARGS ", " READS
+ "}]");
+}
+
+static const char *arg_str(const struct janas_json *args, const char *name)
+{
+ const char *s = janas_json_str(janas_json_get(args, name));
+ return s && *s ? s : NULL;
+}
+
+static int fail(struct janas_buf *b, const char *fmt, ...)
+ __attribute__((format(printf, 2, 3)));
+
+static int fail(struct janas_buf *b, const char *fmt, ...)
+{
+ char line[1024];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(line, sizeof line, fmt, ap);
+ va_end(ap);
+ janas_mcps_text_result(b, line, strlen(line), 1);
+ return 0;
+}
+
+static int answer(struct janas_buf *b, const char *name, struct janas_buf *d,
+ const char *layout, const char *brief)
+{
+ char err[300];
+ int oom = d->oom;
+ int r = oom ? -1
+ : janas_tpl_result(b, name, d->p, d->n, layout, brief, err,
+ sizeof err);
+ janas_buf_free(d);
+ if (r != 0)
+ return fail(b, "The answer could not be written: %s.",
+ oom ? "out of memory" : err);
+ return 0;
+}
+
+/* the structures are large: one at a time, kept here */
+static union {
+ struct sy_status status;
+ struct sy_disks disks;
+ struct sy_usage usage;
+ struct sy_procs procs;
+ struct sy_errors errors;
+ struct sy_updates updates;
+ struct sy_net net;
+} R;
+
+static int t_status(const struct janas_json *args, struct janas_buf *b)
+{
+ (void)args;
+ char err[300] = "";
+ if (sy_get_status(&R.status, err, sizeof err) != 0)
+ return fail(b, "This computer could not be read: %s.", err);
+ struct janas_buf d = {0};
+ sy_status_data(&d, &R.status);
+ return answer(b, "system_status", &d, SY_STATUS_LAYOUT, SY_STATUS_BRIEF);
+}
+
+static int t_disks(const struct janas_json *args, struct janas_buf *b)
+{
+ char err[1200] = "";
+ const char *path = arg_str(args, "path");
+ struct janas_buf d = {0};
+ if (path) {
+ if (sy_get_usage(path, &R.usage, err, sizeof err) != 0)
+ return fail(b, "%s.", err);
+ sy_usage_data(&d, &R.usage);
+ return answer(b, "system_usage", &d, SY_USAGE_LAYOUT, SY_USAGE_BRIEF);
+ }
+ if (sy_get_disks(&R.disks, err, sizeof err) != 0)
+ return fail(b, "The disks could not be read: %s.", err);
+ sy_disks_data(&d, &R.disks);
+ return answer(b, "system_disks", &d, SY_DISKS_LAYOUT, SY_DISKS_BRIEF);
+}
+
+static int t_procs(const struct janas_json *args, struct janas_buf *b)
+{
+ const char *by = arg_str(args, "by");
+ if (!by || strcmp(by, "memory"))
+ by = "cpu";
+ char err[300] = "";
+ if (sy_get_procs(by, arg_str(args, "name"), &R.procs, err, sizeof err) != 0)
+ return fail(b, "The processes could not be read: %s.", err);
+ struct janas_buf d = {0};
+ sy_procs_data(&d, &R.procs);
+ return answer(b, "system_processes", &d, SY_PROCS_LAYOUT, SY_PROCS_BRIEF);
+}
+
+static int t_errors(const struct janas_json *args, struct janas_buf *b)
+{
+ const struct janas_json *h = janas_json_get(args, "hours");
+ double hours = h && h->type == JANAS_JSON_NUMBER ? janas_json_num(h, 0) : 0;
+ if (hours < 0)
+ hours = 0;
+ if (hours > 24 * 31)
+ hours = 24 * 31;
+ char err[400] = "";
+ if (sy_get_errors((int)(hours + 0.5), &R.errors, err, sizeof err) != 0)
+ return fail(b, "The errors could not be read: %s.", err);
+ struct janas_buf d = {0};
+ sy_errors_data(&d, &R.errors);
+ return answer(b, "system_errors", &d, SY_ERRORS_LAYOUT, SY_ERRORS_BRIEF);
+}
+
+static int t_updates(const struct janas_json *args, struct janas_buf *b)
+{
+ (void)args;
+ char err[400] = "";
+ if (sy_get_updates(&R.updates, err, sizeof err) != 0)
+ return fail(b, "The updates could not be read: %s. Tell the user so.",
+ err);
+ struct janas_buf d = {0};
+ sy_updates_data(&d, &R.updates);
+ return answer(b, "system_updates", &d, SY_UPDATES_LAYOUT, SY_UPDATES_BRIEF);
+}
+
+static int t_net(const struct janas_json *args, struct janas_buf *b)
+{
+ (void)args;
+ char err[300] = "";
+ if (sy_get_net(&R.net, err, sizeof err) != 0)
+ return fail(b, "The network could not be read: %s.", err);
+ struct janas_buf d = {0};
+ sy_net_data(&d, &R.net);
+ return answer(b, "system_network", &d, SY_NET_LAYOUT, SY_NET_BRIEF);
+}
+
+int sy_tools_call(void *ctx, const struct janas_json *params,
+ struct janas_buf *b)
+{
+ (void)ctx;
+ const struct janas_json *name = janas_json_get(params, "name");
+ const struct janas_json *args = janas_json_get(params, "arguments");
+ if (args && args->type != JANAS_JSON_OBJECT)
+ args = NULL;
+ static const struct {
+ const char *name;
+ int (*fn)(const struct janas_json *, struct janas_buf *);
+ } T[] = {{"system_status", t_status}, {"system_disks", t_disks},
+ {"system_processes", t_procs}, {"system_errors", t_errors},
+ {"system_updates", t_updates}, {"system_network", t_net}};
+ for (size_t i = 0; i < sizeof T / sizeof *T; i++)
+ if (janas_json_is(name, T[i].name))
+ return T[i].fn(args, b);
+ return -1;
+}
diff --git a/src/services/system/usage.c b/src/services/system/usage.c
new file mode 100644
index 0000000..1c07e2d
--- /dev/null
+++ b/src/services/system/usage.c
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * usage.c - what fills a directory (see system.h), on POSIX systems: each
+ * entry's size, the directories' summed over what they hold, as the disk
+ * counts it (the blocks taken). Within limits: SY_USAGE_MS at most, after
+ * which the sizes are told as at least these; SY_USAGE_DEPTH levels; never
+ * across to another filesystem, never through a symbolic link. A file of
+ * more names than one (hard links) is counted at each.
+ */
+#ifndef _WIN32
+#define _GNU_SOURCE
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/statvfs.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "system.h"
+
+struct walk {
+ dev_t dev;
+ double end; /* ms, monotonic */
+ int cut;
+ long files, unread;
+};
+
+static double now_ms(void)
+{
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return (double)t.tv_sec * 1e3 + (double)t.tv_nsec / 1e6;
+}
+
+static uint64_t taken(const struct stat *st)
+{
+ return (uint64_t)st->st_blocks * 512;
+}
+
+/* the bytes under the directory fd (closed here) */
+static uint64_t sum(struct walk *w, int fd, int depth, long *files)
+{
+ DIR *d = fdopendir(fd);
+ if (!d) {
+ close(fd);
+ w->unread++;
+ return 0;
+ }
+ uint64_t total = 0;
+ struct dirent *e;
+ unsigned tick = 0;
+ while ((e = readdir(d))) {
+ if ((++tick & 255) == 0 && now_ms() > w->end)
+ w->cut = 1;
+ if (w->cut)
+ break;
+ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
+ continue;
+ struct stat st;
+ if (fstatat(dirfd(d), e->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0)
+ continue;
+ total += taken(&st);
+ if (!S_ISDIR(st.st_mode)) {
+ (*files)++;
+ continue;
+ }
+ if (st.st_dev != w->dev || depth >= SY_USAGE_DEPTH)
+ continue;
+ int sub = openat(dirfd(d), e->d_name,
+ O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (sub < 0) {
+ w->unread++;
+ continue;
+ }
+ total += sum(w, sub, depth + 1, files);
+ }
+ closedir(d);
+ return total;
+}
+
+static int bigger(const void *a, const void *b)
+{
+ uint64_t x = ((const struct sy_entry *)a)->bytes,
+ y = ((const struct sy_entry *)b)->bytes;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+int sy_get_usage(const char *path, struct sy_usage *u, char *err,
+ size_t err_len)
+{
+ memset(u, 0, sizeof *u);
+ double t0 = now_ms();
+ const char *home = sy_home();
+ if (!path || !*path)
+ path = home;
+ if (path[0] == '~' && (path[1] == '/' || !path[1]))
+ snprintf(u->path, sizeof u->path, "%s%s", home, path + 1);
+ else
+ sy_put(u->path, sizeof u->path, path);
+ int fd = open(u->path, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ struct stat st;
+ if (fd < 0 || fstat(fd, &st) != 0) {
+ snprintf(err, err_len, "%s cannot be read: %s", u->path,
+ strerror(errno));
+ if (fd >= 0)
+ close(fd);
+ return -1;
+ }
+ struct statvfs v;
+ if (fstatvfs(fd, &v) == 0) {
+ u->fs_total = (uint64_t)v.f_blocks * v.f_frsize;
+ u->fs_avail = (uint64_t)v.f_bavail * v.f_frsize;
+ }
+ struct walk w = {.dev = st.st_dev, .end = t0 + SY_USAGE_MS};
+ DIR *d = fdopendir(fd);
+ if (!d) {
+ close(fd);
+ snprintf(err, err_len, "%s cannot be read", u->path);
+ return -1;
+ }
+ /* every entry kept to sort; the biggest SY_USAGE told */
+ int cap = 256, n = 0;
+ struct sy_entry *all = malloc((size_t)cap * sizeof *all);
+ struct dirent *e;
+ while (all && (e = readdir(d))) {
+ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
+ continue;
+ if (fstatat(dirfd(d), e->d_name, &st, AT_SYMLINK_NOFOLLOW) != 0)
+ continue;
+ if (n == cap) {
+ struct sy_entry *m = realloc(all, (size_t)(cap *= 2) * sizeof *m);
+ if (!m)
+ break;
+ all = m;
+ }
+ struct sy_entry *x = &all[n++];
+ memset(x, 0, sizeof *x);
+ sy_put(x->name, sizeof x->name, e->d_name);
+ x->bytes = taken(&st);
+ x->dir = S_ISDIR(st.st_mode);
+ if (!x->dir) {
+ x->files = 1;
+ continue;
+ }
+ if (st.st_dev != w.dev || w.cut)
+ continue;
+ int sub = openat(dirfd(d), e->d_name,
+ O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (sub < 0) {
+ w.unread++;
+ continue;
+ }
+ x->bytes += sum(&w, sub, 1, &x->files);
+ }
+ closedir(d);
+ if (!all) {
+ snprintf(err, err_len, "out of memory");
+ return -1;
+ }
+ qsort(all, (size_t)n, sizeof *all, bigger);
+ for (int i = 0; i < n; i++) {
+ u->total += all[i].bytes;
+ u->files += all[i].files;
+ }
+ u->n = n < SY_USAGE ? n : SY_USAGE;
+ u->more = n - u->n;
+ memcpy(u->e, all, (size_t)u->n * sizeof *all);
+ free(all);
+ u->cut = w.cut;
+ u->unread = w.unread;
+ u->secs = (now_ms() - t0) / 1e3;
+ return 0;
+}
+#endif
diff --git a/src/services/system/windows.c b/src/services/system/windows.c
new file mode 100644
index 0000000..e215661
--- /dev/null
+++ b/src/services/system/windows.c
@@ -0,0 +1,781 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * windows.c - janas-system's backend for Windows (see system.h), from the
+ * Win32 API, no PowerShell and no WMI: the memory, the processor's times,
+ * the drives, the power status, the processes (Tool Help), the event log
+ * (System and Application, levels critical and error), the services set
+ * to start by themselves and stopped with an error, the network adapters
+ * (IP Helper) and the Wi-Fi signal (WLAN API); what fills a directory,
+ * by the files' lengths (not the clusters they take, as on POSIX).
+ * Not told on Windows: the temperatures (they need WMI and an
+ * administrator), the pressure and the load, the updates (Windows
+ * Update's own list).
+ *
+ * Linked with: iphlpapi ws2_32 wevtapi wlanapi advapi32 ole32.
+ */
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#define _WIN32_WINNT 0x0A00
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <iphlpapi.h>
+#include <netioapi.h>
+#include <objbase.h>
+#include <psapi.h>
+#include <tlhelp32.h>
+#include <winevt.h>
+#include <wlanapi.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "system.h"
+
+/* UTF-16 to UTF-8, cut to cap */
+static void utf8(const wchar_t *w, char *out, size_t cap)
+{
+ out[0] = 0;
+ if (w && !WideCharToMultiByte(CP_UTF8, 0, w, -1, out, (int)cap, NULL, NULL))
+ out[cap - 1] = 0;
+}
+
+static uint64_t ft64(FILETIME f)
+{
+ return ((uint64_t)f.dwHighDateTime << 32) | f.dwLowDateTime;
+}
+
+const char *sy_home(void)
+{
+ static char home[MAX_PATH * 3];
+ if (!home[0]) {
+ wchar_t w[MAX_PATH];
+ DWORD n = GetEnvironmentVariableW(L"USERPROFILE", w, MAX_PATH);
+ if (n && n < MAX_PATH)
+ utf8(w, home, sizeof home);
+ }
+ return home;
+}
+
+static void reg_str(HKEY root, const char *key, const char *name, char *out,
+ size_t cap)
+{
+ DWORD n = (DWORD)cap;
+ out[0] = 0;
+ if (RegGetValueA(root, key, name, RRF_RT_REG_SZ, NULL, out, &n) !=
+ ERROR_SUCCESS)
+ out[0] = 0;
+}
+
+int sy_get_disks(struct sy_disks *d, char *err, size_t err_len)
+{
+ (void)err, (void)err_len;
+ memset(d, 0, sizeof *d);
+ DWORD mask = GetLogicalDrives();
+ for (int i = 0; i < 26; i++) {
+ if (!(mask & (1u << i)))
+ continue;
+ char root[4] = {(char)('A' + i), ':', '\\', 0};
+ UINT type = GetDriveTypeA(root);
+ if (type != DRIVE_FIXED && type != DRIVE_REMOVABLE &&
+ type != DRIVE_REMOTE)
+ continue;
+ ULARGE_INTEGER avail, total, free_all;
+ if (!GetDiskFreeSpaceExA(root, &avail, &total, &free_all))
+ continue; /* a card reader without a card */
+ if (d->n == SY_DISKS) {
+ d->more++;
+ continue;
+ }
+ struct sy_disk *k = &d->d[d->n++];
+ sy_put(k->mount, sizeof k->mount, root);
+ char label[MAX_PATH + 1] = "", fs[MAX_PATH + 1] = "";
+ DWORD flags = 0;
+ GetVolumeInformationA(root, label, sizeof label, NULL, NULL, &flags, fs,
+ sizeof fs);
+ sy_put(k->dev, sizeof k->dev, label);
+ sy_put(k->fs, sizeof k->fs, fs);
+ k->ro = (flags & FILE_READ_ONLY_VOLUME) != 0;
+ k->total = total.QuadPart;
+ k->avail = avail.QuadPart;
+ }
+ return 0;
+}
+
+static void battery(struct sy_battery *b)
+{
+ memset(b, 0, sizeof *b);
+ b->pct = b->minutes = b->health = -1;
+ b->mains = -1;
+ sy_put(b->state, sizeof b->state, "unknown");
+ SYSTEM_POWER_STATUS p;
+ if (!GetSystemPowerStatus(&p))
+ return;
+ b->mains = p.ACLineStatus == 1 ? 1 : p.ACLineStatus == 0 ? 0 : -1;
+ if (p.BatteryFlag == 255 || (p.BatteryFlag & 128))
+ return; /* not known, or no battery */
+ b->present = 1;
+ b->pct = p.BatteryLifePercent <= 100 ? p.BatteryLifePercent : -1;
+ sy_put(b->state, sizeof b->state,
+ (p.BatteryFlag & 8) ? "charging"
+ : b->mains == 0 ? "discharging"
+ : b->pct == 100 ? "full"
+ : "idle");
+ if (b->mains == 0 && p.BatteryLifeTime != (DWORD)-1)
+ b->minutes = (int)(p.BatteryLifeTime / 60);
+}
+
+static void os_name(struct sy_status *s)
+{
+ static const char key[] = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
+ char product[96], display[32], build[16];
+ reg_str(HKEY_LOCAL_MACHINE, key, "ProductName", product, sizeof product);
+ reg_str(HKEY_LOCAL_MACHINE, key, "DisplayVersion", display, sizeof display);
+ reg_str(HKEY_LOCAL_MACHINE, key, "CurrentBuildNumber", build, sizeof build);
+ /* Windows 11 still calls itself Windows 10 there: its build tells */
+ if (atoi(build) >= 22000 && !strncmp(product, "Windows 10", 10))
+ product[8] = '1', product[9] = '1';
+ snprintf(s->os, sizeof s->os, "%s%s%s", product, display[0] ? " " : "",
+ display);
+ snprintf(s->kernel, sizeof s->kernel, "build %s", build);
+}
+
+int sy_get_status(struct sy_status *s, char *err, size_t err_len)
+{
+ memset(s, 0, sizeof *s);
+ sy_put(s->platform, sizeof s->platform, "windows");
+ FILETIME i0, k0, u0, i1, k1, u1;
+ int times = GetSystemTimes(&i0, &k0, &u0) != 0;
+ MEMORYSTATUSEX m = {.dwLength = sizeof m};
+ if (!GlobalMemoryStatusEx(&m)) {
+ snprintf(err, err_len, "the memory could not be read");
+ return -1;
+ }
+ s->mem_total = m.ullTotalPhys;
+ s->mem_avail = m.ullAvailPhys;
+ /* the page file: what the commit limit holds beyond the memory */
+ if (m.ullTotalPageFile > m.ullTotalPhys) {
+ s->swap_total = m.ullTotalPageFile - m.ullTotalPhys;
+ uint64_t used = (m.ullTotalPageFile - m.ullAvailPageFile) >
+ (m.ullTotalPhys - m.ullAvailPhys)
+ ? (m.ullTotalPageFile - m.ullAvailPageFile) -
+ (m.ullTotalPhys - m.ullAvailPhys)
+ : 0;
+ s->swap_free = used < s->swap_total ? s->swap_total - used : 0;
+ }
+ DWORD n = sizeof s->host;
+ GetComputerNameExA(ComputerNameDnsHostname, s->host, &n);
+ os_name(s);
+ reg_str(HKEY_LOCAL_MACHINE,
+ "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0",
+ "ProcessorNameString", s->cpu, sizeof s->cpu);
+ s->cpus = (int)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
+ s->uptime_s = (long)(GetTickCount64() / 1000);
+ s->psi_cpu = s->psi_mem = s->psi_io = -1;
+ char e2[100];
+ sy_get_disks(&s->disks, e2, sizeof e2);
+ battery(&s->bat);
+ Sleep(SY_SAMPLE_MS);
+ s->cpu_pct = -1;
+ if (times && GetSystemTimes(&i1, &k1, &u1)) {
+ /* the kernel's time holds the idle time */
+ uint64_t idle = ft64(i1) - ft64(i0);
+ uint64_t all = (ft64(k1) - ft64(k0)) + (ft64(u1) - ft64(u0));
+ if (all > 0) {
+ s->cpu_pct = (double)(all - idle) * 100 / (double)all;
+ s->sys_pct =
+ (double)(ft64(k1) - ft64(k0) - idle) * 100 / (double)all;
+ }
+ }
+ return 0;
+}
+
+/* ---- the processes ---- */
+
+struct ptime {
+ DWORD pid;
+ uint64_t t;
+};
+
+static int ci_has(const char *s, const char *what)
+{
+ size_t n = strlen(what);
+ for (; *s; s++)
+ if (!_strnicmp(s, what, n))
+ return 1;
+ return 0;
+}
+
+static uint64_t proc_time(HANDLE h, uint64_t *created)
+{
+ FILETIME c, e, k, u;
+ if (!GetProcessTimes(h, &c, &e, &k, &u))
+ return 0;
+ if (created)
+ *created = ft64(c);
+ return ft64(k) + ft64(u);
+}
+
+static void proc_user(DWORD pid, char *out, size_t cap)
+{
+ out[0] = 0;
+ HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid), tok;
+ if (!h)
+ return;
+ if (OpenProcessToken(h, TOKEN_QUERY, &tok)) {
+ char buf[256];
+ DWORD n;
+ if (GetTokenInformation(tok, TokenUser, buf, sizeof buf, &n)) {
+ wchar_t name[128], dom[128];
+ DWORD nn = 128, dn = 128;
+ SID_NAME_USE use;
+ if (LookupAccountSidW(NULL, ((TOKEN_USER *)buf)->User.Sid, name,
+ &nn, dom, &dn, &use))
+ utf8(name, out, cap);
+ }
+ CloseHandle(tok);
+ }
+ CloseHandle(h);
+}
+
+static int more_cpu(const void *a, const void *b)
+{
+ double x = ((const struct sy_proc *)a)->cpu_pct,
+ y = ((const struct sy_proc *)b)->cpu_pct;
+ uint64_t m = ((const struct sy_proc *)a)->mem,
+ k = ((const struct sy_proc *)b)->mem;
+ return x < y ? 1 : x > y ? -1 : m < k ? 1 : m > k ? -1 : 0;
+}
+
+static int more_mem(const void *a, const void *b)
+{
+ uint64_t x = ((const struct sy_proc *)a)->mem,
+ y = ((const struct sy_proc *)b)->mem;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+int sy_get_procs(const char *by, const char *name, struct sy_procs *p,
+ char *err, size_t err_len)
+{
+ memset(p, 0, sizeof *p);
+ sy_put(p->by, sizeof p->by, by);
+ sy_put(p->name, sizeof p->name, name ? name : "");
+ MEMORYSTATUSEX m = {.dwLength = sizeof m};
+ if (GlobalMemoryStatusEx(&m))
+ p->mem_total = m.ullTotalPhys;
+ HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
+ if (snap == INVALID_HANDLE_VALUE) {
+ snprintf(err, err_len, "the processes could not be listed");
+ return -1;
+ }
+ int cap = 512, n = 0;
+ struct sy_proc *v = malloc((size_t)cap * sizeof *v);
+ struct ptime *t0 = malloc((size_t)cap * sizeof *t0);
+ PROCESSENTRY32W e = {.dwSize = sizeof e};
+ for (BOOL ok = Process32FirstW(snap, &e); ok && v && t0;
+ ok = Process32NextW(snap, &e)) {
+ if (e.th32ProcessID == 0) /* the idle process */
+ continue;
+ p->total++;
+ char pname[64];
+ utf8(e.szExeFile, pname, sizeof pname);
+ char *dot = strrchr(pname, '.');
+ if (dot && !_stricmp(dot, ".exe"))
+ *dot = 0;
+ if (name && *name && !ci_has(pname, name))
+ continue;
+ p->matched++;
+ if (n == cap) {
+ cap *= 2;
+ struct sy_proc *w = realloc(v, (size_t)cap * sizeof *v);
+ struct ptime *u = w ? realloc(t0, (size_t)cap * sizeof *t0) : NULL;
+ if (!w || !u) {
+ if (w)
+ v = w;
+ break;
+ }
+ v = w, t0 = u;
+ }
+ struct sy_proc *x = &v[n];
+ memset(x, 0, sizeof *x);
+ x->pid = (int)e.th32ProcessID;
+ x->threads = (int)e.cntThreads;
+ sy_put(x->name, sizeof x->name, pname);
+ t0[n].pid = e.th32ProcessID;
+ t0[n].t = 0;
+ HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
+ e.th32ProcessID);
+ if (h) {
+ uint64_t created = 0;
+ t0[n].t = proc_time(h, &created);
+ FILETIME now;
+ GetSystemTimeAsFileTime(&now);
+ if (created)
+ x->age_s = (long)((ft64(now) - created) / 10000000);
+ PROCESS_MEMORY_COUNTERS pm = {.cb = sizeof pm};
+ if (GetProcessMemoryInfo(h, &pm, sizeof pm))
+ x->mem = pm.WorkingSetSize;
+ CloseHandle(h);
+ }
+ n++;
+ }
+ CloseHandle(snap);
+ if (!v || !t0) {
+ free(v);
+ free(t0);
+ snprintf(err, err_len, "out of memory");
+ return -1;
+ }
+ /* the processor's share: their times again after a while */
+ ULONGLONG w0 = GetTickCount64();
+ Sleep(SY_SAMPLE_MS);
+ double wall = (double)(GetTickCount64() - w0) * 10000; /* 100 ns */
+ int cpus = (int)GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
+ for (int i = 0; i < n; i++) {
+ HANDLE h =
+ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, t0[i].pid);
+ if (!h)
+ continue;
+ uint64_t t = proc_time(h, NULL);
+ CloseHandle(h);
+ if (t >= t0[i].t && t0[i].t && wall > 0 && cpus > 0)
+ v[i].cpu_pct = (double)(t - t0[i].t) * 100 / (wall * cpus);
+ }
+ free(t0);
+ qsort(v, (size_t)n, sizeof *v, strcmp(by, "memory") ? more_cpu : more_mem);
+ p->n = n < SY_PROCS ? n : SY_PROCS;
+ memcpy(p->p, v, (size_t)p->n * sizeof *v);
+ free(v);
+ for (int i = 0; i < p->n; i++) /* who: only for those shown, it costs */
+ proc_user((DWORD)p->p[i].pid, p->p[i].user, sizeof p->p[i].user);
+ return 0;
+}
+
+/* ---- the errors ---- */
+
+/* an event's text in its publisher's words, its source and its time */
+static void one_event(EVT_HANDLE ev, EVT_HANDLE ctx, struct sy_errors *e)
+{
+ DWORD used = 0, props = 0;
+ char buf[2048];
+ if (!EvtRender(ctx, ev, EvtRenderEventValues, sizeof buf, buf, &used,
+ &props))
+ return;
+ EVT_VARIANT *v = (EVT_VARIANT *)buf;
+ char who[64] = "";
+ if (v[0].Type == EvtVarTypeString)
+ utf8(v[0].StringVal, who, sizeof who);
+ long long at = 0;
+ if (v[1].Type == EvtVarTypeFileTime) /* 100 ns since 1601 */
+ at = (long long)(v[1].FileTimeVal / 10000000) - 11644473600LL;
+ wchar_t text[1024] = L"";
+ EVT_HANDLE pub =
+ v[0].Type == EvtVarTypeString
+ ? EvtOpenPublisherMetadata(NULL, v[0].StringVal, NULL, 0, 0)
+ : NULL;
+ DWORD n = 0;
+ if (!pub || !EvtFormatMessage(pub, ev, 0, 0, NULL, EvtFormatMessageEvent,
+ sizeof text / sizeof *text, text, &n))
+ wcscpy(text, L"(no text: its publisher's message is not installed)");
+ if (pub)
+ EvtClose(pub);
+ char t8[1024];
+ utf8(text, t8, sizeof t8);
+ sy_err_add(e, at, who, t8);
+}
+
+static void channel(const wchar_t *path, const wchar_t *query,
+ struct sy_errors *e)
+{
+ EVT_HANDLE q = EvtQuery(NULL, path, query,
+ EvtQueryChannelPath | EvtQueryReverseDirection);
+ if (!q)
+ return;
+ LPCWSTR fields[] = {L"Event/System/Provider/@Name",
+ L"Event/System/TimeCreated/@SystemTime"};
+ EVT_HANDLE ctx = EvtCreateRenderContext(2, fields, EvtRenderContextValues);
+ EVT_HANDLE ev[16];
+ DWORD got = 0;
+ int seen = 0;
+ while (ctx && seen < 2000 && EvtNext(q, 16, ev, 2000, 0, &got)) {
+ for (DWORD i = 0; i < got; i++) {
+ one_event(ev[i], ctx, e);
+ EvtClose(ev[i]);
+ }
+ seen += (int)got;
+ }
+ if (seen >= 2000) /* the latest first: those left are older */
+ e->cut = 1;
+ if (ctx)
+ EvtClose(ctx);
+ EvtClose(q);
+}
+
+/* the services set to start by themselves, stopped with an error */
+static void failed_services(struct sy_errors *e)
+{
+ SC_HANDLE sc = OpenSCManagerW(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE);
+ if (!sc)
+ return;
+ DWORD need = 0, count = 0, resume = 0;
+ EnumServicesStatusExW(sc, SC_ENUM_PROCESS_INFO, SERVICE_WIN32,
+ SERVICE_INACTIVE, NULL, 0, &need, &count, &resume,
+ NULL);
+ BYTE *buf = need ? malloc(need) : NULL;
+ resume = 0;
+ if (buf && EnumServicesStatusExW(sc, SC_ENUM_PROCESS_INFO, SERVICE_WIN32,
+ SERVICE_INACTIVE, buf, need, &need, &count,
+ &resume, NULL)) {
+ ENUM_SERVICE_STATUS_PROCESSW *s = (ENUM_SERVICE_STATUS_PROCESSW *)buf;
+ for (DWORD i = 0; i < count; i++) {
+ DWORD code = s[i].ServiceStatusProcess.dwWin32ExitCode;
+ if (code == 0 || code == ERROR_SERVICE_NEVER_STARTED)
+ continue;
+ SC_HANDLE h =
+ OpenServiceW(sc, s[i].lpServiceName, SERVICE_QUERY_CONFIG);
+ if (!h)
+ continue;
+ DWORD cn = 0;
+ QueryServiceConfigW(h, NULL, 0, &cn);
+ QUERY_SERVICE_CONFIGW *cfg = cn ? malloc(cn) : NULL;
+ int automatic = cfg && QueryServiceConfigW(h, cfg, cn, &cn) &&
+ cfg->dwStartType == SERVICE_AUTO_START;
+ free(cfg);
+ CloseServiceHandle(h);
+ if (!automatic)
+ continue;
+ if (e->n_failed == SY_FAILED) {
+ e->more_failed++;
+ continue;
+ }
+ utf8(s[i].lpDisplayName, e->failed[e->n_failed],
+ sizeof e->failed[0]);
+ e->failed_n[e->n_failed++] = 1;
+ }
+ }
+ free(buf);
+ CloseServiceHandle(sc);
+}
+
+int sy_get_errors(int hours, struct sy_errors *e, char *err, size_t err_len)
+{
+ (void)err, (void)err_len;
+ memset(e, 0, sizeof *e);
+ e->hours = hours;
+ sy_put(e->how, sizeof e->how, "eventlog");
+ unsigned long long ms =
+ hours > 0 ? (unsigned long long)hours * 3600000ULL : GetTickCount64();
+ wchar_t query[200];
+ swprintf(query, sizeof query / sizeof *query,
+ L"*[System[(Level=1 or Level=2) and "
+ L"TimeCreated[timediff(@SystemTime) <= %llu]]]",
+ ms);
+ channel(L"System", query, e);
+ channel(L"Application", query, e);
+ sy_err_order(e);
+ failed_services(e);
+ return 0;
+}
+
+int sy_get_updates(struct sy_updates *u, char *err, size_t err_len)
+{
+ memset(u, 0, sizeof *u);
+ snprintf(err, err_len,
+ "on Windows the updates are Windows Update's, not read here: "
+ "they are in Settings, Windows Update (and winget upgrade for "
+ "the programs installed with winget)");
+ return -1;
+}
+
+/* ---- the network ---- */
+
+static void wifi_signal(struct sy_net *n, const char *const *guids)
+{
+ HANDLE h;
+ DWORD ver;
+ if (WlanOpenHandle(2, NULL, &ver, &h) != ERROR_SUCCESS)
+ return;
+ WLAN_INTERFACE_INFO_LIST *list = NULL;
+ if (WlanEnumInterfaces(h, NULL, &list) == ERROR_SUCCESS) {
+ for (DWORD i = 0; i < list->dwNumberOfItems; i++) {
+ WLAN_INTERFACE_INFO *w = &list->InterfaceInfo[i];
+ wchar_t g[64];
+ char g8[64];
+ StringFromGUID2(&w->InterfaceGuid, g, 64);
+ utf8(g, g8, sizeof g8);
+ int k = 0;
+ while (k < n->n && _stricmp(guids[k], g8))
+ k++;
+ if (k == n->n)
+ continue;
+ DWORD sz = 0;
+ WLAN_CONNECTION_ATTRIBUTES *c = NULL;
+ if (WlanQueryInterface(h, &w->InterfaceGuid,
+ wlan_intf_opcode_current_connection, NULL,
+ &sz, (void **)&c, NULL) == ERROR_SUCCESS) {
+ n->i[k].wifi_pct =
+ (int)c->wlanAssociationAttributes.wlanSignalQuality;
+ WlanFreeMemory(c);
+ }
+ LONG *rssi = NULL;
+ if (WlanQueryInterface(h, &w->InterfaceGuid, wlan_intf_opcode_rssi,
+ NULL, &sz, (void **)&rssi,
+ NULL) == ERROR_SUCCESS) {
+ n->i[k].signal_dbm = (int)*rssi;
+ WlanFreeMemory(rssi);
+ }
+ }
+ WlanFreeMemory(list);
+ }
+ WlanCloseHandle(h, NULL);
+}
+
+static void addr_str(const SOCKET_ADDRESS *a, char *out, size_t cap)
+{
+ DWORD n = (DWORD)cap;
+ wchar_t w[64];
+ DWORD wn = 64;
+ out[0] = 0;
+ if (WSAAddressToStringW(a->lpSockaddr, (DWORD)a->iSockaddrLength, NULL, w,
+ &wn) == 0)
+ utf8(w, out, n);
+}
+
+int sy_get_net(struct sy_net *n, char *err, size_t err_len)
+{
+ memset(n, 0, sizeof *n);
+ WSADATA wsa;
+ WSAStartup(MAKEWORD(2, 2), &wsa);
+ ULONG size = 32768;
+ IP_ADAPTER_ADDRESSES *list = NULL;
+ ULONG rc = ERROR_BUFFER_OVERFLOW;
+ for (int tries = 0; rc == ERROR_BUFFER_OVERFLOW && tries < 3; tries++) {
+ free(list);
+ list = malloc(size);
+ if (!list)
+ break;
+ rc = GetAdaptersAddresses(AF_UNSPEC,
+ GAA_FLAG_INCLUDE_GATEWAYS |
+ GAA_FLAG_SKIP_MULTICAST |
+ GAA_FLAG_SKIP_ANYCAST,
+ NULL, list, &size);
+ }
+ if (!list || rc != NO_ERROR) {
+ free(list);
+ snprintf(err, err_len, "the network adapters could not be read");
+ return -1;
+ }
+ static char guid[SY_IFACES][64];
+ const char *guids[SY_IFACES];
+ for (IP_ADAPTER_ADDRESSES *a = list; a; a = a->Next) {
+ if (a->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
+ continue;
+ if (n->n == SY_IFACES) {
+ n->more++;
+ continue;
+ }
+ struct sy_iface *x = &n->i[n->n];
+ utf8(a->FriendlyName, x->name, sizeof x->name);
+ sy_put(guid[n->n], sizeof guid[0], a->AdapterName);
+ guids[n->n] = guid[n->n];
+ n->n++;
+ sy_put(x->kind, sizeof x->kind,
+ a->IfType == IF_TYPE_IEEE80211 ? "wifi"
+ : a->IfType == IF_TYPE_ETHERNET_CSMACD ? "ethernet"
+ : "virtual");
+ sy_put(x->state, sizeof x->state,
+ a->OperStatus == IfOperStatusUp ? "up"
+ : a->OperStatus == IfOperStatusDormant ? "dormant"
+ : a->OperStatus == IfOperStatusLowerLayerDown ? "lowerlayerdown"
+ : a->OperStatus == IfOperStatusDown ||
+ a->OperStatus == IfOperStatusNotPresent
+ ? "down"
+ : "unknown");
+ if (a->TransmitLinkSpeed && a->TransmitLinkSpeed != (ULONG64)-1)
+ x->speed_mbps = (long)(a->TransmitLinkSpeed / 1000000);
+ for (IP_ADAPTER_UNICAST_ADDRESS *u = a->FirstUnicastAddress;
+ u && x->n_addr < SY_ADDRS; u = u->Next)
+ addr_str(&u->Address, x->addr[x->n_addr++], sizeof x->addr[0]);
+ MIB_IF_ROW2 row = {.InterfaceLuid = a->Luid};
+ if (GetIfEntry2(&row) == NO_ERROR) {
+ x->rx = row.InOctets;
+ x->tx = row.OutOctets;
+ }
+ if (!n->gateway[0] && a->FirstGatewayAddress &&
+ a->OperStatus == IfOperStatusUp) {
+ addr_str(&a->FirstGatewayAddress->Address, n->gateway,
+ sizeof n->gateway);
+ sy_put(n->gw_iface, sizeof n->gw_iface, x->name);
+ }
+ for (IP_ADAPTER_DNS_SERVER_ADDRESS *d = a->FirstDnsServerAddress;
+ d && n->n_dns < 3 && a->OperStatus == IfOperStatusUp;
+ d = d->Next) {
+ char s[64];
+ addr_str(&d->Address, s, sizeof s);
+ int seen = 0;
+ for (int k = 0; k < n->n_dns; k++)
+ seen |= !strcmp(n->dns[k], s);
+ if (!seen && s[0])
+ sy_put(n->dns[n->n_dns++], sizeof n->dns[0], s);
+ }
+ }
+ free(list);
+ /* the virtual ones without addresses are noise */
+ int k = 0;
+ for (int i = 0; i < n->n; i++)
+ if (strcmp(n->i[i].kind, "virtual") || n->i[i].n_addr) {
+ guids[k] = guids[i];
+ n->i[k++] = n->i[i];
+ }
+ n->n = k;
+ wifi_signal(n, guids);
+ WSACleanup();
+ return 0;
+}
+
+/* ---- what fills a directory ---- */
+
+struct walk {
+ ULONGLONG end;
+ int cut;
+ long unread;
+};
+
+/* the bytes under dir (UTF-16, without the final \); reparse points (links,
+ junctions, mounted volumes) are not followed */
+static uint64_t sum(struct walk *w, const wchar_t *dir, int depth, long *files)
+{
+ wchar_t pat[1100];
+ if (_snwprintf(pat, 1100, L"%ls\\*", dir) < 0)
+ return 0;
+ WIN32_FIND_DATAW f;
+ HANDLE h = FindFirstFileExW(pat, FindExInfoBasic, &f, FindExSearchNameMatch,
+ NULL, FIND_FIRST_EX_LARGE_FETCH);
+ if (h == INVALID_HANDLE_VALUE) {
+ w->unread++;
+ return 0;
+ }
+ uint64_t total = 0;
+ unsigned tick = 0;
+ do {
+ if ((++tick & 255) == 0 && GetTickCount64() > w->end)
+ w->cut = 1;
+ if (w->cut)
+ break;
+ if (!wcscmp(f.cFileName, L".") || !wcscmp(f.cFileName, L".."))
+ continue;
+ if (f.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
+ continue;
+ if (!(f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
+ total += ((uint64_t)f.nFileSizeHigh << 32) | f.nFileSizeLow;
+ (*files)++;
+ continue;
+ }
+ if (depth >= SY_USAGE_DEPTH)
+ continue;
+ wchar_t sub[1100];
+ if (_snwprintf(sub, 1100, L"%ls\\%ls", dir, f.cFileName) > 0)
+ total += sum(w, sub, depth + 1, files);
+ } while (FindNextFileW(h, &f));
+ FindClose(h);
+ return total;
+}
+
+static int bigger(const void *a, const void *b)
+{
+ uint64_t x = ((const struct sy_entry *)a)->bytes,
+ y = ((const struct sy_entry *)b)->bytes;
+ return x < y ? 1 : x > y ? -1 : 0;
+}
+
+int sy_get_usage(const char *path, struct sy_usage *u, char *err,
+ size_t err_len)
+{
+ memset(u, 0, sizeof *u);
+ ULONGLONG t0 = GetTickCount64();
+ const char *home = sy_home();
+ if (!path || !*path)
+ path = home;
+ if (path[0] == '~' && (path[1] == '/' || path[1] == '\\' || !path[1]))
+ snprintf(u->path, sizeof u->path, "%s%s", home, path + 1);
+ else
+ sy_put(u->path, sizeof u->path, path);
+ size_t len = strlen(u->path);
+ while (len > 3 && (u->path[len - 1] == '\\' || u->path[len - 1] == '/'))
+ u->path[--len] = 0;
+ wchar_t dir[1100];
+ if (!MultiByteToWideChar(CP_UTF8, 0, u->path, -1, dir, 1100)) {
+ snprintf(err, err_len, "%s is not a path", u->path);
+ return -1;
+ }
+ size_t dl = wcslen(dir);
+ if (dl && dir[dl - 1] == L'\\') /* "C:\" */
+ dir[dl - 1] = 0;
+ ULARGE_INTEGER avail, total, free_all;
+ wchar_t probe[1104];
+ _snwprintf(probe, 1104, L"%ls\\", dir);
+ if (GetDiskFreeSpaceExW(probe, &avail, &total, &free_all)) {
+ u->fs_total = total.QuadPart;
+ u->fs_avail = avail.QuadPart;
+ }
+ wchar_t pat[1104];
+ _snwprintf(pat, 1104, L"%ls\\*", dir);
+ WIN32_FIND_DATAW f;
+ HANDLE h = FindFirstFileExW(pat, FindExInfoBasic, &f, FindExSearchNameMatch,
+ NULL, FIND_FIRST_EX_LARGE_FETCH);
+ if (h == INVALID_HANDLE_VALUE) {
+ snprintf(err, err_len, "%s cannot be read", u->path);
+ return -1;
+ }
+ struct walk w = {.end = t0 + SY_USAGE_MS};
+ int cap = 256, n = 0;
+ struct sy_entry *all = malloc((size_t)cap * sizeof *all);
+ do {
+ if (!all)
+ break;
+ if (!wcscmp(f.cFileName, L".") || !wcscmp(f.cFileName, L".."))
+ continue;
+ if (n == cap) {
+ struct sy_entry *m = realloc(all, (size_t)(cap *= 2) * sizeof *m);
+ if (!m)
+ break;
+ all = m;
+ }
+ struct sy_entry *x = &all[n++];
+ memset(x, 0, sizeof *x);
+ utf8(f.cFileName, x->name, sizeof x->name);
+ x->dir = (f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
+ if (!x->dir) {
+ x->bytes = ((uint64_t)f.nFileSizeHigh << 32) | f.nFileSizeLow;
+ x->files = 1;
+ continue;
+ }
+ if ((f.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) || w.cut)
+ continue;
+ wchar_t sub[1100];
+ if (_snwprintf(sub, 1100, L"%ls\\%ls", dir, f.cFileName) > 0)
+ x->bytes = sum(&w, sub, 1, &x->files);
+ } while (FindNextFileW(h, &f));
+ FindClose(h);
+ if (!all) {
+ snprintf(err, err_len, "out of memory");
+ return -1;
+ }
+ qsort(all, (size_t)n, sizeof *all, bigger);
+ for (int i = 0; i < n; i++) {
+ u->total += all[i].bytes;
+ u->files += all[i].files;
+ }
+ u->n = n < SY_USAGE ? n : SY_USAGE;
+ u->more = n - u->n;
+ memcpy(u->e, all, (size_t)u->n * sizeof *all);
+ free(all);
+ u->cut = w.cut;
+ u->unread = w.unread;
+ u->secs = (double)(GetTickCount64() - t0) / 1e3;
+ return 0;
+}
+#endif
diff --git a/tests/test_git_parse.c b/tests/test_git_parse.c
index ae30e93..4775bb8 100644
--- a/tests/test_git_parse.c
+++ b/tests/test_git_parse.c
@@ -9,7 +9,6 @@
* made for the purpose.
* The sources belong to the program, so they are compiled in here.
*/
-#define _GNU_SOURCE /* run.c's pipe2 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/tests/test_layout.c b/tests/test_layout.c
index 9674b6e..8058696 100644
--- a/tests/test_layout.c
+++ b/tests/test_layout.c
@@ -123,7 +123,8 @@ int main(void)
free(again);
free(it);
- /* the text given back untranslated: not used, not kept */
+ /* the text given back untranslated: asked once more, told so; then not
+ used, not kept */
translate_wind = 0;
static const char EN2[] = "Rain {{mm}} mm.\n";
int before = calls;
@@ -131,8 +132,10 @@ int main(void)
char p2[1200];
snprintf(p2, sizeof p2, "%s/janas/layouts/test2.it.%016llx.txt", dir,
(unsigned long long)glossary_mark("it", "test2", mark(EN2)));
- CHECK(!same && calls == before + 1 && access(p2, F_OK) != 0,
- "an untranslated text refused");
+ CHECK(!same && calls == before + 2 && access(p2, F_OK) != 0 &&
+ strstr(asked, "The text came back as it was, untranslated"),
+ "an untranslated text asked again, then refused (%d requests)",
+ calls - before);
free(same);
translate_wind = 1;
diff --git a/tests/test_system_parse.c b/tests/test_system_parse.c
new file mode 100644
index 0000000..bd2dac6
--- /dev/null
+++ b/tests/test_system_parse.c
@@ -0,0 +1,471 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * test_system_parse.c - janas-system's reading of Linux's texts, without
+ * reading the system, and the layouts filled with what was read. The
+ * texts are those of the development laptop (Debian 13) on 2 October
+ * 2026, cut; the btrfs subvolume and the path with a space in mountinfo,
+ * and the outputs of dnf and pacman, are written from their documentation
+ * (no such system was at hand).
+ * The sources belong to the program, so they are compiled in here.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "services/common/template.h"
+#include "services/system/data.c"
+#include "services/system/layouts.c"
+#include "services/system/read.c"
+
+/* the backend is not compiled in: the home for the paths */
+const char *sy_home(void)
+{
+ return "/home/someone";
+}
+
+static int failures;
+
+#define CHECK(c, ...) \
+ do { \
+ if (!(c)) { \
+ printf(__VA_ARGS__); \
+ printf("\n"); \
+ failures++; \
+ } \
+ } while (0)
+
+static const char S_MEMINFO[] = "MemTotal: 32280768 kB\n"
+ "MemFree: 2973200 kB\n"
+ "MemAvailable: 24510148 kB\n"
+ "Buffers: 524688 kB\n"
+ "SwapTotal: 32982012 kB\n"
+ "SwapFree: 31316232 kB\n";
+
+static const char S_STAT[] =
+ "cpu 333284235 3886676 54046493 3968942521 6156313 0 292631 0 0 0\n"
+ "cpu0 1 2 3 4 5 6 7 8 9 10\n";
+
+static const char S_PSI[] =
+ "some avg10=0.01 avg60=0.02 avg300=0.00 total=8039391441\n"
+ "full avg10=0.01 avg60=0.02 avg300=0.00 total=6399024250\n";
+
+static const char S_PID_STAT[] =
+ "2011430 (Isolated Web Co) S 1981282 1981282 1981282 0 -1 4194560 337955 "
+ "0 4 0 4475 282 0 0 20 0 35 0 198506288 3139346432 118613 "
+ "18446744073709551615 94824029778960 94824030202304 140726984299296 0 0 "
+ "0 0 69634 1082134264 0 0 0 17 6 0 0 0 0 0\n";
+
+static const char S_MOUNTINFO[] =
+ "25 31 0:23 / /proc rw,nosuid,nodev,noexec,relatime shared:12 - proc "
+ "proc rw\n"
+ "28 31 0:25 / /run rw,nosuid,nodev,noexec,relatime shared:5 - tmpfs "
+ "tmpfs rw,size=3228080k,mode=755,inode64\n"
+ "31 1 259:5 / / rw,relatime shared:1 - ext4 /dev/nvme0n1p5 "
+ "rw,errors=remount-ro,stripe=128\n"
+ "49 31 259:1 / /boot/efi rw,relatime shared:88 - vfat /dev/nvme0n1p1 "
+ "rw,fmask=0077,dmask=0077,codepage=437,iocharset=ascii,shortname=mixed,"
+ "utf8,errors=remount-ro\n"
+ "191 161 0:69 / /run/user/1000/doc rw,nosuid,nodev,relatime shared:660 "
+ "- fuse.portal portal rw,user_id=1000,group_id=1000\n"
+ /* written for the test */
+ "80 31 0:50 /@home /home rw,relatime shared:30 - btrfs /dev/sda2 rw\n"
+ "81 31 0:50 /@snap /home/snap rw,relatime shared:31 - btrfs /dev/sda2 "
+ "rw\n"
+ "90 31 8:17 / /media/someone/My\\040Disk ro,nosuid shared:40 - exfat "
+ "/dev/sdb1 ro\n";
+
+static const char S_JOURNAL[] =
+ "{\"_SYSTEMD_USER_UNIT\":\"plasma-kwin_wayland.service\",\"_SYSTEMD_UNIT\":"
+ "\"[email protected]\",\"__REALTIME_TIMESTAMP\":\"1790961552458210\","
+ "\"PRIORITY\":\"3\",\"MESSAGE\":\"PAM adding faulty module: pam_sss.so\","
+ "\"SYSLOG_IDENTIFIER\":\"kscreenlocker_greet\"}\n"
+ "{\"_SYSTEMD_UNIT\":\"[email protected]\",\"__REALTIME_TIMESTAMP\":"
+ "\"1790967655461074\",\"MESSAGE\":\"PAM unable to dlopen(pam_sss.so): "
+ "/usr/lib/security/pam_sss.so: cannot open shared object file\","
+ "\"PRIORITY\":\"3\",\"SYSLOG_IDENTIFIER\":\"kscreenlocker_greet\"}\n"
+ "{\"SYSLOG_IDENTIFIER\":\"kscreenlocker_greet\",\"MESSAGE\":\"PAM adding "
+ "faulty module: pam_sss.so\",\"__REALTIME_TIMESTAMP\":"
+ "\"1790967655464070\",\"PRIORITY\":\"3\"}\n"
+ /* a message of bytes not text: journalctl writes it as a list */
+ "{\"SYSLOG_IDENTIFIER\":\"x\",\"MESSAGE\":[80,65,77],"
+ "\"__REALTIME_TIMESTAMP\":\"1790967655464071\"}\n";
+
+static const char S_FAILED[] =
+ "[email protected] loaded failed failed "
+ "Pass systemd-coredump journal entries to relevant user for potential "
+ "DrKonqi handling\n"
+ "[email protected] loaded failed failed "
+ "Pass systemd-coredump journal entries to relevant user for potential "
+ "DrKonqi handling\n"
+ "\xe2\x97\x8f cups.service loaded failed failed CUPS Scheduler\n";
+
+static const char S_APT[] =
+ "Listing...\n"
+ "bind9-dnsutils/stable-security 1:9.20.29-1~deb13u1 amd64 [upgradable "
+ "from: 1:9.20.26-1~deb13u1]\n"
+ "chromium-common/stable-security 154.0.8037.92-1~deb13u1 amd64 "
+ "[upgradable from: 152.0.7977.82-1~deb13u1]\n"
+ "tzdata/stable 2026b-0+deb13u1 all [upgradable from: 2026a-0+deb13u1]\n";
+
+static const char S_DNF[] = "\n"
+ "kernel.x86_64 6.11.4-301.fc41 updates\n"
+ "vim-minimal.x86_64 2:9.1.785-1.fc41 updates\n"
+ "Obsoleting Packages\n"
+ "grub2-tools.x86_64 1:2.12-10.fc41 updates\n";
+
+static const char S_PACMAN[] = "linux 6.11.3.arch1-1 -> 6.11.4.arch1-1\n"
+ "firefox 131.0.2-1 -> 131.0.3-1\n";
+
+static const char S_WIRELESS[] =
+ "Inter-| sta-| Quality | Discarded packets | "
+ "Missed | WE\n"
+ " face | tus | link level noise | nwid crypt frag retry misc | "
+ "beacon | 22\n"
+ "wlp0s20f3: 0000 50. -60. -256 0 0 0 343 10299 "
+ " 0\n";
+
+static const char S_ROUTE[] =
+ "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\t"
+ "Window\tIRTT\n"
+ "wlp0s20f3\t0001A8C0\t00000000\t0001\t0\t0\t600\t00FFFFFF\t0\t0\t0\n"
+ "wlp0s20f3\t00000000\t0101A8C0\t0003\t0\t0\t600\t00000000\t0\t0\t0\n";
+
+static const char S_OS[] = "PRETTY_NAME=\"Debian GNU/Linux 13 (trixie)\"\n"
+ "NAME=\"Debian GNU/Linux\"\n";
+
+/* the layout filled with the data d; the text, or "" (counted) */
+static char *fill(const char *layout, struct janas_buf *d)
+{
+ static char out[16384];
+ char why[200];
+ struct janas_json_doc *doc = janas_json_parse(d->p, d->n, why, sizeof why);
+ CHECK(doc, "the data is not JSON: %s\n%.*s", why, (int)d->n, d->p);
+ out[0] = 0;
+ if (doc) {
+ struct janas_buf o = {0};
+ char err[200];
+ int r = janas_tpl_render(layout, strlen(layout), janas_json_root(doc),
+ &o, err, sizeof err);
+ CHECK(r == 0, "not filled: %s", err);
+ if (r == 0 && o.p)
+ snprintf(out, sizeof out, "%.*s", (int)o.n, o.p);
+ janas_buf_free(&o);
+ janas_json_free(doc);
+ }
+ janas_buf_free(d);
+ return out;
+}
+
+static void test_status(void)
+{
+ struct sy_status s;
+ memset(&s, 0, sizeof s);
+ CHECK(sy_read_meminfo(S_MEMINFO, &s) == 0, "meminfo");
+ CHECK(s.mem_total == 32280768ull * 1024 &&
+ s.mem_avail == 24510148ull * 1024,
+ "memory %llu %llu", (unsigned long long)s.mem_total,
+ (unsigned long long)s.mem_avail);
+ CHECK(s.swap_total == 32982012ull * 1024, "swap");
+ uint64_t busy, all, sys;
+ CHECK(sy_read_cpu_ticks(S_STAT, &busy, &all, &sys) == 0, "stat");
+ CHECK(sys == 54046493ull + 292631, "kernel ticks");
+ CHECK(all == 333284235ull + 3886676 + 54046493 + 3968942521ull + 6156313 +
+ 292631,
+ "all ticks %llu", (unsigned long long)all);
+ CHECK(busy == all - 3968942521ull - 6156313, "busy ticks");
+ CHECK(sy_read_loadavg("0.11 0.36 0.47 1/1628 2650727\n", s.load) == 0 &&
+ s.load[2] == 0.47,
+ "loadavg");
+ CHECK(sy_read_psi(S_PSI) == 0.01, "psi");
+ CHECK(sy_read_psi("") == -1, "psi absent");
+ CHECK(sy_read_os_release(S_OS, s.os, sizeof s.os) == 0 &&
+ !strcmp(s.os, "Debian GNU/Linux 13 (trixie)"),
+ "os-release: %s", s.os);
+ CHECK(!strcmp(sy_sensor_kind("coretemp"), "cpu") &&
+ !strcmp(sy_sensor_kind("nvme"), "disk") &&
+ !strcmp(sy_sensor_kind("spd5118"), "memory") &&
+ !strcmp(sy_sensor_kind("iwlwifi_1"), "wifi") &&
+ !strcmp(sy_sensor_kind("acpitz"), "board"),
+ "sensor kinds");
+
+ /* a whole status, as the backend would give it */
+ snprintf(s.host, sizeof s.host, "babay");
+ snprintf(s.kernel, sizeof s.kernel, "6.12.107+deb13-amd64");
+ snprintf(s.cpu, sizeof s.cpu, "Intel(R) Core(TM) Ultra 7 155H");
+ s.cpus = 22;
+ s.uptime_s = 22 * 86400 + 23 * 3600 + 28 * 60;
+ s.has_load = 1;
+ s.cpu_pct = 4.4;
+ s.psi_cpu = 30, s.psi_mem = 0, s.psi_io = 0.5;
+ CHECK(sy_read_mountinfo(S_MOUNTINFO, &s.disks) == 0, "mountinfo");
+ s.disks.d[0].total = 900ull << 30, s.disks.d[0].avail = 50ull << 30;
+ s.bat = (struct sy_battery){.present = 1,
+ .pct = 80,
+ .mains = 0,
+ .state = "discharging",
+ .minutes = 135,
+ .health = 75};
+ s.t[0] = (struct sy_temp){.kind = "cpu", .c = 106, .high = 110};
+ s.t[1] = (struct sy_temp){.kind = "disk", .c = 31.85, .high = 83.85};
+ s.n_temps = 2;
+ struct janas_buf d = {0};
+ sy_status_data(&d, &s);
+ const char *t = fill(SY_STATUS_LAYOUT, &d);
+ CHECK(strstr(t, "babay: Debian GNU/Linux 13 (trixie), 6.12.107"), "%s", t);
+ CHECK(strstr(t, "on for 22 d 23 h 28 min."), "uptime:\n%s", t);
+ CHECK(strstr(t, "22 threads, 4% in use; load 0.11, 0.36, 0.47"),
+ "processor:\n%s", t);
+ CHECK(strstr(t, "Memory: 7.4 GB used of 30.8 GB (24%), 23.4 GB "
+ "available; swap: 1.6 GB of 31.5 GB."),
+ "memory:\n%s", t);
+ CHECK(strstr(t, "Waiting, of the last 10 seconds: for the processor 30%"),
+ "pressure:\n%s", t);
+ CHECK(strstr(t, " /: 850 GB of 900 GB (94%), 50 GB free - nearly full\n"),
+ "disk:\n%s", t);
+ CHECK(strstr(t, "Battery: 80%, on battery, 2 h 15 min left; capacity: 75% "
+ "of what it was new."),
+ "battery:\n%s", t);
+ CHECK(strstr(t, "Temperatures:\n processor: 106 °C, near its limit of "
+ "110 °C\n disk: 32 °C\n"),
+ "temperatures:\n%s", t);
+ sy_status_data(&d, &s);
+ t = fill(SY_STATUS_BRIEF, &d);
+ CHECK(strstr(t, "/ 94% (50 GB free, NEARLY FULL)") &&
+ strstr(t, "cpu 106 C NEAR ITS LIMIT") &&
+ strstr(t, ", worn (75%)"),
+ "status brief:\n%s", t);
+}
+
+static void test_disks(void)
+{
+ struct sy_disks d;
+ sy_read_mountinfo(S_MOUNTINFO, &d);
+ /* proc, tmpfs and the portal out; the second btrfs subvolume too */
+ CHECK(d.n == 4, "disks: %d", d.n);
+ CHECK(d.n == 4 && !strcmp(d.d[0].mount, "/") &&
+ !strcmp(d.d[0].fs, "ext4") &&
+ !strcmp(d.d[0].dev, "/dev/nvme0n1p5") && !d.d[0].ro,
+ "the root");
+ CHECK(d.n == 4 && !strcmp(d.d[2].mount, "/home"), "btrfs once");
+ CHECK(d.n == 4 && !strcmp(d.d[3].mount, "/media/someone/My Disk") &&
+ d.d[3].ro,
+ "the space in a path, read only: %s", d.d[3].mount);
+ for (int i = 0; i < d.n; i++)
+ d.d[i].total = 100ull << 30, d.d[i].avail = 25ull << 30;
+ struct janas_buf b = {0};
+ sy_disks_data(&b, &d);
+ const char *t = fill(SY_DISKS_LAYOUT, &b);
+ CHECK(strstr(t, " /media/someone/My Disk (/dev/sdb1, exfat, read only): "
+ "75 GB used of 100 GB (75%), 25 GB free\n"),
+ "disks layout:\n%s", t);
+}
+
+static void test_procs(void)
+{
+ char name[64];
+ uint64_t ticks, start;
+ int threads;
+ CHECK(sy_read_pid_stat(S_PID_STAT, name, sizeof name, &ticks, &threads,
+ &start) == 0,
+ "pid stat");
+ CHECK(!strcmp(name, "Isolated Web Co") && ticks == 4475 + 282 &&
+ threads == 35 && start == 198506288,
+ "pid stat: %s %llu %d %llu", name, (unsigned long long)ticks, threads,
+ (unsigned long long)start);
+ struct sy_procs p;
+ memset(&p, 0, sizeof p);
+ snprintf(p.by, sizeof p.by, "cpu");
+ p.total = 412, p.matched = 412, p.n = 2;
+ p.mem_total = 32ull << 30;
+ p.p[0] = (struct sy_proc){.pid = 2011430,
+ .threads = 35,
+ .name = "Isolated Web Co",
+ .user = "someone",
+ .cpu_pct = 12.34,
+ .mem = 463ull << 20,
+ .age_s = 3 * 3600 + 5 * 60};
+ p.p[1] = (struct sy_proc){.pid = 1, .name = "systemd", .user = "root"};
+ struct janas_buf b = {0};
+ sy_procs_data(&b, &p);
+ const char *t = fill(SY_PROCS_LAYOUT, &b);
+ CHECK(strstr(t, "The processes using the most processor, of 412:\n"
+ " Isolated Web Co (pid 2011430, someone): processor "
+ "12.3%, memory 463 MB (1.4%), running for 3 h 5 min\n"),
+ "processes:\n%s", t);
+ p.n = p.matched = 0;
+ snprintf(p.name, sizeof p.name, "firefox");
+ sy_procs_data(&b, &p);
+ t = fill(SY_PROCS_LAYOUT, &b);
+ CHECK(strstr(t, "Processes with \"firefox\" in their name: 0 of 412:\n"
+ " none.\n"),
+ "none:\n%s", t);
+}
+
+static void test_errors(void)
+{
+ struct sy_errors e;
+ memset(&e, 0, sizeof e);
+ sy_read_journal(S_JOURNAL, sizeof S_JOURNAL - 1, &e);
+ CHECK(e.total == 3 && e.n == 2, "journal: %d entries, %d kinds", e.total,
+ e.n);
+ sy_err_order(&e);
+ CHECK(e.n == 2 && e.e[0].count == 2 &&
+ !strcmp(e.e[0].who, "kscreenlocker_greet") &&
+ e.e[0].at == 1790967655,
+ "the same message counted, its latest time");
+ sy_read_failed(S_FAILED, &e);
+ CHECK(e.n_failed == 2 &&
+ !strcmp(e.failed[0], "[email protected]") &&
+ e.failed_n[0] == 2 && !strcmp(e.failed[1], "cups.service"),
+ "failed: %d %s", e.n_failed, e.failed[0]);
+ e.user_only = 1;
+ struct janas_buf b = {0};
+ sy_errors_data(&b, &e);
+ const char *t = fill(SY_ERRORS_LAYOUT, &b);
+ CHECK(strstr(t, "Errors since the computer started: 3.\nOnly those of "
+ "your own programs and session"),
+ "errors head:\n%s", t);
+ CHECK(strstr(t, " kscreenlocker_greet (2 times): PAM adding faulty module: "
+ "pam_sss.so\n"),
+ "errors item:\n%s", t);
+ CHECK(strstr(t, "Services that failed:\n "
+ "[email protected] (2 times)\n "
+ "cups.service\n"),
+ "failed services:\n%s", t);
+
+ /* a core dump: its first line, the same but for the numbers counted
+ once */
+ memset(&e, 0, sizeof e);
+ sy_err_add(&e, 100, "systemd-coredump",
+ "Process 2992988 (sb) of user 1000 dumped core.\n\nModule "
+ "/home/x/sb without build-id.");
+ sy_err_add(&e, 200, "systemd-coredump",
+ "Process 2993006 (sb) of user 1000 dumped core.\n\nModule");
+ sy_err_add(&e, 150, "systemd-coredump",
+ "Process 2990885 (r11g) of user 1000 dumped core.");
+ CHECK(e.n == 2 && e.e[0].count == 2 && e.e[0].at == 200 &&
+ !strcmp(e.e[0].text,
+ "Process 2993006 (sb) of user 1000 dumped core."),
+ "core dumps: %d kinds, %s", e.n, e.e[0].text);
+
+ /* more kinds than kept: the oldest go */
+ memset(&e, 0, sizeof e);
+ for (int i = 0; i < SY_ERRS + 5; i++) {
+ char text[32];
+ snprintf(text, sizeof text, "error %c", 'A' + i);
+ sy_err_add(&e, 1000 + i, "p", text);
+ }
+ sy_err_order(&e);
+ CHECK(e.n == SY_ERRS && e.more == 5 && e.total == SY_ERRS + 5 &&
+ e.e[0].at == 1000 + SY_ERRS + 4,
+ "the latest kept: %d more %d", e.n, e.more);
+}
+
+static void test_updates(void)
+{
+ struct sy_updates u;
+ memset(&u, 0, sizeof u);
+ sy_read_apt(S_APT, &u);
+ CHECK(u.total == 3 && u.security == 2 &&
+ !strcmp(u.u[0].name, "bind9-dnsutils") &&
+ !strcmp(u.u[0].to, "1:9.20.29-1~deb13u1") &&
+ !strcmp(u.u[0].from, "1:9.20.26-1~deb13u1") && !u.u[2].security,
+ "apt: %d %d %s", u.total, u.security, u.u[0].name);
+ struct janas_buf b = {0};
+ sy_updates_data(&b, &u);
+ const char *t = fill(SY_UPDATES_LAYOUT, &b);
+ CHECK(strstr(t, "Updates available: 3, 2 of them for security, by apt's "
+ "list.\n"),
+ "updates head:\n%s", t);
+ CHECK(strstr(t, " tzdata 2026a-0+deb13u1 -> 2026b-0+deb13u1\n") &&
+ strstr(t, "fetched again with: sudo apt update"),
+ "updates:\n%s", t);
+ memset(&u, 0, sizeof u);
+ sy_read_dnf(S_DNF, &u);
+ CHECK(u.total == 2 && !strcmp(u.u[0].name, "kernel") &&
+ !strcmp(u.u[1].to, "2:9.1.785-1.fc41"),
+ "dnf: %d %s", u.total, u.u[0].name);
+ memset(&u, 0, sizeof u);
+ sy_read_pacman(S_PACMAN, &u);
+ CHECK(u.total == 2 && !strcmp(u.u[1].name, "firefox") &&
+ !strcmp(u.u[1].from, "131.0.2-1") &&
+ !strcmp(u.u[1].to, "131.0.3-1"),
+ "pacman: %d", u.total);
+}
+
+static void test_net(void)
+{
+ int dbm = 0, q = 0;
+ CHECK(sy_read_wireless(S_WIRELESS, "wlp0s20f3", &dbm, &q) == 0 &&
+ dbm == -60 && q == 71,
+ "wireless %d %d", dbm, q);
+ CHECK(sy_read_wireless(S_WIRELESS, "wlan1", &dbm, &q) == -1,
+ "no such interface");
+ struct sy_net n;
+ memset(&n, 0, sizeof n);
+ CHECK(sy_read_route(S_ROUTE, n.gateway, sizeof n.gateway, n.gw_iface,
+ sizeof n.gw_iface) == 0 &&
+ !strcmp(n.gateway, "192.168.1.1") &&
+ !strcmp(n.gw_iface, "wlp0s20f3"),
+ "route: %s %s", n.gateway, n.gw_iface);
+ sy_read_resolv("# x\nnameserver 1.1.1.1\nnameserver 1.0.0.1\n", &n);
+ CHECK(n.n_dns == 2 && !strcmp(n.dns[1], "1.0.0.1"), "resolv");
+ n.n = 1;
+ n.i[0] = (struct sy_iface){.name = "wlp0s20f3",
+ .kind = "wifi",
+ .state = "up",
+ .addr = {"192.168.1.20"},
+ .n_addr = 1,
+ .signal_dbm = -60,
+ .wifi_pct = 71,
+ .rx = 3ull << 30,
+ .tx = 200ull << 20};
+ struct janas_buf b = {0};
+ sy_net_data(&b, &n);
+ const char *t = fill(SY_NET_LAYOUT, &b);
+ CHECK(strstr(t, "wlp0s20f3 (Wi-Fi, connected), the way out to the "
+ "internet: 192.168.1.20\n signal: -60 dBm (71%)\n "
+ "received 3 GB, sent 200 MB\n"),
+ "network:\n%s", t);
+ CHECK(strstr(t, "Gateway: 192.168.1.1; name servers: 1.1.1.1 1.0.0.1."),
+ "gateway:\n%s", t);
+}
+
+static void test_usage(void)
+{
+ struct sy_usage u;
+ memset(&u, 0, sizeof u);
+ snprintf(u.path, sizeof u.path, "/home/someone");
+ u.total = 120ull << 30, u.fs_total = 900ull << 30, u.fs_avail = 50ull << 30;
+ u.files = 123456, u.n = 2, u.more = 30, u.cut = 1, u.secs = 8.04;
+ u.e[0] = (struct sy_entry){
+ .name = ".cache", .bytes = 60ull << 30, .files = 100000, .dir = 1};
+ u.e[1] =
+ (struct sy_entry){.name = "film.mkv", .bytes = 4ull << 30, .files = 1};
+ struct janas_buf b = {0};
+ sy_usage_data(&b, &u);
+ const char *t = fill(SY_USAGE_LAYOUT, &b);
+ CHECK(strstr(t, "~: 120 GB in 123456 files, at least: the time ran out "
+ "after 8 s; the disk has 50 GB free of 900 GB.\n"
+ " 60 GB (50%) .cache/, 100000 files\n"
+ " 4 GB (3%) film.mkv\n ... and 30 more entries.\n"),
+ "usage:\n%s", t);
+}
+
+int main(void)
+{
+ test_status();
+ test_disks();
+ test_procs();
+ test_errors();
+ test_updates();
+ test_net();
+ test_usage();
+ if (failures) {
+ printf("test_system_parse: %d failures\n", failures);
+ return 1;
+ }
+ printf("test_system_parse: ok\n");
+ return 0;
+}