Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

Monitor → Processes: stop a process (Quit / Force Quit) and Get Info

Federico Pereira6b4aeb651ad2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 00aee05..99b367d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,17 @@ of the matching [GitHub release](https://github.com/lordbasex/LordOS/releases),
### Added
+- **Monitor → Processes: stop a process and Get Info.** Select a row and use the new Stop and
+ Info buttons, the right-click menu, a double click, ❖/Ctrl+I or Delete. Stop asks first, with
+ **Quit** (SIGTERM), **Force Quit** (SIGKILL) and Cancel. Your own processes are signalled by the
+ session itself with `pidfd_send_signal` after checking the process's start time, so a reused PID
+ is never hit; another user's or root's need an administrator and go through two new fixed,
+ validated root helper actions (`proc-signal`, `proc-info`). PID 1, kernel threads, your
+ session, LordOS's services and helpers and PipeWire can't be stopped: the sheet explains why.
+ Get Info shows memory (real, virtual, shared, private, proportional), statistics (parent, group,
+ CPU time, threads, context switches, page faults, start time, nice, control group and LordOS
+ restrictions), open files and ports (with the addresses of each socket), the executable and the
+ command line, updated every second ([docs/MONITOR.md](docs/MONITOR.md#process-actions-081)).
- **Settings → Sharing → Remote login (SSH).** A new switch, off by default on every install,
turns the standard SSH server on and off for good (`systemctl enable --now` / `disable --now`).
The first time, it installs `openssh-server` through the package engine (the Store's path). The
diff --git a/apps/monitor/Processes.jsx b/apps/monitor/Processes.jsx
new file mode 100644
index 0000000..c127d09
--- /dev/null
+++ b/apps/monitor/Processes.jsx
@@ -0,0 +1,480 @@
+// Processes.jsx — the Processes tab: the table, and the actions on a process (docs/MONITOR.md,
+// "Process actions"): Stop (Quit = SIGTERM, Force Quit = SIGKILL) and Get Info (memory,
+// statistics, open files and ports), from the toolbar, a right-click menu, a double click and the
+// keyboard (⌘/Ctrl+I, Delete).
+//
+// The user's own processes are signalled by lord-server itself (lord.monitor.signal); another
+// user's or root's go through the root helper's proc-signal / proc-info (administrators only).
+// Both check the process's start time, so a PID reused meanwhile is never hit, and both refuse
+// the protected ones (PID 1, kernel threads, the session, LordOS's services and helpers,
+// PipeWire), which the table marks with `prot`.
+import {
+ View, Text, ScrollView, Segmented, SearchField, ToolbarButton, Button, GroupBox, FormRow, typeScale, spacing, useTheme, useLocale,
+ useStore, useSettings, useKeyboard, createStore, monitor, monitorProcesses, monitorDetail, firewall, firewallState, formatNumber,
+ formatDate, formatTime, addListener,
+} from '@lordos/sdk';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { fmt, AppGlyph, Table, Cell } from './index.jsx';
+
+const RED = '#ff453a';
+
+// What is open over the window: the selected row, the context menu, the stop sheet and Get Info.
+const ui = createStore({ sel: null, menu: null, stop: null, info: null });
+const put = (p) => ui.set((s) => ({ ...s, ...p }));
+const keyOf = (p) => (p ? `${p.pid}:${p.st}` : '');
+const layerRoot = { current: null }; // the window-sized box the layers are placed in
+
+let adminCache = null;
+const isAdmin = () => {
+ if (adminCache == null) { try { adminCache = !!lord.system.info().admin; } catch (e) { adminCache = false; } }
+ return adminCache;
+};
+
+const myUid = (procs) => procs?.list.find((p) => p.self)?.uid;
+const procLabel = (tr, p) => (p.app === 'lordos' ? tr('monitor.lordos') : p.name);
+const findProc = (procs, sel) => (sel ? procs?.list.find((p) => p.pid === sel.pid && p.st === sel.st) || null : null);
+
+// ---- icons (drawn: a circle with a cross, and a circled "i") ----
+
+function StopGlyph({ color }) {
+ return (
+ <View style={{ width: 16, height: 16, borderRadius: 8, border: `1.5px solid ${color}`, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 9, fontWeight: 700, color, marginTop: -1 }}>✕</Text>
+ </View>
+ );
+}
+
+function InfoGlyph({ color }) {
+ return (
+ <View style={{ width: 16, height: 16, borderRadius: 8, border: `1.5px solid ${color}`, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 10, fontWeight: 700, color, marginTop: -1 }}>i</Text>
+ </View>
+ );
+}
+
+// ---- actions ----
+
+const openStop = (p) => { if (p) put({ stop: { pid: p.pid, st: p.st }, menu: null }); };
+const openInfo = (p) => { if (p) put({ info: { pid: p.pid, st: p.st }, sel: { pid: p.pid, st: p.st }, menu: null }); };
+
+// ---- the tab ----
+
+export function ProcessesTab() {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const procs = useStore(monitorProcesses);
+ const state = useStore(ui);
+ const [q, setQ] = useState('');
+ const [mine, setMine] = useState('mine');
+ const [sort, setSort] = useState({ key: 'cpu', dir: -1 });
+ const me = myUid(procs);
+ const cols = [
+ { key: 'name', label: tr('monitor.process'), flex: 1, sort: true },
+ { key: 'cpu', label: tr('monitor.cpuPct'), width: 80, num: true, sort: true },
+ { key: 'rss', label: tr('monitor.memory'), width: 96, num: true, sort: true },
+ { key: 'threads', label: tr('monitor.threads'), width: 64, num: true, sort: true },
+ { key: 'pid', label: tr('monitor.pid'), width: 72, num: true, sort: true },
+ { key: 'user', label: tr('monitor.user'), width: 96, sort: true },
+ ];
+ const needle = q.trim().toLowerCase();
+ const list = useMemo(() => {
+ if (!procs) return [];
+ const k = sort.key;
+ const label = (p) => procLabel(tr, p);
+ return procs.list.filter((p) => (mine === 'all' || p.uid === me) && (!needle || `${p.name} ${p.cmd} ${p.appName || ''} ${p.pid}`.toLowerCase().includes(needle)))
+ .sort((a, b) => {
+ const va = k === 'name' ? label(a).toLowerCase() : a[k], vb = k === 'name' ? label(b).toLowerCase() : b[k];
+ return (va < vb ? -1 : va > vb ? 1 : a.pid - b.pid) * sort.dir;
+ });
+ }, [procs, mine, me, needle, sort]);
+ // the selection only counts while its row is visible (filters and search hide it)
+ const selected = state.sel ? list.slice(0, 150).find((p) => p.pid === state.sel.pid && p.st === state.sel.st) || null : null;
+ const overlay = !!(state.stop || state.info || state.menu);
+
+ useKeyboard((e) => {
+ if (state.menu) { if (e.key === 'Escape') put({ menu: null }); return; }
+ if (state.stop) { if (e.key === 'Escape') put({ stop: null }); return; }
+ if (state.info) { if (e.key === 'Escape') put({ info: null }); return; }
+ const k = String(e.base || e.key || '').toLowerCase();
+ if ((e.meta || e.ctrl) && k === 'i') { openInfo(selected); return; }
+ if (e.key === 'Delete' || ((e.meta || e.ctrl) && e.key === 'Backspace')) { openStop(selected); return; }
+ if (e.key === 'Enter' && selected) { openInfo(selected); return; }
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ const shown = list.slice(0, 150);
+ const i = shown.findIndex((p) => keyOf(p) === keyOf(selected));
+ const j = Math.max(0, Math.min(shown.length - 1, i < 0 ? 0 : i + (e.key === 'ArrowDown' ? 1 : -1)));
+ if (shown[j]) put({ sel: { pid: shown[j].pid, st: shown[j].st } });
+ }
+ });
+
+ if (!procs) return <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.loading')}</Text>;
+ const shown = list.slice(0, 150);
+ const totalCpu = procs.list.reduce((a, p) => a + p.cpu, 0);
+ const onContext = (p, ev) => {
+ const at = layerRoot.current && ev?.local ? ev.local(layerRoot.current) : { x: ev?.x || 0, y: ev?.y || 0 };
+ put({ sel: { pid: p.pid, st: p.st }, menu: { pid: p.pid, st: p.st, x: at.x, y: at.y } });
+ };
+ return (
+ <>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10, zIndex: 10 }}>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text }}>{tr('monitor.processes')}</Text>
+ <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.procCount', { count: procs.total })}</Text>
+ <View style={{ flex: 1 }} />
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.xs }}>
+ <ToolbarButton icon={<StopGlyph color={selected ? t.text : t.textDim} />} title={tr('monitor.proc.stopTip')} disabled={!selected || overlay}
+ onClick={() => openStop(selected)} />
+ <ToolbarButton icon={<InfoGlyph color={selected ? t.text : t.textDim} />} title={tr('monitor.proc.infoTip')} disabled={!selected || overlay}
+ onClick={() => openInfo(selected)} />
+ </View>
+ <Segmented value={mine} onChange={setMine} options={[['mine', tr('monitor.mine')], ['all', tr('monitor.all')]]} />
+ <SearchField value={q} onChange={setQ} placeholder={tr('monitor.search')} width={200} />
+ </View>
+ <Table cols={cols} sort={sort} onSort={(key) => setSort((s0) => ({ key, dir: s0.key === key ? -s0.dir : key === 'name' || key === 'user' || key === 'pid' ? 1 : -1 }))}
+ rows={shown.map((p, i) => {
+ const on = keyOf(p) === keyOf(selected);
+ const fg = on ? '#fff' : null, dim = on ? 'rgba(255,255,255,0.82)' : t.textDim;
+ return (
+ <View key={p.pid} onMouseDown={() => put({ sel: { pid: p.pid, st: p.st } })} onDoubleClick={() => openInfo(p)} onContextMenu={(ev) => onContext(p, ev)}
+ style={{ flexDirection: 'row', height: 26, alignItems: 'center', paddingHorizontal: 10, backgroundColor: on ? t.accent : i % 2 ? t.hover : 'transparent' }}>
+ <Cell col={cols[0]}><AppGlyph item={p} /><Text style={{ fontSize: 12, color: fg || t.text, whiteSpace: 'nowrap' }}>{procLabel(tr, p)}</Text>
+ {p.appName && p.appName !== p.name ? <Text style={{ fontSize: 11, color: dim, whiteSpace: 'nowrap' }}>{p.appName}</Text> : null}</Cell>
+ <Cell col={cols[1]} color={fg} bold={p.cpu > 0.5}>{formatNumber(p.cpu * 100, 1)}</Cell>
+ <Cell col={cols[2]} color={fg}>{fmt.mem(p.rss)}</Cell>
+ <Cell col={cols[3]} color={dim}>{formatNumber(p.threads, 0)}</Cell>
+ <Cell col={cols[4]} color={dim}>{String(p.pid)}</Cell>
+ <Cell col={cols[5]} color={dim}>{p.user}</Cell>
+ </View>
+ );
+ })} />
+ <Text style={{ fontSize: 11, color: t.textDim }}>{tr('monitor.procFoot', { shown: shown.length, count: list.length, cpu: formatNumber(totalCpu * 100, 0) })}</Text>
+ </>
+ );
+}
+
+// ---- layers over the window: the context menu, the stop sheet and Get Info ----
+
+export function ProcessLayers({ active }) {
+ const state = useStore(ui);
+ const procs = useStore(monitorProcesses);
+ const root = useRef(null);
+ layerRoot.current = root.current;
+ useEffect(() => { layerRoot.current = root.current; });
+ // leaving the tab closes everything (and stops following the process)
+ useEffect(() => { if (!active) put({ menu: null, stop: null, info: null }); }, [active]);
+ const menuP = state.menu ? findProc(procs, state.menu) : null;
+ return (
+ <>
+ <View ref={root} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, pointerEvents: 'none' }} />
+ {active && state.info ? <InfoSheet key={keyOf(state.info)} want={state.info} /> : null}
+ {active && state.stop ? <StopSheet want={state.stop} /> : null}
+ {active && menuP ? <RowMenu p={menuP} x={state.menu.x} y={state.menu.y} /> : null}
+ </>
+ );
+}
+
+function bounds() {
+ try { const l = lord.getLayout(layerRoot.current.id); return { w: l[2], h: l[3] }; } catch (e) { return { w: 900, h: 580 }; }
+}
+
+function RowMenu({ p, x, y }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const ref = useRef(null);
+ const [hover, setHover] = useState(-1);
+ useEffect(() => addListener('pointerdown', (e) => {
+ const n = ref.current;
+ if (!n) return;
+ const [bx, by, bw, bh] = lord.getLayout(n.id);
+ if (!(e.x >= bx && e.x <= bx + bw && e.y >= by && e.y <= by + bh)) put({ menu: null });
+ }), []);
+ const items = [
+ { label: tr('monitor.proc.getInfo'), hint: '❖I', onClick: () => openInfo(p) },
+ '-',
+ { label: tr('monitor.proc.quitMenu'), hint: tr('monitor.proc.deleteKey'), danger: true, onClick: () => openStop(p) },
+ ];
+ const width = 220, h = items.reduce((s, it) => s + (it === '-' ? 9 : 24), 10);
+ const b = bounds();
+ const left = Math.max(4, Math.min(x, b.w - width - 4)), top = Math.max(4, Math.min(y, b.h - h - 4));
+ return (
+ <View ref={ref} style={{ position: 'absolute', left, top, width, paddingVertical: 5, borderRadius: 8, zIndex: 300,
+ backgroundColor: t.mode === 'dark' ? '#2c2c31' : '#ffffff', border: `1px solid ${t.separator}`, boxShadow: '0 10px 30px rgba(0,0,0,0.35)' }}>
+ {items.map((it, i) => {
+ if (it === '-') return <View key={i} style={{ height: 1, marginVertical: 4, marginHorizontal: 8, backgroundColor: t.separator }} />;
+ const on = hover === i;
+ return (
+ <View key={i} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(-1)} onClick={() => { put({ menu: null }); it.onClick(); }}
+ style={{ height: 24, marginHorizontal: 5, paddingHorizontal: 10, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 8, backgroundColor: on ? t.accent : 'transparent' }}>
+ <Text style={{ flex: 1, fontSize: 13, color: on ? '#fff' : it.danger ? RED : t.text, whiteSpace: 'nowrap', textAlign: 'start' }}>{it.label}</Text>
+ <Text style={{ fontSize: 11, color: on ? '#fff' : t.textDim, direction: 'ltr' }}>{it.hint}</Text>
+ </View>
+ );
+ })}
+ </View>
+ );
+}
+
+// A sheet centered over the window (docs/DESIGN.md "Dialogs and sheets").
+function Sheet({ width, height, children, z = 200 }) {
+ const t = useTheme();
+ const b = bounds();
+ return (
+ <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, zIndex: z, alignItems: 'center', justifyContent: 'center',
+ backgroundColor: 'rgba(0,0,0,0.28)' }}>
+ <View style={{ width: Math.min(width, b.w - 32), height: height ? Math.min(height, b.h - 32) : undefined, padding: spacing.xl, gap: spacing.m, borderRadius: 12,
+ backgroundColor: t.mode === 'dark' ? '#2a2a2f' : '#ffffff', border: `1px solid ${t.separator}`, boxShadow: '0 18px 50px rgba(0,0,0,0.35)' }}>
+ {children}
+ </View>
+ </View>
+ );
+}
+
+function StopSheet({ want }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const procs = useStore(monitorProcesses);
+ const [busy, setBusy] = useState(false);
+ const [err, setErr] = useState(null);
+ const [p0] = useState(() => findProc(procs, want)); // keep the name if it exits meanwhile
+ const p = findProc(procs, want) || p0;
+ if (!p) return null;
+ const own = p.uid === myUid(procs);
+ const close = () => put({ stop: null });
+ const name = procLabel(tr, p);
+ const run = async (kind) => {
+ setBusy(true);
+ setErr(null);
+ try { await monitor.stopProcess(p, kind, { own }); close(); } catch (e) { setErr(e?.message || String(e)); setBusy(false); }
+ };
+ let title, body, actions;
+ if (p.prot || (!own && !isAdmin())) {
+ title = tr('monitor.proc.cantStop', { name });
+ body = p.prot ? tr(`monitor.proc.why.${p.prot}`) : tr('monitor.proc.needAdmin', { user: p.user });
+ actions = <><View style={{ flex: 1 }} /><Button primary label={tr('monitor.proc.ok')} onClick={close} /></>;
+ } else {
+ title = tr('monitor.proc.confirm', { name });
+ body = own ? tr('monitor.proc.confirmHint') : tr('monitor.proc.confirmOther', { user: p.user });
+ actions = (
+ <>
+ <Button label={tr('monitor.proc.cancel')} disabled={busy} onClick={close} />
+ <View style={{ flex: 1 }} />
+ <Button destructive label={tr('monitor.proc.forceQuit')} disabled={busy} onClick={() => run('KILL')} />
+ <Button primary label={tr('monitor.proc.quit')} disabled={busy} onClick={() => run('TERM')} />
+ </>
+ );
+ }
+ return (
+ <Sheet width={440} z={250}>
+ <View style={{ flexDirection: 'row', gap: spacing.m, alignItems: 'flex-start' }}>
+ <AppGlyph item={p} size={32} />
+ <View style={{ flex: 1, gap: 6, minWidth: 0 }}>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text, textAlign: 'start', lineHeight: 1.3 }}>{title}</Text>
+ <Text style={{ fontSize: typeScale.body, color: t.textDim, lineHeight: 1.4, textAlign: 'start' }}>{body}</Text>
+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, textAlign: 'start' }}>{tr('monitor.proc.pidUser', { pid: p.pid, user: p.user })}</Text>
+ {err ? <Text style={{ fontSize: typeScale.caption, color: RED, textAlign: 'start' }}>{err}</Text> : null}
+ </View>
+ </View>
+ <View style={{ flexDirection: 'row', gap: spacing.s, marginTop: spacing.xs }}>{actions}</View>
+ </Sheet>
+ );
+}
+
+// ---- Get Info ----
+
+const na = (tr) => tr('monitor.proc.na');
+
+function cpuTime(tr, sec) {
+ if (sec < 60) return tr('monitor.proc.seconds', { v: formatNumber(sec, 2) });
+ const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = Math.floor(sec % 60);
+ const pad = (n) => String(n).padStart(2, '0');
+ return h ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
+}
+
+function Row({ label, children }) {
+ return <FormRow label={label} labelWidth={170} minHeight={30}>{children}</FormRow>;
+}
+
+function Val({ children, dim, mono }) {
+ const t = useTheme();
+ return <Text style={{ fontSize: typeScale.body, color: dim ? t.textDim : t.text, textAlign: 'start', fontFamily: mono ? 'monospace' : undefined }}>{children}</Text>;
+}
+
+function MemoryTab({ d }) {
+ const { t: tr } = useLocale();
+ const m = (v) => (v == null ? na(tr) : fmt.mem(v));
+ const shared = d.shared != null ? d.shared : d.rssFile != null && d.rssShmem != null ? d.rssFile + d.rssShmem : null;
+ return (
+ <View style={{ gap: spacing.l }}>
+ <GroupBox>
+ <Row label={tr('monitor.proc.mem.real')}><Val>{m(d.rss)}</Val></Row>
+ <Row label={tr('monitor.proc.mem.virtual')}><Val>{m(d.vsize)}</Val></Row>
+ <Row label={tr('monitor.proc.mem.shared')}><Val>{m(shared)}</Val></Row>
+ <Row label={tr('monitor.proc.mem.private')}><Val dim={d.private == null}>{m(d.private)}</Val></Row>
+ <Row label={tr('monitor.proc.mem.pss')}><Val dim={d.pss == null}>{m(d.pss)}</Val></Row>
+ <Row label={tr('monitor.proc.mem.swap')}><Val>{m(d.swap)}</Val></Row>
+ </GroupBox>
+ <GroupBox title={tr('monitor.proc.mem.residentParts')}>
+ <Row label={tr('monitor.proc.mem.anon')}><Val>{m(d.rssAnon)}</Val></Row>
+ <Row label={tr('monitor.proc.mem.file')}><Val>{m(d.rssFile)}</Val></Row>
+ <Row label={tr('monitor.proc.mem.shmem')}><Val>{m(d.rssShmem)}</Val></Row>
+ </GroupBox>
+ </View>
+ );
+}
+
+function restrictionsOf(tr, d, p) {
+ const out = [];
+ if (d.isolated) out.push(tr('monitor.proc.r.isolated'));
+ if (d.seccomp === 2) out.push(tr('monitor.proc.r.seccomp'));
+ else if (d.seccomp === 1) out.push(tr('monitor.proc.r.seccompStrict'));
+ if (d.nnp === 1) out.push(tr('monitor.proc.r.nnp'));
+ const app = p?.app;
+ if (app && firewall.available() && firewall.enforceable(app)) {
+ if (firewall.appRule(app) === 'deny') out.push(tr('monitor.proc.r.netBlocked'));
+ const flags = firewall.state()?.restricted?.[app] || [];
+ for (const f of flags) out.push(tr(`firewall.r.${f}`));
+ }
+ return out;
+}
+
+function StatsTab({ d, p, parent }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const rev = useStore(firewallState, (s) => s.rev);
+ const restr = useMemo(() => restrictionsOf(tr, d, p), [d.isolated, d.seccomp, d.nnp, p?.app, rev]);
+ const scope = (d.cgroup || '').split('/').filter(Boolean).pop() || '/';
+ const start = d.startMs ? new Date(d.startMs) : null;
+ return (
+ <GroupBox>
+ <Row label={tr('monitor.proc.st.user')}><Val>{p ? p.user : String(d.uid)}{d.euid !== d.uid ? ` (${tr('monitor.proc.st.effective', { uid: d.euid })})` : ''}</Val></Row>
+ <Row label={tr('monitor.proc.st.parent')}>
+ {parent ? (
+ <Text onClick={() => openInfo(parent)} style={{ fontSize: typeScale.body, color: t.accent, textAlign: 'start' }}>{`${procLabel(tr, parent)} (${parent.pid})`}</Text>
+ ) : <Val>{d.ppid ? String(d.ppid) : '—'}</Val>}
+ </Row>
+ <Row label={tr('monitor.proc.st.group')}><Val>{`${d.pgid} · ${tr('monitor.proc.st.session', { sid: d.sid })}`}</Val></Row>
+ <Row label={tr('monitor.proc.st.cpu')}><Val>{p ? fmt.pct(tr, p.cpu) : '—'}</Val></Row>
+ <Row label={tr('monitor.proc.st.cpuTime')}><Val>{cpuTime(tr, (d.utime + d.stime) / (d.hz || 100))}</Val></Row>
+ <Row label={tr('monitor.threads')}><Val>{formatNumber(d.threads, 0)}</Val></Row>
+ <Row label={tr('monitor.proc.st.ctx')}>
+ <Val>{d.vctx == null ? na(tr) : tr('monitor.proc.st.ctxValue', { v: formatNumber(d.vctx, 0), n: formatNumber(d.nvctx || 0, 0) })}</Val>
+ </Row>
+ <Row label={tr('monitor.proc.st.faults')}><Val>{tr('monitor.proc.st.faultsValue', { minor: formatNumber(d.minflt, 0), major: formatNumber(d.majflt, 0) })}</Val></Row>
+ <Row label={tr('monitor.proc.st.started')}><Val>{start ? `${formatDate(start, 'long')} ${formatTime(start, { seconds: true })}` : '—'}</Val></Row>
+ <Row label={tr('monitor.proc.st.nice')}><Val>{tr('monitor.proc.st.niceValue', { nice: d.nice, prio: d.prio })}</Val></Row>
+ <Row label={tr('monitor.proc.st.scope')}>
+ <View style={{ gap: 2 }}>
+ <Val>{scope}</Val>
+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, textAlign: 'start', direction: 'ltr' }}>{d.cgroup || '/'}</Text>
+ </View>
+ </Row>
+ <Row label={tr('monitor.proc.st.restrictions')}>
+ <View style={{ gap: 2 }}>{restr.length ? restr.map((r) => <Val key={r}>{r}</Val>) : <Val dim>{tr('monitor.proc.r.none')}</Val>}</View>
+ </Row>
+ </GroupBox>
+ );
+}
+
+const KINDS = ['file', 'dev', 'socket', 'pipe', 'anon', 'other'];
+
+function FilesTab({ d, own }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const [settings] = useSettings();
+ const hideAddr = settings.monitor?.connections === false;
+ if (!d.fds) {
+ const hint = own ? tr('monitor.proc.files.naOwn') : isAdmin() ? tr('monitor.proc.files.naAdmin') : tr('monitor.proc.files.needAdmin');
+ return <Text style={{ fontSize: typeScale.body, color: t.textDim, lineHeight: 1.4, textAlign: 'start' }}>{hint}</Text>;
+ }
+ const text = (f) => {
+ if (f.k === 'socket' && f.proto && f.proto !== 'UNIX') {
+ const remote = f.remote ? (hideAddr ? tr('monitor.proc.files.hidden') : f.remote) : '';
+ return `${f.local || '*'}${remote ? ` → ${remote}` : ''}${f.state ? ` · ${f.state}` : ''}`;
+ }
+ if (f.k === 'socket' && f.proto === 'UNIX') return f.p || tr('monitor.proc.files.unnamed');
+ return f.p || '';
+ };
+ const kind = (f) => (f.k === 'socket' && f.proto ? f.proto : tr(`monitor.proc.kind.${KINDS.includes(f.k) ? f.k : 'other'}`));
+ return (
+ <View style={{ gap: spacing.s }}>
+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, textAlign: 'start' }}>
+ {d.fdTotal > d.fds.length ? tr('monitor.proc.files.countCut', { shown: d.fds.length, count: d.fdTotal }) : tr('monitor.proc.files.count', { count: d.fdTotal })}
+ </Text>
+ <View style={{ borderRadius: 8, border: `1px solid ${t.separator}`, overflow: 'hidden' }}>
+ {d.fds.map((f, i) => (
+ <View key={f.fd} style={{ flexDirection: 'row', alignItems: 'center', minHeight: 24, paddingHorizontal: 10, paddingVertical: 3, gap: spacing.s, backgroundColor: i % 2 ? t.hover : 'transparent' }}>
+ <Text style={{ width: 36, fontSize: 11, color: t.textDim, fontFamily: 'monospace', textAlign: 'end' }}>{String(f.fd)}</Text>
+ <Text style={{ width: 64, fontSize: 11, fontWeight: 600, color: f.k === 'socket' ? t.accent : t.textDim, whiteSpace: 'nowrap' }}>{kind(f)}</Text>
+ <Text style={{ flex: 1, minWidth: 0, fontSize: 11, color: t.text, fontFamily: 'monospace', direction: 'ltr', textAlign: 'left' }} numberOfLines={2}>{text(f)}</Text>
+ </View>
+ ))}
+ </View>
+ </View>
+ );
+}
+
+function InfoSheet({ want }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const procs = useStore(monitorProcesses);
+ const d = useStore(monitorDetail);
+ const [tab, setTab] = useState('memory');
+ const [p0] = useState(() => findProc(procs, want));
+ const live = findProc(procs, want);
+ const p = live || p0;
+ const own = p ? p.uid === myUid(procs) : false;
+ useEffect(() => (p ? monitor.watchProcess(p, { asAdmin: !own && isAdmin() }) : undefined), []);
+ const close = () => put({ info: null });
+ const parent = d && d.ppid ? procs?.list.find((x) => x.pid === d.ppid) : null;
+ const ready = d && d.pid === want.pid;
+ const gone = (ready && d.gone) || (procs && !live);
+ const cmd = ready && d.cmdline ? d.cmdline.map((a) => (/[\s"']/.test(a) || !a ? JSON.stringify(a) : a)).join(' ') : '';
+ return (
+ <Sheet width={620} height={620}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.m }}>
+ {p ? <AppGlyph item={p} size={32} /> : null}
+ <View style={{ flex: 1, minWidth: 0, gap: 2 }}>
+ <Text style={{ fontSize: typeScale.title, fontWeight: 600, color: t.text, textAlign: 'start', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>{p ? procLabel(tr, p) : String(want.pid)}</Text>
+ <Text style={{ fontSize: typeScale.callout, color: gone ? RED : t.textDim, textAlign: 'start' }}>
+ {gone ? tr('monitor.proc.gone') : tr('monitor.proc.pidUser', { pid: want.pid, user: p?.user || '' })}
+ </Text>
+ </View>
+ </View>
+ {ready && !d.gone ? (
+ <View style={{ gap: 4 }}>
+ <View style={{ flexDirection: 'row', gap: spacing.s }}>
+ <Text style={{ width: 110, fontSize: typeScale.caption, fontWeight: 600, color: t.textDim, textAlign: 'start' }}>{tr('monitor.proc.exe')}</Text>
+ <Text style={{ flex: 1, minWidth: 0, fontSize: 11, color: d.exe ? t.text : t.textDim, fontFamily: 'monospace', direction: 'ltr', textAlign: 'left' }} numberOfLines={2}>
+ {d.exe || (own ? na(tr) : tr('monitor.proc.files.needAdminShort'))}</Text>
+ </View>
+ <View style={{ flexDirection: 'row', gap: spacing.s }}>
+ <Text style={{ width: 110, fontSize: typeScale.caption, fontWeight: 600, color: t.textDim, textAlign: 'start' }}>{tr('monitor.proc.cmdline')}</Text>
+ <Text style={{ flex: 1, minWidth: 0, fontSize: 11, color: cmd ? t.text : t.textDim, fontFamily: 'monospace', direction: 'ltr', textAlign: 'left', lineHeight: 1.35 }} numberOfLines={4}>
+ {cmd ? `${cmd}${d.cmdCut ? ' …' : ''}` : tr('monitor.proc.noCmdline')}</Text>
+ </View>
+ </View>
+ ) : null}
+ <View style={{ alignItems: 'center' }}>
+ <Segmented appearance="neutral" value={tab} onChange={setTab}
+ options={[['memory', tr('monitor.memory')], ['stats', tr('monitor.proc.tab.stats')], ['files', tr('monitor.proc.tab.files')]]} />
+ </View>
+ <View style={{ flex: 1, minHeight: 0 }}>
+ {!ready ? <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.loading')}</Text>
+ : d.gone ? <Text style={{ fontSize: 12, color: t.textDim, textAlign: 'start' }}>{tr('monitor.proc.goneHint')}</Text>
+ : (
+ <ScrollView style={{ flex: 1 }} gutter>
+ <View style={{ paddingBottom: 4 }}>
+ {tab === 'memory' && <MemoryTab d={d} />}
+ {tab === 'stats' && <StatsTab d={d} p={live} parent={parent} />}
+ {tab === 'files' && <FilesTab d={d} own={own} />}
+ </View>
+ </ScrollView>
+ )}
+ </View>
+ <View style={{ flexDirection: 'row', gap: spacing.s }}>
+ <Button label={tr('monitor.proc.quitDots')} disabled={!live || gone} onClick={() => openStop(live)} />
+ <View style={{ flex: 1 }} />
+ <Button primary label={tr('monitor.proc.close')} onClick={close} />
+ </View>
+ </Sheet>
+ );
+}
diff --git a/apps/monitor/index.jsx b/apps/monitor/index.jsx
index 31872c7..bcb759a 100644
--- a/apps/monitor/index.jsx
+++ b/apps/monitor/index.jsx
@@ -4,8 +4,8 @@
// sampling rate. lord-server (lord.monitor) reads the metrics only while this window is open,
// four times per second.
import {
- View, Text, Image, ScrollView, Segmented, SearchField, Toolbar, typeScale, useTheme, useLocale, useStore, useSettings, useAppWindow,
- useMonitor, monitor, monitorProcesses, monitorSamples, formatBytes, formatNumber, LordOSLogo, iconFromFile,
+ View, Text, Image, ScrollView, Segmented, Toolbar, typeScale, useTheme, useLocale, useStore, useSettings, useAppWindow,
+ useMonitor, monitor, monitorSamples, formatBytes, formatNumber, LordOSLogo, iconFromFile,
} from '@lordos/sdk';
import { registerDockActions } from '@lordos/sdk';
import * as sdk from '@lordos/sdk';
@@ -17,6 +17,7 @@ import { MonitorPrivacy } from './Privacy.jsx';
import { FirewallPrivacy } from './Firewall.jsx';
import { FirewallRulesPrivacy } from './FwRules.jsx';
import { CoolingTab } from './Cooling.jsx';
+import { ProcessesTab, ProcessLayers } from './Processes.jsx';
export function Icon({ size }) { return <MonitorIcon size={size} />; }
@@ -287,9 +288,9 @@ function MemTab({ s, last }) {
// ---- Disks ----
// Table column: the flexible one stretches; fixed-width ones don't shrink.
-const colBox = (c) => (c.flex ? { flex: c.flex, minWidth: 0 } : { width: c.width, flexShrink: 0 });
+export const colBox = (c) => (c.flex ? { flex: c.flex, minWidth: 0 } : { width: c.width, flexShrink: 0 });
-function Table({ cols, rows, onSort, sort }) {
+export function Table({ cols, rows, onSort, sort }) {
const t = useTheme();
const card = useCardStyle();
return (
@@ -358,59 +359,6 @@ export function AppGlyph({ item, size = 16 }) {
return <Ico size={size} />;
}
-function ProcessesTab() {
- const t = useTheme();
- const { t: tr } = useLocale();
- const procs = useStore(monitorProcesses);
- const [q, setQ] = useState('');
- const [mine, setMine] = useState('mine');
- const [sort, setSort] = useState({ key: 'cpu', dir: -1 });
- const me = procs?.list.find((p) => p.self)?.uid;
- const cols = [
- { key: 'name', label: tr('monitor.process'), flex: 1, sort: true },
- { key: 'cpu', label: tr('monitor.cpuPct'), width: 80, num: true, sort: true },
- { key: 'rss', label: tr('monitor.memory'), width: 96, num: true, sort: true },
- { key: 'threads', label: tr('monitor.threads'), width: 64, num: true, sort: true },
- { key: 'pid', label: tr('monitor.pid'), width: 72, num: true, sort: true },
- { key: 'user', label: tr('monitor.user'), width: 96, sort: true },
- ];
- if (!procs) return <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.loading')}</Text>;
- const needle = q.trim().toLowerCase();
- const label = (p) => (p.app === 'lordos' ? tr('monitor.lordos') : p.name);
- let list = procs.list.filter((p) => (mine === 'all' || p.uid === me) && (!needle || `${p.name} ${p.cmd} ${p.appName || ''} ${p.pid}`.toLowerCase().includes(needle)));
- const k = sort.key;
- list = list.slice().sort((a, b) => {
- const va = k === 'name' ? label(a).toLowerCase() : a[k], vb = k === 'name' ? label(b).toLowerCase() : b[k];
- return (va < vb ? -1 : va > vb ? 1 : a.pid - b.pid) * sort.dir;
- });
- const shown = list.slice(0, 150);
- const totalCpu = procs.list.reduce((a, p) => a + p.cpu, 0);
- return (
- <>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text }}>{tr('monitor.processes')}</Text>
- <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.procCount', { count: procs.total })}</Text>
- <View style={{ flex: 1 }} />
- <Segmented value={mine} onChange={setMine} options={[['mine', tr('monitor.mine')], ['all', tr('monitor.all')]]} />
- <SearchField value={q} onChange={setQ} placeholder={tr('monitor.search')} width={200} />
- </View>
- <Table cols={cols} sort={sort} onSort={(key) => setSort((s0) => ({ key, dir: s0.key === key ? -s0.dir : key === 'name' || key === 'user' || key === 'pid' ? 1 : -1 }))}
- rows={shown.map((p, i) => (
- <View key={p.pid} style={{ flexDirection: 'row', height: 26, alignItems: 'center', paddingHorizontal: 10, backgroundColor: i % 2 ? t.hover : 'transparent' }}>
- <Cell col={cols[0]}><AppGlyph item={p} /><Text style={{ fontSize: 12, color: t.text, whiteSpace: 'nowrap' }}>{label(p)}</Text>
- {p.appName && p.appName !== p.name ? <Text style={{ fontSize: 11, color: t.textDim, whiteSpace: 'nowrap' }}>{p.appName}</Text> : null}</Cell>
- <Cell col={cols[1]} bold={p.cpu > 0.5}>{formatNumber(p.cpu * 100, 1)}</Cell>
- <Cell col={cols[2]}>{fmt.mem(p.rss)}</Cell>
- <Cell col={cols[3]} color={t.textDim}>{formatNumber(p.threads, 0)}</Cell>
- <Cell col={cols[4]} color={t.textDim}>{String(p.pid)}</Cell>
- <Cell col={cols[5]} color={t.textDim}>{p.user}</Cell>
- </View>
- ))} />
- <Text style={{ fontSize: 11, color: t.textDim }}>{tr('monitor.procFoot', { shown: shown.length, count: list.length, cpu: formatNumber(totalCpu * 100, 0) })}</Text>
- </>
- );
-}
-
// ---- window ----
let lastTab = 'overview';
@@ -503,6 +451,7 @@ export default function Monitor() {
)}
<View style={{ height: 1, backgroundColor: t.separator }} />
<Footer />
+ <ProcessLayers active={tab === 'processes'} />
</View>
);
}
diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.json
index 335b219..c1886e6 100644
--- a/assets/locales/en/errors.json
+++ b/assets/locales/en/errors.json
@@ -549,5 +549,14 @@
"fw.restricted.notifications": "{app} is restricted from showing notifications (Privacy → App network access)",
"ssh.badConfig": "The SSH server configuration is not valid (sshd -t); nothing was changed",
"ssh.notInstalled": "The SSH server (openssh-server) is not installed",
- "ssh.startFailed": "The SSH server did not start (see Logs)"
+ "ssh.startFailed": "The SSH server did not start (see Logs)",
+ "proc.gone": "That process has already ended",
+ "proc.protectedInit": "This process runs the whole system and can't be stopped",
+ "proc.protectedKernel": "Kernel threads can't be stopped",
+ "proc.protectedSession": "This is your session: use Log Out to end it",
+ "proc.protectedSystem": "This process is part of LordOS and can't be stopped",
+ "proc.denied": "Not allowed to stop this process",
+ "proc.failed": "Could not stop the process",
+ "proc.badArgument": "Invalid process request",
+ "proc.notOwn": "This process belongs to another user"
}
diff --git a/assets/locales/en/monitor.json b/assets/locales/en/monitor.json
index 44e138b..cb074f5 100644
--- a/assets/locales/en/monitor.json
+++ b/assets/locales/en/monitor.json
@@ -138,5 +138,84 @@
"privacy.open": "Open Monitor",
"net.placeApps": "Apps",
"net.privacyShort": "IP-to-country from a local database (DB-IP Lite, CC BY 4.0, db-ip.com): no address leaves the computer.",
- "tab.cooling": "Cooling"
+ "tab.cooling": "Cooling",
+ "proc.stopTip": "Stop process",
+ "proc.infoTip": "Get info (❖I)",
+ "proc.getInfo": "Get Info",
+ "proc.quitMenu": "Quit Process…",
+ "proc.deleteKey": "Del",
+ "proc.cantStop": "“{name}” can’t be stopped",
+ "proc.why.init": "This process starts and runs the whole system.",
+ "proc.why.kernel": "This is part of the Linux kernel.",
+ "proc.why.session": "This is your LordOS session. To end it, use Log Out from the LordOS menu.",
+ "proc.why.system": "This process is part of LordOS.",
+ "proc.needAdmin": "This process belongs to {user}. Only an administrator can stop another user’s processes.",
+ "proc.ok": "OK",
+ "proc.confirm": "Are you sure you want to quit “{name}”?",
+ "proc.confirmHint": "Quit asks it to close. Force Quit stops it at once; any unsaved work in it is lost.",
+ "proc.confirmOther": "This process belongs to {user}. Quit asks it to close; Force Quit stops it at once.",
+ "proc.cancel": "Cancel",
+ "proc.forceQuit": "Force Quit",
+ "proc.quit": "Quit",
+ "proc.quitDots": "Quit…",
+ "proc.close": "Close",
+ "proc.pidUser": "PID {pid} · {user}",
+ "proc.na": "Not available",
+ "proc.seconds": "{v} s",
+ "proc.mem.real": "Real memory",
+ "proc.mem.virtual": "Virtual memory",
+ "proc.mem.shared": "Shared memory",
+ "proc.mem.private": "Private memory",
+ "proc.mem.pss": "Proportional share",
+ "proc.mem.swap": "Swapped out",
+ "proc.mem.residentParts": "Real memory by kind",
+ "proc.mem.anon": "Anonymous",
+ "proc.mem.file": "Mapped files",
+ "proc.mem.shmem": "Shared memory objects",
+ "proc.r.isolated": "Isolated LordOS app (Landlock, seccomp, own cgroup)",
+ "proc.r.seccomp": "Seccomp system call filter",
+ "proc.r.seccompStrict": "Seccomp strict mode",
+ "proc.r.nnp": "Cannot gain new privileges",
+ "proc.r.netBlocked": "Network blocked by your rule",
+ "proc.r.none": "None",
+ "proc.st.user": "User",
+ "proc.st.effective": "effective {uid}",
+ "proc.st.parent": "Parent process",
+ "proc.st.group": "Process group",
+ "proc.st.session": "session {sid}",
+ "proc.st.cpu": "CPU",
+ "proc.st.cpuTime": "CPU time",
+ "proc.st.ctx": "Context switches",
+ "proc.st.ctxValue": "{v} voluntary · {n} forced",
+ "proc.st.faults": "Page faults",
+ "proc.st.faultsValue": "{minor} minor · {major} major",
+ "proc.st.started": "Started",
+ "proc.st.nice": "Nice / priority",
+ "proc.st.niceValue": "{nice} / {prio}",
+ "proc.st.scope": "Control group",
+ "proc.st.restrictions": "Restrictions",
+ "proc.files.naOwn": "Its open files can’t be read.",
+ "proc.files.naAdmin": "Its open files could not be read.",
+ "proc.files.needAdmin": "This process belongs to another user. Only an administrator can see its open files and ports.",
+ "proc.files.needAdminShort": "Only an administrator can see this",
+ "proc.files.hidden": "hidden (Monitor privacy settings)",
+ "proc.files.unnamed": "unnamed",
+ "proc.files.count": {
+ "one": "{count} open file or port",
+ "other": "{count} open files and ports"
+ },
+ "proc.files.countCut": "Showing {shown} of {count} open files and ports",
+ "proc.kind.file": "File",
+ "proc.kind.dev": "Device",
+ "proc.kind.socket": "Socket",
+ "proc.kind.pipe": "Pipe",
+ "proc.kind.anon": "Kernel",
+ "proc.kind.other": "Other",
+ "proc.gone": "This process has ended",
+ "proc.goneHint": "It is no longer running, so there is nothing more to show.",
+ "proc.exe": "Executable",
+ "proc.cmdline": "Command line",
+ "proc.noCmdline": "(none: a kernel thread or a process that cleared it)",
+ "proc.tab.stats": "Statistics",
+ "proc.tab.files": "Open files and ports"
}
diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.json
index bd26c13..51eb699 100644
--- a/assets/locales/es/errors.json
+++ b/assets/locales/es/errors.json
@@ -549,5 +549,14 @@
"fw.restricted.notifications": "{app} tiene restringido mostrar notificaciones (Privacidad → Red de las apps)",
"ssh.badConfig": "La configuración del servidor SSH no es válida (sshd -t); no se cambió nada",
"ssh.notInstalled": "El servidor SSH (openssh-server) no está instalado",
- "ssh.startFailed": "El servidor SSH no arrancó (mirá Registros)"
+ "ssh.startFailed": "El servidor SSH no arrancó (mirá Registros)",
+ "proc.gone": "Ese proceso ya terminó",
+ "proc.protectedInit": "Este proceso hace funcionar todo el sistema y no se puede detener",
+ "proc.protectedKernel": "Los hilos del núcleo no se pueden detener",
+ "proc.protectedSession": "Es tu sesión: usá Cerrar sesión para terminarla",
+ "proc.protectedSystem": "Este proceso es parte de LordOS y no se puede detener",
+ "proc.denied": "No tenés permiso para detener este proceso",
+ "proc.failed": "No se pudo detener el proceso",
+ "proc.badArgument": "Pedido de proceso no válido",
+ "proc.notOwn": "Este proceso es de otro usuario"
}
diff --git a/assets/locales/es/monitor.json b/assets/locales/es/monitor.json
index c8a363f..78afbc6 100644
--- a/assets/locales/es/monitor.json
+++ b/assets/locales/es/monitor.json
@@ -138,5 +138,84 @@
"privacy.open": "Abrir Monitor",
"net.placeApps": "Apps",
"net.privacyShort": "País por IP con una base local (DB-IP Lite, CC BY 4.0, db-ip.com): ninguna dirección sale del equipo.",
- "tab.cooling": "Refrigeración"
+ "tab.cooling": "Refrigeración",
+ "proc.stopTip": "Detener proceso",
+ "proc.infoTip": "Información (❖I)",
+ "proc.getInfo": "Obtener información",
+ "proc.quitMenu": "Salir del proceso…",
+ "proc.deleteKey": "Supr",
+ "proc.cantStop": "«{name}» no se puede detener",
+ "proc.why.init": "Este proceso arranca y hace funcionar todo el sistema.",
+ "proc.why.kernel": "Es parte del núcleo Linux.",
+ "proc.why.session": "Es tu sesión de LordOS. Para terminarla, usá Cerrar sesión en el menú de LordOS.",
+ "proc.why.system": "Este proceso es parte de LordOS.",
+ "proc.needAdmin": "Este proceso es de {user}. Solo un administrador puede detener procesos de otro usuario.",
+ "proc.ok": "Aceptar",
+ "proc.confirm": "¿Seguro que querés salir de «{name}»?",
+ "proc.confirmHint": "Salir le pide que se cierre. Forzar salida lo detiene en el acto; se pierde lo que no esté guardado.",
+ "proc.confirmOther": "Este proceso es de {user}. Salir le pide que se cierre; Forzar salida lo detiene en el acto.",
+ "proc.cancel": "Cancelar",
+ "proc.forceQuit": "Forzar salida",
+ "proc.quit": "Salir",
+ "proc.quitDots": "Salir…",
+ "proc.close": "Cerrar",
+ "proc.pidUser": "PID {pid} · {user}",
+ "proc.na": "No disponible",
+ "proc.seconds": "{v} s",
+ "proc.mem.real": "Memoria real",
+ "proc.mem.virtual": "Memoria virtual",
+ "proc.mem.shared": "Memoria compartida",
+ "proc.mem.private": "Memoria privada",
+ "proc.mem.pss": "Parte proporcional",
+ "proc.mem.swap": "En intercambio",
+ "proc.mem.residentParts": "Memoria real por tipo",
+ "proc.mem.anon": "Anónima",
+ "proc.mem.file": "Archivos mapeados",
+ "proc.mem.shmem": "Objetos de memoria compartida",
+ "proc.r.isolated": "App de LordOS aislada (Landlock, seccomp, cgroup propio)",
+ "proc.r.seccomp": "Filtro de llamadas al sistema (seccomp)",
+ "proc.r.seccompStrict": "Seccomp en modo estricto",
+ "proc.r.nnp": "No puede obtener privilegios nuevos",
+ "proc.r.netBlocked": "Red bloqueada por tu regla",
+ "proc.r.none": "Ninguna",
+ "proc.st.user": "Usuario",
+ "proc.st.effective": "efectivo {uid}",
+ "proc.st.parent": "Proceso padre",
+ "proc.st.group": "Grupo de procesos",
+ "proc.st.session": "sesión {sid}",
+ "proc.st.cpu": "CPU",
+ "proc.st.cpuTime": "Tiempo de CPU",
+ "proc.st.ctx": "Cambios de contexto",
+ "proc.st.ctxValue": "{v} voluntarios · {n} forzados",
+ "proc.st.faults": "Fallos de página",
+ "proc.st.faultsValue": "{minor} menores · {major} mayores",
+ "proc.st.started": "Inicio",
+ "proc.st.nice": "Nice / prioridad",
+ "proc.st.niceValue": "{nice} / {prio}",
+ "proc.st.scope": "Grupo de control",
+ "proc.st.restrictions": "Restricciones",
+ "proc.files.naOwn": "No se pueden leer sus archivos abiertos.",
+ "proc.files.naAdmin": "No se pudieron leer sus archivos abiertos.",
+ "proc.files.needAdmin": "Este proceso es de otro usuario. Solo un administrador puede ver sus archivos y puertos abiertos.",
+ "proc.files.needAdminShort": "Solo un administrador puede verlo",
+ "proc.files.hidden": "oculta (privacidad del Monitor)",
+ "proc.files.unnamed": "sin nombre",
+ "proc.files.count": {
+ "one": "{count} archivo o puerto abierto",
+ "other": "{count} archivos y puertos abiertos"
+ },
+ "proc.files.countCut": "Se muestran {shown} de {count} archivos y puertos abiertos",
+ "proc.kind.file": "Archivo",
+ "proc.kind.dev": "Dispositivo",
+ "proc.kind.socket": "Socket",
+ "proc.kind.pipe": "Tubería",
+ "proc.kind.anon": "Núcleo",
+ "proc.kind.other": "Otro",
+ "proc.gone": "Este proceso terminó",
+ "proc.goneHint": "Ya no está en ejecución: no hay nada más que mostrar.",
+ "proc.exe": "Ejecutable",
+ "proc.cmdline": "Línea de comandos",
+ "proc.noCmdline": "(ninguna: un hilo del núcleo o un proceso que la borró)",
+ "proc.tab.stats": "Estadísticas",
+ "proc.tab.files": "Archivos y puertos abiertos"
}
diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.json
index c0ec39c..0543704 100644
--- a/assets/locales/pt/errors.json
+++ b/assets/locales/pt/errors.json
@@ -549,5 +549,14 @@
"fw.restricted.notifications": "{app} está impedido de mostrar notificações (Privacidade → Rede dos apps)",
"ssh.badConfig": "A configuração do servidor SSH não é válida (sshd -t); nada foi alterado",
"ssh.notInstalled": "O servidor SSH (openssh-server) não está instalado",
- "ssh.startFailed": "O servidor SSH não iniciou (veja Registros)"
+ "ssh.startFailed": "O servidor SSH não iniciou (veja Registros)",
+ "proc.gone": "Esse processo já terminou",
+ "proc.protectedInit": "Este processo mantém todo o sistema e não pode ser parado",
+ "proc.protectedKernel": "Threads do núcleo não podem ser paradas",
+ "proc.protectedSession": "É a sua sessão: use Encerrar sessão para encerrá-la",
+ "proc.protectedSystem": "Este processo faz parte do LordOS e não pode ser parado",
+ "proc.denied": "Sem permissão para parar este processo",
+ "proc.failed": "Não foi possível parar o processo",
+ "proc.badArgument": "Pedido de processo inválido",
+ "proc.notOwn": "Este processo pertence a outro usuário"
}
diff --git a/assets/locales/pt/monitor.json b/assets/locales/pt/monitor.json
index c1a2e7b..c0a44a7 100644
--- a/assets/locales/pt/monitor.json
+++ b/assets/locales/pt/monitor.json
@@ -138,5 +138,84 @@
"privacy.open": "Abrir Monitor",
"net.placeApps": "Apps",
"net.privacyShort": "País por IP com uma base local (DB-IP Lite, CC BY 4.0, db-ip.com): nenhum endereço sai do computador.",
- "tab.cooling": "Resfriamento"
+ "tab.cooling": "Resfriamento",
+ "proc.stopTip": "Parar processo",
+ "proc.infoTip": "Informações (❖I)",
+ "proc.getInfo": "Obter informações",
+ "proc.quitMenu": "Encerrar processo…",
+ "proc.deleteKey": "Del",
+ "proc.cantStop": "“{name}” não pode ser parado",
+ "proc.why.init": "Este processo inicia e mantém todo o sistema funcionando.",
+ "proc.why.kernel": "Faz parte do núcleo Linux.",
+ "proc.why.session": "É a sua sessão do LordOS. Para encerrá-la, use Encerrar sessão no menu do LordOS.",
+ "proc.why.system": "Este processo faz parte do LordOS.",
+ "proc.needAdmin": "Este processo pertence a {user}. Só um administrador pode parar processos de outro usuário.",
+ "proc.ok": "OK",
+ "proc.confirm": "Tem certeza de que deseja encerrar “{name}”?",
+ "proc.confirmHint": "Encerrar pede que ele feche. Forçar encerramento o para na hora; o que não foi salvo se perde.",
+ "proc.confirmOther": "Este processo pertence a {user}. Encerrar pede que ele feche; Forçar encerramento o para na hora.",
+ "proc.cancel": "Cancelar",
+ "proc.forceQuit": "Forçar encerramento",
+ "proc.quit": "Encerrar",
+ "proc.quitDots": "Encerrar…",
+ "proc.close": "Fechar",
+ "proc.pidUser": "PID {pid} · {user}",
+ "proc.na": "Não disponível",
+ "proc.seconds": "{v} s",
+ "proc.mem.real": "Memória real",
+ "proc.mem.virtual": "Memória virtual",
+ "proc.mem.shared": "Memória compartilhada",
+ "proc.mem.private": "Memória privada",
+ "proc.mem.pss": "Parte proporcional",
+ "proc.mem.swap": "Em swap",
+ "proc.mem.residentParts": "Memória real por tipo",
+ "proc.mem.anon": "Anônima",
+ "proc.mem.file": "Arquivos mapeados",
+ "proc.mem.shmem": "Objetos de memória compartilhada",
+ "proc.r.isolated": "App do LordOS isolado (Landlock, seccomp, cgroup próprio)",
+ "proc.r.seccomp": "Filtro de chamadas de sistema (seccomp)",
+ "proc.r.seccompStrict": "Seccomp em modo estrito",
+ "proc.r.nnp": "Não pode obter novos privilégios",
+ "proc.r.netBlocked": "Rede bloqueada pela sua regra",
+ "proc.r.none": "Nenhuma",
+ "proc.st.user": "Usuário",
+ "proc.st.effective": "efetivo {uid}",
+ "proc.st.parent": "Processo pai",
+ "proc.st.group": "Grupo de processos",
+ "proc.st.session": "sessão {sid}",
+ "proc.st.cpu": "CPU",
+ "proc.st.cpuTime": "Tempo de CPU",
+ "proc.st.ctx": "Trocas de contexto",
+ "proc.st.ctxValue": "{v} voluntárias · {n} forçadas",
+ "proc.st.faults": "Falhas de página",
+ "proc.st.faultsValue": "{minor} menores · {major} maiores",
+ "proc.st.started": "Início",
+ "proc.st.nice": "Nice / prioridade",
+ "proc.st.niceValue": "{nice} / {prio}",
+ "proc.st.scope": "Grupo de controle",
+ "proc.st.restrictions": "Restrições",
+ "proc.files.naOwn": "Não é possível ler os arquivos abertos dele.",
+ "proc.files.naAdmin": "Não foi possível ler os arquivos abertos dele.",
+ "proc.files.needAdmin": "Este processo pertence a outro usuário. Só um administrador pode ver os arquivos e portas abertos dele.",
+ "proc.files.needAdminShort": "Só um administrador pode ver isto",
+ "proc.files.hidden": "oculto (privacidade do Monitor)",
+ "proc.files.unnamed": "sem nome",
+ "proc.files.count": {
+ "one": "{count} arquivo ou porta aberto",
+ "other": "{count} arquivos e portas abertos"
+ },
+ "proc.files.countCut": "Mostrando {shown} de {count} arquivos e portas abertos",
+ "proc.kind.file": "Arquivo",
+ "proc.kind.dev": "Dispositivo",
+ "proc.kind.socket": "Socket",
+ "proc.kind.pipe": "Pipe",
+ "proc.kind.anon": "Núcleo",
+ "proc.kind.other": "Outro",
+ "proc.gone": "Este processo terminou",
+ "proc.goneHint": "Ele não está mais em execução: não há mais nada para mostrar.",
+ "proc.exe": "Executável",
+ "proc.cmdline": "Linha de comando",
+ "proc.noCmdline": "(nenhuma: uma thread do núcleo ou um processo que a apagou)",
+ "proc.tab.stats": "Estatísticas",
+ "proc.tab.files": "Arquivos e portas abertos"
}
diff --git a/docs/MONITOR.md b/docs/MONITOR.md
index fcf7bc4..6204235 100644
--- a/docs/MONITOR.md
+++ b/docs/MONITOR.md
@@ -7,7 +7,9 @@ a big number and a live area chart, a row of small figures and a footer with the
The Network tab takes the shape of a per-app network monitor (apps on the left, map in the middle, summary on
the right).
-Phase 1 (this one): read-only. No root daemon, no firewall, no saved history and no alerts.
+Phase 1 was read-only. Since then the Network tab holds per-app firewall rules (Phase 2) and, in
+0.8.1, the Processes tab can stop a process and show its details ("Process actions"). There is no
+saved history and there are no alerts.
## Tabs
@@ -18,7 +20,7 @@ Phase 1 (this one): read-only. No root daemon, no firewall, no saved history and
| Memory | stacked bar (used, file cache, free), swap and a 60 s chart |
| Network | apps with connections, map, summary or detail of the chosen app (see below) |
| Disks | total read and write and one row per disk (model, `/dev`, size, rates) |
-| Processes | sortable table (CPU, memory, threads, PID, user), search, "Mine" / "All" |
+| Processes | sortable table (CPU, memory, threads, PID, user), search, "Mine" / "All"; Stop and Get Info for the selected process (see "Process actions") |
Charts pause with the mouse over them and show a crosshair with the values at that instant, as in
TangoOS. Time always runs left to right, also in Arabic and Hebrew; the rest of the window mirrors
@@ -88,18 +90,103 @@ server, and this app's rule is that no address leaves the machine.
**"This computer"** is placed by the time zone (`/etc/localtime` → coordinates from
`/usr/share/zoneinfo/zone1970.tab`), without the network.
+### Process actions (0.8.1)
+
+Select a row in Processes and use the two buttons next to "Mine / All", the right-click menu, a
+double click or the keyboard:
+
+| Action | Toolbar | Menu | Keys |
+|---|---|---|---|
+| **Stop** | circle with a cross | "Quit Process…" | Delete (or ❖/Ctrl+Backspace) |
+| **Get Info** | circled "i" | "Get Info" | ❖/Ctrl+I, Enter, double click |
+
+The arrow keys move the selection. Both buttons are disabled while nothing is selected.
+❖/Ctrl+Q is not used: it quits the Monitor.
+
+**Stop** opens a sheet: *Are you sure you want to quit "name"?* with **Quit** (SIGTERM: the process
+is asked to close), **Force Quit** (SIGKILL) and **Cancel**.
+
+- **The user's own processes** (same uid) are signalled by `lord-server` itself with a syscall,
+ not a program: `lord.monitor.signal(pid, start, 'TERM' | 'KILL')` (`js_monitor.c` →
+ `proc_signal()` in `monitor/procctl.c`).
+- **Another user's or root's processes**, only for administrators (sudo/admin/wheel): the root
+ helper's fixed action `proc-signal <pid> <start> TERM|KILL` (`monitor/proc_admin.c`), the same
+ authorization as every other privileged action (`admin.c` refuses a non-administrator with
+ `admin.notAdmin`). The arguments are two decimal numbers and one of two words, checked on the root
+ side; there is no shell and no program. A non-administrator gets an explanation instead of the
+ buttons.
+- **No PID-reuse races.** Every row carries `st`, the process's start time in clock ticks (field 22
+ of `/proc/<pid>/stat`). `proc_signal()` first pins the process with `pidfd_open`, then compares
+ the start time, and only then calls `pidfd_send_signal` on that pidfd. If the process ended and
+ its PID was given to another one before the pin, the start time differs and the request is
+ refused (`proc.gone`); if it ends after the pin, the signal can only reach the pinned (dead)
+ process. Kernels without pidfd fall back to `kill(2)` right after the check.
+- **Protected processes** can't be stopped from the Monitor, in either path (`proc_protect_reason()`;
+ each row has `prot`, and the C side checks again). The sheet explains why instead:
+
+ | `prot` | Which | Explanation |
+ |---|---|---|
+ | `init` | PID 1 | "This process starts and runs the whole system." |
+ | `kernel` | kernel threads (`PF_KTHREAD`) | "This is part of the Linux kernel." |
+ | `session` | the session's own `lord-server` | "This is your LordOS session. To end it, use Log Out…" |
+ | `system` | `lord-sessiond`, `lord-netperm`, `lord-netd`, `lord-fand`, `lord-vault`, `lord-maild`, `lord-doc`, `lord-media`, the root helper (`lord-admin`), any `lord-server` that is not an isolated app (another session, a terminal holder), PipeWire (`pipewire`, `pipewire-pulse`, `wireplumber`) and the systemd managers | "This process is part of LordOS." |
+
+ An isolated `.lpk` app (`lord-server --app <id>`) is not protected: a hung app can be quit. The
+ names are matched against the process name and, when it can be read, the executable's name. This
+ is a guard against mistakes, not a security boundary (the kernel's rules on who may signal whom
+ still apply; a terminal can always `kill` the user's own processes).
+
+**Get Info** opens a sheet that follows the process once per second while it is open:
+
+- **Header:** icon, name, PID and user; the executable path and the command line (arguments with
+ spaces are quoted; up to four lines, then "…"; at most 128 arguments of 2 KB each are read).
+- **Memory:** real (RSS), virtual, shared, private, proportional share (PSS) and swapped out, plus
+ the real memory by kind (anonymous, mapped files, shared memory objects). From
+ `/proc/<pid>/status` (anyone can read it) and `/proc/<pid>/smaps_rollup` (the owner or root).
+- **Statistics:** user (and the effective uid if it differs), parent process (a link: it selects the
+ parent and shows its details), process group and session, CPU %, CPU time, threads, context
+ switches (voluntary and forced), page faults (minor and major), start time, nice and priority, the
+ control group (the app scope, as the firewall sees it) and the restrictions LordOS knows about:
+ an isolated LordOS app (Landlock, seccomp, its own cgroup), a seccomp filter, "no new
+ privileges", a network block rule and the app's restrictions from Settings → Privacy (`lord.fw`).
+- **Open files and ports:** each descriptor of `/proc/<pid>/fd` (up to 300; the total is always
+ shown): files, devices, pipes, kernel objects and sockets, with the protocol, local and remote
+ address and TCP state from that process's own `/proc/<pid>/net/{tcp,tcp6,udp,udp6,unix}`. Same
+ privacy rules as the rest of the Monitor: addresses are numbers, nothing is looked up on the
+ network, and with Settings → Privacy → Monitor → connections off the remote addresses are hidden.
+- **Another user's process:** what anyone can read (status, stat, cmdline) comes from the session;
+ the memory breakdown, executable, working folder and open files need root. For an administrator
+ they come from the helper's read-only `proc-info <pid> <start>` action (the same JSON, sent as LOG
+ lines of at most 900 bytes that `sdk/monitor.js` joins); for anyone else those fields say "Not
+ available" or "Only an administrator can see this".
+- **Quit…** opens the stop sheet for the same process; **Close** (or Escape) closes it. If the
+ process ends, the sheet says so.
+
+The details are built on the Monitor's sampling thread (`mon_detail`, once per second and only
+while the sheet is open), never during a frame. Sampling a process's stacks ("Sample process") is
+not offered: it needs ptrace and an unwinder, which LordOS doesn't ship.
+
+Tests: `build/procctl-test` (in `make -C server test`): stat parsing with a hostile name, the
+protected list, a stale start time refused while the process survives, TERM and KILL on real
+children, the session and PID 1 refused, and the Get Info JSON (a pipe and a listening TCP socket
+among the open files; no private parts when not the owner; "gone" for another start time).
+
## Architecture
```
apps/monitor/ index.jsx (tabs), Network.jsx (Network), MapView.jsx (map), Chart.jsx,
TrafficChart.jsx (mirrored sent/received chart), draw.js (pixels),
icons.jsx, Privacy.jsx, countries.js (generated)
-sdk/monitor.js useMonitor(), stores monitorSamples / monitorProcesses / monitorConnections
+apps/monitor/Processes.jsx the Processes tab, its context menu, the stop sheet and Get Info
+sdk/monitor.js useMonitor(), stores monitorSamples / monitorProcesses / monitorConnections /
+ monitorDetail; monitor.watchProcess(), monitor.stopProcess()
server/src/ui/js_monitor.c lord.monitor (read-only, validated API)
server/src/monitor/mon.c sampling thread: /proc, /sys, processes
server/src/monitor/conn.c connections via sock_diag + inode → process
server/src/monitor/mmdb.c our own MaxMind DB reader (IP → country)
server/src/monitor/map.c vector map, on its own thread
+server/src/monitor/procctl.c the protected list, proc_signal() (pidfd) and the Get Info JSON
+server/src/monitor/proc_admin.c the root helper's proc-signal / proc-info (administrators)
assets/monitor/ land.bin (Natural Earth 1:50m), geoip-country.mmdb.xz (DB-IP Lite)
tools/gen-monitor-data.py generates that data, countries.js and the country names
tests/mmdb_test.c, tests/map_bench.c reader test and map benchmark
@@ -112,14 +199,18 @@ tests/mmdb_test.c, tests/map_bench.c reader test and map benchmark
| `start()` / `stop()` | adds or removes an interested party; at 0, or with no queries for 3 s, the thread goes to sleep |
| `want(processes, connections, countries)` | which lists the thread builds besides the sample |
| `sample()` | the latest sample, or `null` if there is no new one |
-| `processes(lang)` | `{ t, total, hz, list: [{ pid, ppid, uid, user, name, cmd, exe, state, threads, cpu, rss, start, self, app, appName, appIcon }] }` |
+| `processes(lang)` | `{ t, total, hz, list: [{ pid, ppid, uid, user, name, cmd, exe, state, threads, cpu, rss, start, st, self, prot, app, appName, appIcon }] }` (`st`: start time in ticks; `prot`: why it can't be stopped, or `null`) |
| `connections(lang)` | `{ t, ok, others, list: [{ id, proto, fam, state, dir, local, lport, remote, rport, scope, cc, pid, self, name, exe, sent, recv, app, appName, appIcon }] }` |
| `info()` | `{ cpuModel, cores, geo, tick, home: { zone, cc, lat, lon } }`; `cpuModel` comes from `js_sys_cpu_name()`, the same one About uses (on ARM, the core from "CPU part" and the board) |
| `map(view)` | requests a map frame: `{ width, height, lon, lat, ppd, land, border, accent, homeColor, selColor, home, dots: [{ lon, lat, r, sel }] }` (validated numbers, up to 2048×2048 and 256 dots) |
| `mapFrame()` | the latest ready frame `{ seq, width, height, lon, lat, ppd, ms, data }`, or `null` |
+| `detail(pid, st)` | Get Info: the process the thread describes once per second (`0, 0`: none) |
+| `detailInfo()` | its latest details, or `null` if there is nothing new; `{ pid, gone: true }` once it ended |
+| `signal(pid, st, 'TERM' \| 'KILL')` | stops one of the user's own processes: `null`, or an error code (`proc.gone`, `proc.protected…`, `proc.notOwn`, `proc.denied`) |
-No function takes paths or commands: the only arguments are booleans and a language code
-(letters, digits, `-` and `_`, up to 15). `lord-server` runs nothing for the Monitor.
+No function takes paths or commands: the only arguments are booleans, a language code (letters,
+digits, `-` and `_`, up to 15), a PID with its start time (integers) and `'TERM'` or `'KILL'`.
+`lord-server` runs nothing for the Monitor.
### Sampling without slowing the screen
@@ -341,6 +432,20 @@ It runs outside the frame. While it draws, the screen shows the previous frame s
VM.
- **Lookup:** each one walks at most 128 nodes.
+## Screenshots (0.8.1, process actions, VM 118)
+
+- The Stop and Get Info buttons with a row selected: ![light](monitor-process-toolbar-light.png)
+ ![dark](monitor-process-toolbar-dark.png)
+- The right-click menu: ![light](monitor-process-menu-light.png) ![dark](monitor-process-menu-dark.png)
+- The stop sheet: ![light](monitor-process-stop-light.png) ![dark](monitor-process-stop-dark.png)
+- Get Info of a download (curl), Memory, Statistics and Open files and ports:
+ ![memory](monitor-process-info-memory-light.png) ![statistics](monitor-process-info-stats-light.png)
+ ![files](monitor-process-info-files-light.png); dark: ![memory](monitor-process-info-memory-dark.png)
+ ![statistics](monitor-process-info-stats-dark.png) ![files](monitor-process-info-files-dark.png)
+- A root process as an administrator (read through `proc-info`): ![root](monitor-process-info-root.png)
+- A non-administrator trying to stop another user's process: ![refused](monitor-process-needadmin.png)
+- Right to left (Arabic): ![rtl](monitor-process-rtl.png)
+
## Screenshots (0.8.1, VM 118, real traffic: a browser on a video site over QUIC and five downloads)
- Network, dark and light: ![dark](monitor-network-dark.png) ![light](monitor-network-light.png)
diff --git a/docs/monitor-process-info-files-dark.png b/docs/monitor-process-info-files-dark.png
new file mode 100644
index 0000000..4dcc893
Binary files /dev/null and b/docs/monitor-process-info-files-dark.png differ
diff --git a/docs/monitor-process-info-files-light.png b/docs/monitor-process-info-files-light.png
new file mode 100644
index 0000000..862b085
Binary files /dev/null and b/docs/monitor-process-info-files-light.png differ
diff --git a/docs/monitor-process-info-memory-dark.png b/docs/monitor-process-info-memory-dark.png
new file mode 100644
index 0000000..5140e73
Binary files /dev/null and b/docs/monitor-process-info-memory-dark.png differ
diff --git a/docs/monitor-process-info-memory-light.png b/docs/monitor-process-info-memory-light.png
new file mode 100644
index 0000000..de1c2b7
Binary files /dev/null and b/docs/monitor-process-info-memory-light.png differ
diff --git a/docs/monitor-process-info-root.png b/docs/monitor-process-info-root.png
new file mode 100644
index 0000000..02a2714
Binary files /dev/null and b/docs/monitor-process-info-root.png differ
diff --git a/docs/monitor-process-info-stats-dark.png b/docs/monitor-process-info-stats-dark.png
new file mode 100644
index 0000000..020ea3d
Binary files /dev/null and b/docs/monitor-process-info-stats-dark.png differ
diff --git a/docs/monitor-process-info-stats-light.png b/docs/monitor-process-info-stats-light.png
new file mode 100644
index 0000000..867c568
Binary files /dev/null and b/docs/monitor-process-info-stats-light.png differ
diff --git a/docs/monitor-process-menu-dark.png b/docs/monitor-process-menu-dark.png
new file mode 100644
index 0000000..983b7ff
Binary files /dev/null and b/docs/monitor-process-menu-dark.png differ
diff --git a/docs/monitor-process-menu-light.png b/docs/monitor-process-menu-light.png
new file mode 100644
index 0000000..0eaacc1
Binary files /dev/null and b/docs/monitor-process-menu-light.png differ
diff --git a/docs/monitor-process-needadmin.png b/docs/monitor-process-needadmin.png
new file mode 100644
index 0000000..340c8cc
Binary files /dev/null and b/docs/monitor-process-needadmin.png differ
diff --git a/docs/monitor-process-rtl.png b/docs/monitor-process-rtl.png
new file mode 100644
index 0000000..02c55ad
Binary files /dev/null and b/docs/monitor-process-rtl.png differ
diff --git a/docs/monitor-process-stop-dark.png b/docs/monitor-process-stop-dark.png
new file mode 100644
index 0000000..ce1923d
Binary files /dev/null and b/docs/monitor-process-stop-dark.png differ
diff --git a/docs/monitor-process-stop-light.png b/docs/monitor-process-stop-light.png
new file mode 100644
index 0000000..324378f
Binary files /dev/null and b/docs/monitor-process-stop-light.png differ
diff --git a/docs/monitor-process-toolbar-dark.png b/docs/monitor-process-toolbar-dark.png
new file mode 100644
index 0000000..fb8cb54
Binary files /dev/null and b/docs/monitor-process-toolbar-dark.png differ
diff --git a/docs/monitor-process-toolbar-light.png b/docs/monitor-process-toolbar-light.png
new file mode 100644
index 0000000..e01b99a
Binary files /dev/null and b/docs/monitor-process-toolbar-light.png differ
diff --git a/sdk/index.js b/sdk/index.js
index f241705..bf98736 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -46,7 +46,7 @@ export {
dockDrag, dockPoof, beginDockDrag, registerDockTarget, dockDragJustEnded,
} from './dock.js';
export { sound, useSound, useSoundPeak, soundState, defaultSink, defaultSource, microphones } from './sound.js';
-export { monitor, useMonitor, monitorSamples, monitorProcesses, monitorConnections, monitorDevices, MONITOR_HISTORY, firewall, firewallState } from './monitor.js';
+export { monitor, useMonitor, monitorSamples, monitorProcesses, monitorConnections, monitorDevices, monitorDetail, MONITOR_HISTORY, firewall, firewallState } from './monitor.js';
export * as fwRule from './fwrule.js'; // checks what the user types for a firewall rule
export { packages, packageList, refreshPackages, packageFile, loadWasm } from './packages.js';
import { refreshPackages } from './packages.js';
diff --git a/sdk/monitor.js b/sdk/monitor.js
index 0233841..8e99dea 100644
--- a/sdk/monitor.js
+++ b/sdk/monitor.js
@@ -9,18 +9,26 @@
// polls it): with the app closed it costs nothing. The process and connection lists are built
// only if some useMonitor asks for them, once per second.
//
+// One process (Processes tab, docs/MONITOR.md "Process actions"):
+// monitor.watchProcess(p, { asAdmin }) Get Info: monitorDetail follows p once per second; returns stop()
+// await monitor.stopProcess(p, 'TERM' | 'KILL') the user's own: lord-server signals it; another
+// user's or root's: the root helper (administrators)
+//
// Phase 2 (not implemented yet): monitor.deviceUsers() → [{ kind: 'camera' | 'microphone',
// app, name, pid }] and the monitorDevices store; and the firewall with per-app and per-domain rules,
// which rely on the same connection records (the `verdict` field, always 'allow' today).
import { useEffect, useRef, useState } from 'react';
import { createStore, useStore } from './store.js';
import { locale } from './i18n.js';
+import { admin } from './admin.js';
+import { codeError } from './errors.js';
export const MONITOR_HISTORY = 240; // 60 s at 4 samples per second
export const monitorSamples = createStore([]);
export const monitorProcesses = createStore(null);
export const monitorConnections = createStore(null);
export const monitorDevices = createStore([]); // phase 2
+export const monitorDetail = createStore(null); // Get Info of one process (procctl.c's JSON)
const available = () => typeof lord.monitor !== 'undefined';
const wants = new Map(); // mounted useMonitor → { procs, conns }
@@ -41,6 +49,7 @@ function poll() {
if (s) monitorSamples.set((list) => (list.length >= MONITOR_HISTORY ? [...list.slice(1 - MONITOR_HISTORY), s] : [...list, s]));
const lang = locale.get().lang;
if (w.procs) { const p = lord.monitor.processes(lang); if (p) monitorProcesses.set(() => p); }
+ if (watched && !watched.viaAdmin) { const d = lord.monitor.detailInfo(); if (d) monitorDetail.set(() => d); }
if (w.conns) {
const c = lord.monitor.connections(lang);
if (c) {
@@ -65,6 +74,7 @@ function unsubscribe(token) {
if (wants.size || !timer) return;
clearInterval(timer);
timer = null;
+ if (watched) stopWatching(watched);
lord.monitor.want(false, false, false);
lord.monitor.stop();
monitorSamples.set([]); // the history starts over when reopened
@@ -143,9 +153,62 @@ export const firewall = {
RESTRICTIONS: ['no-internet', 'no-lan', 'no-network', 'no-incoming', 'no-camera', 'no-mic', 'no-screen', 'no-usb', 'no-bluetooth', 'no-files', 'no-clipboard', 'no-notifications'],
};
+// ---- one process: Get Info and stop ----
+let watched = null; // { pid, st, viaAdmin, timer }
+
+// Get Info as root (another user's process, administrators only): the helper's proc-info sends the
+// JSON in LOG lines that are joined here. If it fails, the session's partial details are used.
+function adminDetail(w) {
+ let text = '';
+ admin.run('proc-info', `${w.pid} ${w.st}`, (line) => { text += line; }, { quiet: true }).then(() => {
+ if (watched !== w) return;
+ try { monitorDetail.set(() => JSON.parse(text)); } catch (e) { /* cut or broken: keep the last one */ }
+ }).catch(() => {
+ if (watched !== w) return;
+ w.viaAdmin = false; // not allowed after all: what the session can read
+ clearInterval(w.timer);
+ lord.monitor.detail(w.pid, w.st);
+ });
+}
+
+function watchProcess(p, { asAdmin = false } = {}) {
+ if (!available() || !p) return () => {};
+ if (watched) stopWatching(watched);
+ const w = { pid: p.pid, st: p.st, viaAdmin: !!asAdmin && admin.available(), timer: null };
+ watched = w;
+ monitorDetail.set(() => null);
+ if (w.viaAdmin) {
+ lord.monitor.detail(0, 0);
+ adminDetail(w);
+ w.timer = setInterval(() => adminDetail(w), 1000);
+ } else lord.monitor.detail(p.pid, p.st);
+ return () => stopWatching(w);
+}
+
+function stopWatching(w) {
+ if (watched !== w) return;
+ clearInterval(w.timer);
+ watched = null;
+ lord.monitor.detail(0, 0);
+ monitorDetail.set(() => null);
+}
+
+// own: the process runs as this user (p.uid === the session's uid); otherwise the root helper.
+async function stopProcess(p, kind, { own } = {}) {
+ if (kind !== 'TERM' && kind !== 'KILL') throw codeError('sys.badArgument');
+ if (own) {
+ const err = lord.monitor.signal(p.pid, p.st, kind);
+ if (err) throw codeError(err);
+ return;
+ }
+ await admin.run('proc-signal', `${p.pid} ${p.st} ${kind}`, null, { quiet: true });
+}
+
let infoCache = null;
export const monitor = {
available,
info: () => (infoCache ||= available() ? lord.monitor.info() : null),
deviceUsers: () => [], // phase 2
+ watchProcess,
+ stopProcess,
};
diff --git a/server/Makefile b/server/Makefile
index 93167ac..bdfd7fd 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -48,7 +48,7 @@ QJS_OBJ := $(patsubst %,build/qjs/%.o,quickjs libregexp libunicode cutils dtoa)
# .lpk app isolation, permissions and signing (src/sec, see docs/PRIVACY.md and docs/SIGNING.md)
# Monitor: metrics, connections and the country of an IP (src/monitor, see docs/MONITOR.md)
-MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c
+MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/proc_admin.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c
# Media (src/media, docs/MEDIA.md): only the lord-server side. Only lord-media links FFmpeg.
MEDIA_SRC := src/media/media.c src/media/mview.c src/media/capture.c src/media/annot.c src/media/maudio.c src/media/mpulse.c src/media/proto.c src/ui/js_media.c
SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c src/sec/restrict.c src/sec/appid.c src/sec/pwguard.c
@@ -302,8 +302,14 @@ build/backup-test: tests/backup_test.c src/backup/engine.c src/backup/crypt.c sr
build/mmdb-test: tests/mmdb_test.c src/monitor/mmdb.c src/monitor/mmdb.h src/pkg/xz.c build/obj/ui/stb.o
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/mmdb_test.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm
# drawing time of the Monitor's vector map (not a test: it measures; see docs/MONITOR.md)
-build/map-bench: tests/map_bench.c src/monitor/map.c src/monitor/map.h src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/map_bench.c src/monitor/map.c src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
+build/map-bench: tests/map_bench.c src/monitor/map.c src/monitor/map.h src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/map_bench.c src/monitor/map.c src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
+# Monitor process actions (src/monitor/procctl.c): the protected list, stat parsing, a signal that
+# refuses a stale start time (PID reuse), TERM/KILL on a child, and the Get Info JSON
+test: build/procctl-test
+build/procctl-test: tests/procctl_test.c src/monitor/procctl.c src/monitor/procctl.h src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/procctl_test.c src/monitor/procctl.c src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/pkg/xz.c build/obj/ui/stb.o -lm -lpthread
+ ./$@ || { rm -f $@; exit 1; }
# canvas.c rows: SIMD (NEON on aarch64) against C, bit for bit, and how long each one takes
# UI engine (docs/DESIGN.md "Engine notes"): ellipsis in LTR/RTL/Arabic/Thai/emoji, per-side borders,
# per-corner radii, logical edges, transforms and hit testing; `build/engine-test bench` times a 2000-row
diff --git a/server/src/admin.c b/server/src/admin.c
index 134c2fe..2363f26 100644
--- a/server/src/admin.c
+++ b/server/src/admin.c
@@ -37,6 +37,7 @@
#include "disk/disk.h"
#include "logs/logs_admin.h"
#include "hw/hw_admin.h"
+#include "monitor/proc_admin.h"
#include <ctype.h>
#include <errno.h>
@@ -395,6 +396,7 @@ static const struct { const char *name; ActionFn fn; int flags; } actions[] = {
DISK_ADMIN_ACTIONS
LOGS_ADMIN_ACTIONS
HW_ADMIN_ACTIONS
+ PROC_ADMIN_ACTIONS
#endif /* LORD_NETD: other modules' actions go above this line */
};
#define N_ACTIONS (sizeof actions / sizeof actions[0])
diff --git a/server/src/monitor/mon.c b/server/src/monitor/mon.c
index 03ae4a3..1611cd9 100644
--- a/server/src/monitor/mon.c
+++ b/server/src/monitor/mon.c
@@ -4,12 +4,14 @@
* /proc/stat (total and per-core CPU), /proc/meminfo, /proc/loadavg, /proc/uptime,
* /proc/net/dev (traffic per interface), /proc/diskstats + /sys/block (reads and writes per
* disk), /sys/class/hwmon and /sys/class/thermal (temperature and fans),
- * /proc/<pid>/{stat,cmdline,exe} (processes) and sock_diag (connections, in conn.c).
+ * /proc/<pid>/{stat,cmdline,exe} (processes), sock_diag (connections, in conn.c) and, for the
+ * one process whose Get Info is open, procctl.c's details.
*
* The thread builds ready-made JSON; the screen thread only copies the latest (mon_*_json). No
* program is executed. */
#include "mon.h"
#include "monpriv.h"
+#include "procctl.h"
#include <ctype.h>
#include <dirent.h>
@@ -126,8 +128,10 @@ static struct {
pthread_cond_t cv;
int started, refs, want_procs, want_conns, want_geo;
double last_poll;
- char *sample, *procs, *conns;
- uint64_t sseq, pseq, cseq;
+ char *sample, *procs, *conns, *detail;
+ uint64_t sseq, pseq, cseq, dseq;
+ int detail_pid; /* Get Info: 0 = none */
+ unsigned long long detail_start;
char geo_path[PATH_MAX];
} M = { .mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER };
@@ -467,9 +471,12 @@ static void procs_scan(Buf *b) {
struct stat sb;
snprintf(p, sizeof p, "/proc/%d", pid);
unsigned uid = stat(p, &sb) ? 0 : (unsigned)sb.st_uid;
- char cmd[256] = "";
+ char cmd[256] = "", argv1[16] = "";
snprintf(p, sizeof p, "/proc/%d/cmdline", pid);
- if (mon_read_small(p, cmd, sizeof cmd) > 0) {
+ long cl = mon_read_small(p, cmd, sizeof cmd);
+ if (cl > 0) {
+ size_t a0 = strnlen(cmd, (size_t)cl);
+ if ((long)a0 + 1 < cl) snprintf(argv1, sizeof argv1, "%s", cmd + a0 + 1);
char *base = strrchr(cmd, '/');
if (base) memmove(cmd, base + 1, strlen(base + 1) + 1);
}
@@ -494,9 +501,13 @@ static void procs_scan(Buf *b) {
mon_buf_str(b, cmd);
mon_buf_printf(b, ",\"exe\":");
mon_buf_str(b, exe);
- mon_buf_printf(b, ",\"state\":\"%c\",\"threads\":%llu,\"cpu\":%.4f,\"rss\":%llu,\"start\":%.0f,\"self\":%s}",
+ /* why it may not be stopped (procctl.c); "st": the exact start time for proc_signal */
+ const char *prot = proc_protect_reason(pid, (unsigned)v[5], comm, exe, argv1, self);
+ mon_buf_printf(b, ",\"state\":\"%c\",\"threads\":%llu,\"cpu\":%.4f,\"rss\":%llu,\"start\":%.0f,\"st\":%llu,\"self\":%s,\"prot\":",
isalpha((unsigned char)state) ? state : '?', v[16], cpu, v[20] * (unsigned long long)page,
- (double)start / (double)hz, pid == self ? "true" : "false");
+ (double)start / (double)hz, start, pid == self ? "true" : "false");
+ if (prot) mon_buf_str(b, prot); else mon_buf_printf(b, "null");
+ mon_buf_printf(b, "}");
}
closedir(d);
qsort(pcur, (size_t)n, sizeof *pcur, cmp_pid);
@@ -532,7 +543,8 @@ static void *worker(void *arg) {
slept = 1;
pthread_cond_wait(&M.cv, &M.mu);
}
- int wp = M.want_procs, wc = M.want_conns, wg = M.want_geo;
+ int wp = M.want_procs, wc = M.want_conns, wg = M.want_geo, dpid = M.detail_pid;
+ unsigned long long dstart = M.detail_start;
pthread_mutex_unlock(&M.mu);
if (slept || !tick) { /* (re)start: no stale rates */
memset(&prev, 0, sizeof prev);
@@ -560,6 +572,17 @@ static void *worker(void *arg) {
procs_scan(&p);
publish(&M.procs, &M.pseq, &p);
}
+ if (dpid > 0 && tick % 4 == 1) {
+ /* Get Info: full details only for the user's own processes (the kernel decides what
+ * else is readable: another user's smaps_rollup, exe and fds are not) */
+ char pp[64];
+ struct stat sb;
+ snprintf(pp, sizeof pp, "/proc/%d", dpid);
+ int own = !stat(pp, &sb) && sb.st_uid == getuid();
+ Buf d = { 0 };
+ proc_detail_json(&d, dpid, dstart, own, (int)getpid());
+ publish(&M.detail, &M.dseq, &d);
+ }
if (wc && tick % 4 == 2) {
if (wg && !geo_tried) { geo_tried = 1; geo_open = M.geo_path[0] && !mmdb_open(&geo, M.geo_path); }
Buf c = { 0 };
@@ -592,6 +615,7 @@ void mon_reset(void) {
pthread_mutex_lock(&M.mu);
M.refs = 0;
M.want_procs = M.want_conns = M.want_geo = 0;
+ M.detail_pid = 0;
pthread_mutex_unlock(&M.mu);
}
@@ -639,6 +663,17 @@ static char *take(char *slot, uint64_t have, uint64_t *seq) {
char *mon_sample_json(uint64_t *seq) { return take(M.sample, M.sseq, seq); }
char *mon_procs_json(uint64_t *seq) { return take(M.procs, M.pseq, seq); }
char *mon_conns_json(uint64_t *seq) { return take(M.conns, M.cseq, seq); }
+char *mon_detail_json(uint64_t *seq) { return take(M.detail, M.dseq, seq); }
+
+void mon_detail(int pid, unsigned long long start) {
+ pthread_mutex_lock(&M.mu);
+ M.detail_pid = pid > 0 && pid <= PROC_PID_MAX ? pid : 0;
+ M.detail_start = start;
+ free(M.detail); /* never show the previous process's details */
+ M.detail = NULL;
+ M.dseq++;
+ pthread_mutex_unlock(&M.mu);
+}
/* ---- fixed data ----------------------------------------------------------------------- */
diff --git a/server/src/monitor/mon.h b/server/src/monitor/mon.h
index 36916f9..744991d 100644
--- a/server/src/monitor/mon.h
+++ b/server/src/monitor/mon.h
@@ -23,6 +23,10 @@ void mon_want(int procs, int conns, int geo);
char *mon_sample_json(uint64_t *seq);
char *mon_procs_json(uint64_t *seq);
char *mon_conns_json(uint64_t *seq);
+/* Get Info (procctl.c): the process whose details the thread builds once per second (pid 0: none)
+ * and the latest JSON. start: its start time in ticks, so a reused PID shows as gone. */
+void mon_detail(int pid, unsigned long long start);
+char *mon_detail_json(uint64_t *seq);
/* Fixed data: CPU model, cores, location from the time zone, country database. */
char *mon_info_json(void);
diff --git a/server/src/monitor/proc_admin.c b/server/src/monitor/proc_admin.c
new file mode 100644
index 0000000..22c1fe2
--- /dev/null
+++ b/server/src/monitor/proc_admin.c
@@ -0,0 +1,82 @@
+/* proc_admin.c — process actions of the root helper, for the Monitor's Processes tab when the
+ * process belongs to another user or to root (the user's own processes are signalled by
+ * lord-server itself, without root). Administrators only.
+ *
+ * proc-signal <pid> <start> TERM|KILL stop one process; <start> is its start time (field 22
+ * of /proc/<pid>/stat), so a reused PID is never hit
+ * proc-info <pid> <start> the Get Info JSON with the parts only root can read
+ * (memory breakdown, executable, open files and sockets)
+ *
+ * The arguments are numbers and one of two words, checked here; the protected list
+ * (procctl.c) applies too. It runs no program: one syscall (pidfd_send_signal) and reads of
+ * /proc. proc-info sends its JSON as LOG lines of at most 900 bytes (cut on UTF-8 boundaries)
+ * that the session joins; OK carries the number of lines. */
+#include "proc_admin.h"
+#include "procctl.h"
+
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+/* "<pid> <start>[ <word>]" with nothing else: decimal numbers without signs or leading zeros. */
+static int parse_args(const char *arg, size_t len, int *pid, unsigned long long *start, char *word, size_t wn) {
+ char a[96];
+ while (len && (arg[len - 1] == '\n' || arg[len - 1] == ' ')) len--;
+ if (!len || len >= sizeof a || memchr(arg, 0, len) || memchr(arg, '\n', len)) return -1;
+ memcpy(a, arg, len);
+ a[len] = 0;
+ char *f[3] = { 0 }, *save = NULL;
+ int n = 0;
+ for (char *t = strtok_r(a, " ", &save); t; t = strtok_r(NULL, " ", &save)) { if (n == 3) return -1; f[n++] = t; }
+ if (n != (word ? 3 : 2)) return -1;
+ for (int i = 0; i < 2; i++) {
+ size_t l = strlen(f[i]);
+ if (!l || l > 20 || (l > 1 && f[i][0] == '0')) return -1;
+ for (size_t k = 0; k < l; k++) if (f[i][k] < '0' || f[i][k] > '9') return -1;
+ }
+ long long p = strtoll(f[0], NULL, 10);
+ if (p < 1 || p > PROC_PID_MAX) return -1;
+ *pid = (int)p;
+ *start = strtoull(f[1], NULL, 10);
+ if (word) snprintf(word, wn, "%s", f[2]);
+ return 0;
+}
+
+void proc_act_signal(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ int pid;
+ unsigned long long start;
+ char w[8];
+ if (parse_args(arg, len, &pid, &start, w, sizeof w) || (strcmp(w, "TERM") && strcmp(w, "KILL"))) {
+ admin_err("admin.invalidArgument", NULL);
+ return;
+ }
+ /* the helper's parent is the session's lord-server */
+ const char *e = proc_signal(pid, start, !strcmp(w, "KILL") ? SIGKILL : SIGTERM, (int)getppid());
+ if (e) admin_err(e, NULL);
+ else admin_say("OK", "%d", pid); /* i18n-ok */
+}
+
+#define CHUNK 900
+
+void proc_act_info(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ int pid;
+ unsigned long long start;
+ if (parse_args(arg, len, &pid, &start, NULL, 0)) { admin_err("admin.invalidArgument", NULL); return; }
+ Buf b = { 0 };
+ proc_detail_json(&b, pid, start, 1, (int)getppid());
+ if (b.bad || !b.p) { mon_buf_free(&b); admin_err("proc.failed", NULL); return; }
+ int lines = 0;
+ for (size_t i = 0; i < b.n && lines < 256;) {
+ size_t n = b.n - i < CHUNK ? b.n - i : CHUNK;
+ while (n < b.n - i && n > 1 && ((unsigned char)b.p[i + n] & 0xc0) == 0x80) n--; /* not inside a UTF-8 sequence */
+ admin_say("LOG", "%.*s", (int)n, b.p + i); /* i18n-ok */
+ i += n;
+ lines++;
+ }
+ mon_buf_free(&b);
+ admin_say("OK", "%d", lines); /* i18n-ok */
+}
diff --git a/server/src/monitor/proc_admin.h b/server/src/monitor/proc_admin.h
new file mode 100644
index 0000000..858d421
--- /dev/null
+++ b/server/src/monitor/proc_admin.h
@@ -0,0 +1,16 @@
+/* proc_admin.h — the root helper's process actions for the Monitor (administrators only; see
+ * proc_admin.c and docs/MONITOR.md, "Process actions"). */
+#ifndef LORD_PROC_ADMIN_H
+#define LORD_PROC_ADMIN_H
+
+#include "../admin.h"
+
+void proc_act_signal(const AdminReq *r, const char *arg, size_t len);
+void proc_act_info(const AdminReq *r, const char *arg, size_t len);
+
+/* Administrators only (no A_ANYONE); both are quick, so they run inside the helper. */
+#define PROC_ADMIN_ACTIONS \
+ { "proc-signal", proc_act_signal, 0 }, \
+ { "proc-info", proc_act_info, 0 },
+
+#endif
diff --git a/server/src/monitor/procctl.c b/server/src/monitor/procctl.c
new file mode 100644
index 0000000..cb86a2f
--- /dev/null
+++ b/server/src/monitor/procctl.c
@@ -0,0 +1,437 @@
+/* procctl.c — protected processes, a PID-reuse-safe signal and the Get Info details of one
+ * process (see procctl.h and docs/MONITOR.md, "Process actions"). */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include "procctl.h"
+
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#ifndef SYS_pidfd_open
+#define SYS_pidfd_open 434
+#endif
+#ifndef SYS_pidfd_send_signal
+#define SYS_pidfd_send_signal 424
+#endif
+
+#define PF_KTHREAD_FLAG 0x00200000u /* include/linux/sched.h */
+#define MAX_FD_SHOW 300 /* open files listed (the total is always counted) */
+#define MAX_ARGS 128
+#define MAX_ARG_LEN 2048
+
+/* ---- /proc/<pid>/stat ---- */
+
+int proc_stat_parse(const char *txt, ProcStat *s) {
+ memset(s, 0, sizeof *s);
+ const char *lp = strchr(txt, '('), *rp = strrchr(txt, ')');
+ if (!lp || !rp || rp < lp || rp[1] != ' ' || !rp[2]) return -1;
+ s->pid = atoi(txt);
+ int cl = (int)(rp - lp - 1);
+ snprintf(s->comm, sizeof s->comm, "%.*s", cl < 63 ? cl : 63, lp + 1);
+ s->state = rp[2];
+ /* fields 4.. (ppid) as numbers: v[0] = field 4 */
+ long long v[22] = { 0 };
+ char *q = (char *)rp + 3;
+ for (int i = 0; i < 22; i++) {
+ char *e;
+ v[i] = strtoll(q, &e, 10);
+ if (e == q) return -1;
+ q = e;
+ }
+ s->ppid = (int)v[0];
+ s->pgid = (int)v[1];
+ s->sid = (int)v[2];
+ s->flags = (unsigned)v[5];
+ s->minflt = (unsigned long long)v[6];
+ s->majflt = (unsigned long long)v[8];
+ s->utime = (unsigned long long)v[10];
+ s->stime = (unsigned long long)v[11];
+ s->prio = (long)v[14];
+ s->nice = (long)v[15];
+ s->threads = (long)v[16];
+ s->start = (unsigned long long)v[18];
+ s->vsize = (unsigned long long)v[19];
+ s->rss = (unsigned long long)(v[20] < 0 ? 0 : v[20]);
+ return s->pid > 0 ? 0 : -1;
+}
+
+int proc_stat_read(int pid, ProcStat *s) {
+ char p[64], txt[1024];
+ snprintf(p, sizeof p, "/proc/%d/stat", pid);
+ if (mon_read_small(p, txt, sizeof txt) <= 0) return -1;
+ return proc_stat_parse(txt, s);
+}
+
+/* ---- the protected list ---- */
+
+static const char *const system_names[] = {
+ "lord-sessiond", "lord-netperm", "lord-netd", "lord-fand", /* root services */
+ "lord-vault", "lord-maild", "lord-doc", "lord-media", /* the session's helpers */
+ "lord-admin", /* the root helper (comm) */
+ "pipewire", "pipewire-pulse", "wireplumber", /* sound and screen sharing */
+ "systemd", "(sd-pam)", /* the init and user managers */
+ NULL,
+};
+
+static int in_system(const char *name) {
+ if (!name || !name[0]) return 0;
+ for (int i = 0; system_names[i]; i++) if (!strcmp(name, system_names[i])) return 1;
+ return 0;
+}
+
+static const char *base_of(const char *p) { const char *b = strrchr(p, '/'); return b ? b + 1 : p; }
+
+const char *proc_protect_reason(int pid, unsigned flags, const char *comm, const char *exe, const char *argv1, int session_pid) {
+ if (pid <= 1) return "init";
+ if (pid == 2 || (flags & PF_KTHREAD_FLAG)) return "kernel";
+ if (pid == session_pid) return "session";
+ char eb[256] = "";
+ if (exe && exe[0]) {
+ snprintf(eb, sizeof eb, "%s", base_of(exe));
+ char *del = strstr(eb, " (deleted)"); /* updated while running */
+ if (del) *del = 0;
+ }
+ if (in_system(comm) || in_system(eb)) return "system";
+ /* lord-server: an isolated app (`lord-server --app <id>`) may be quit; any other instance
+ * (another session, a terminal holder) is part of LordOS */
+ if (!strcmp(eb, "lord-server") || (!eb[0] && comm && !strcmp(comm, "lord-server")))
+ return argv1 && !strcmp(argv1, "--app") ? NULL : "system";
+ return NULL;
+}
+
+/* argv[1] from /proc/<pid>/cmdline into out ("" if there is none). */
+static void read_argv1(int pid, char *out, size_t n) {
+ char p[64], cmd[512];
+ out[0] = 0;
+ snprintf(p, sizeof p, "/proc/%d/cmdline", pid);
+ long k = mon_read_small(p, cmd, sizeof cmd);
+ if (k <= 0) return;
+ size_t a0 = strnlen(cmd, (size_t)k);
+ if ((long)a0 + 1 < k) snprintf(out, n, "%s", cmd + a0 + 1);
+}
+
+static void read_exe(int pid, char *out, size_t n) {
+ char p[64];
+ snprintf(p, sizeof p, "/proc/%d/exe", pid);
+ ssize_t k = readlink(p, out, n - 1);
+ out[k > 0 ? k : 0] = 0;
+}
+
+const char *proc_protected(int pid, int session_pid) {
+ ProcStat s;
+ if (pid <= 1) return "init";
+ if (proc_stat_read(pid, &s)) return NULL;
+ char exe[PATH_MAX], a1[64];
+ read_exe(pid, exe, sizeof exe);
+ read_argv1(pid, a1, sizeof a1);
+ return proc_protect_reason(pid, s.flags, s.comm, exe, a1, session_pid);
+}
+
+/* ---- signal ---- */
+
+const char *proc_signal(int pid, unsigned long long start, int sig, int session_pid) {
+ if (pid <= 0 || pid > PROC_PID_MAX || (sig != SIGTERM && sig != SIGKILL)) return "proc.badArgument";
+ if (pid == 1) return "proc.protectedInit";
+ /* 1. pin the process: from here on the pidfd names this process, never a later one */
+ int pfd = (int)syscall(SYS_pidfd_open, pid, 0);
+ if (pfd < 0 && errno == ESRCH) return "proc.gone";
+ /* 2. is it still the one the user chose? (a PID reused before step 1 has another start time) */
+ ProcStat s;
+ if (proc_stat_read(pid, &s) || s.start != start) { if (pfd >= 0) close(pfd); return "proc.gone"; }
+ const char *why = proc_protected(pid, session_pid);
+ if (why) {
+ if (pfd >= 0) close(pfd);
+ if (!strcmp(why, "init")) return "proc.protectedInit";
+ if (!strcmp(why, "kernel")) return "proc.protectedKernel";
+ if (!strcmp(why, "session")) return "proc.protectedSession";
+ return "proc.protectedSystem";
+ }
+ /* 3. signal the pinned process; if it died meanwhile this is ESRCH, never another process */
+ int r;
+ if (pfd >= 0) {
+ r = (int)syscall(SYS_pidfd_send_signal, pfd, sig, NULL, 0);
+ int e = errno;
+ close(pfd);
+ errno = e;
+ } else {
+ /* no pidfd (kernel before 5.3): kill(2) right after the check; the window is small but real */
+ r = kill(pid, sig);
+ }
+ if (!r) return NULL;
+ if (errno == ESRCH) return "proc.gone";
+ if (errno == EPERM) return "proc.denied";
+ return "proc.failed";
+}
+
+/* ---- Get Info ---- */
+
+static unsigned long long btime_s(void) {
+ static unsigned long long bt;
+ if (bt) return bt;
+ static char txt[65536];
+ if (mon_read_small("/proc/stat", txt, sizeof txt) <= 0) return 0;
+ const char *p = strstr(txt, "\nbtime ");
+ if (p) bt = strtoull(p + 7, NULL, 10);
+ return bt;
+}
+
+/* "Key: 1234 kB" lines: value of key (kB) or -1. */
+static long long kv(const char *txt, const char *key) {
+ size_t kl = strlen(key);
+ for (const char *p = txt; p && *p; p = strchr(p, '\n'), p = p ? p + 1 : NULL) {
+ if (!strncmp(p, key, kl) && p[kl] == ':') return strtoll(p + kl + 1, NULL, 10);
+ }
+ return -1;
+}
+
+static void num_or_null(Buf *b, const char *key, long long v, long long mul) {
+ if (v < 0) mon_buf_printf(b, ",\"%s\":null", key);
+ else mon_buf_printf(b, ",\"%s\":%lld", key, v * mul);
+}
+
+typedef struct { int fd; unsigned long ino; char kind; } FdSock; /* kind: 0 unknown, 't' tcp, 'u' udp, 'x' unix */
+
+static const char *tcp_state(unsigned st) {
+ static const char *const n[] = { "", "ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", "FIN_WAIT2", "TIME_WAIT",
+ "CLOSE", "CLOSE_WAIT", "LAST_ACK", "LISTEN", "CLOSING" };
+ return st < sizeof n / sizeof n[0] ? n[st] : "";
+}
+
+/* "0100007F:0035" (v4) or 32 hex digits + ":port" (v6) → "127.0.0.1:53" / "[::1]:53"; zero → "". */
+static void fmt_addr(const char *hex, int v6, char *out, size_t n) {
+ out[0] = 0;
+ const char *colon = strchr(hex, ':');
+ if (!colon) return;
+ unsigned port = (unsigned)strtoul(colon + 1, NULL, 16);
+ char ip[INET6_ADDRSTRLEN] = "";
+ int zero = 1;
+ if (!v6) {
+ struct in_addr a;
+ a.s_addr = (uint32_t)strtoul(hex, NULL, 16);
+ zero = a.s_addr == 0;
+ inet_ntop(AF_INET, &a, ip, sizeof ip);
+ if (zero && !port) return;
+ snprintf(out, n, "%s:%u", ip, port);
+ } else {
+ struct in6_addr a;
+ if (colon - hex != 32) return;
+ for (int i = 0; i < 4; i++) {
+ char w[9];
+ memcpy(w, hex + i * 8, 8);
+ w[8] = 0;
+ uint32_t v = (uint32_t)strtoul(w, NULL, 16);
+ memcpy(&a.s6_addr[i * 4], &v, 4);
+ if (v) zero = 0;
+ }
+ inet_ntop(AF_INET6, &a, ip, sizeof ip);
+ if (zero && !port) return;
+ snprintf(out, n, "[%s]:%u", ip, port);
+ }
+}
+
+typedef struct { unsigned long ino; char proto[8], local[64], remote[64], state[16], path[256]; int found; } SockInfo;
+
+/* Fills the sockets of fds from /proc/<pid>/net/{tcp,tcp6,udp,udp6,unix} (that process's network
+ * namespace). */
+static void sockets_lookup(int pid, SockInfo *si, int n) {
+ if (!n) return;
+ static const struct { const char *file, *proto; int v6, tcp; } tabs[] = {
+ { "tcp", "TCP", 0, 1 }, { "tcp6", "TCP", 1, 1 }, { "udp", "UDP", 0, 0 }, { "udp6", "UDP", 1, 0 },
+ };
+ char path[64], line[512];
+ for (size_t t = 0; t < sizeof tabs / sizeof tabs[0]; t++) {
+ snprintf(path, sizeof path, "/proc/%d/net/%s", pid, tabs[t].file);
+ FILE *f = fopen(path, "re");
+ if (!f) continue;
+ while (fgets(line, sizeof line, f)) {
+ char la[80], ra[80];
+ unsigned st;
+ unsigned long ino;
+ /* sl local rem st tx:rx tr:tm retr uid timeout inode */
+ if (sscanf(line, " %*s %79s %79s %x %*s %*s %*s %*s %*s %lu", la, ra, &st, &ino) != 4 || !ino) continue;
+ for (int i = 0; i < n; i++) {
+ if (si[i].found || si[i].ino != ino) continue;
+ si[i].found = 1;
+ snprintf(si[i].proto, sizeof si[i].proto, "%s", tabs[t].proto);
+ fmt_addr(la, tabs[t].v6, si[i].local, sizeof si[i].local);
+ fmt_addr(ra, tabs[t].v6, si[i].remote, sizeof si[i].remote);
+ snprintf(si[i].state, sizeof si[i].state, "%s", tabs[t].tcp ? tcp_state(st) : st == 1 ? "ESTABLISHED" : "");
+ }
+ }
+ fclose(f);
+ }
+ snprintf(path, sizeof path, "/proc/%d/net/unix", pid);
+ FILE *f = fopen(path, "re");
+ if (!f) return;
+ while (fgets(line, sizeof line, f)) {
+ unsigned long ino;
+ int off = 0;
+ /* Num RefCount Protocol Flags Type St Inode Path */
+ if (sscanf(line, "%*s %*s %*s %*s %*s %*s %lu%n", &ino, &off) != 1 || !ino) continue;
+ for (int i = 0; i < n; i++) {
+ if (si[i].found || si[i].ino != ino) continue;
+ si[i].found = 1;
+ snprintf(si[i].proto, sizeof si[i].proto, "UNIX");
+ const char *p = line + off;
+ while (*p == ' ') p++;
+ snprintf(si[i].path, sizeof si[i].path, "%s", p);
+ si[i].path[strcspn(si[i].path, "\n")] = 0;
+ }
+ }
+ fclose(f);
+}
+
+static int cmp_int(const void *a, const void *b) { return *(const int *)a - *(const int *)b; }
+
+static void fds_json(Buf *b, int pid) {
+ char dir[64];
+ snprintf(dir, sizeof dir, "/proc/%d/fd", pid);
+ DIR *d = opendir(dir);
+ if (!d) { mon_buf_printf(b, ",\"fds\":null,\"fdTotal\":null"); return; }
+ int *fds = malloc(sizeof(int) * MAX_FD_SHOW), nf = 0, total = 0;
+ struct dirent *e;
+ while ((e = readdir(d))) {
+ if (!isdigit((unsigned char)e->d_name[0])) continue;
+ total++;
+ if (fds && nf < MAX_FD_SHOW) fds[nf++] = atoi(e->d_name);
+ }
+ closedir(d);
+ if (!fds) { mon_buf_printf(b, ",\"fds\":null,\"fdTotal\":%d", total); return; }
+ qsort(fds, (size_t)nf, sizeof *fds, cmp_int);
+ static char targets[MAX_FD_SHOW][PATH_MAX];
+ SockInfo *si = calloc((size_t)(nf ? nf : 1), sizeof *si);
+ int *sidx = calloc((size_t)(nf ? nf : 1), sizeof *sidx), ns = 0;
+ for (int i = 0; i < nf; i++) {
+ char p[96];
+ snprintf(p, sizeof p, "/proc/%d/fd/%d", pid, fds[i]);
+ ssize_t k = readlink(p, targets[i], PATH_MAX - 1);
+ targets[i][k > 0 ? k : 0] = 0;
+ sidx[i] = -1;
+ if (si && sidx && !strncmp(targets[i], "socket:[", 8)) { si[ns].ino = strtoul(targets[i] + 8, NULL, 10); sidx[i] = ns++; }
+ }
+ if (si) sockets_lookup(pid, si, ns);
+ mon_buf_printf(b, ",\"fdTotal\":%d,\"fds\":[", total);
+ for (int i = 0; i < nf; i++) {
+ const char *t = targets[i];
+ mon_buf_printf(b, "%s{\"fd\":%d", i ? "," : "", fds[i]);
+ if (sidx && sidx[i] >= 0 && si && si[sidx[i]].found) {
+ SockInfo *s = &si[sidx[i]];
+ mon_buf_printf(b, ",\"k\":\"socket\",\"proto\":\"%s\"", s->proto);
+ if (s->path[0]) { mon_buf_printf(b, ",\"p\":"); mon_buf_str(b, s->path); }
+ if (s->local[0]) { mon_buf_printf(b, ",\"local\":"); mon_buf_str(b, s->local); }
+ if (s->remote[0]) { mon_buf_printf(b, ",\"remote\":"); mon_buf_str(b, s->remote); }
+ if (s->state[0]) mon_buf_printf(b, ",\"state\":\"%s\"", s->state);
+ } else {
+ const char *k = !strncmp(t, "socket:", 7) ? "socket" : !strncmp(t, "pipe:", 5) ? "pipe" : !strncmp(t, "anon_inode:", 11) ? "anon"
+ : !strncmp(t, "/dev/", 5) ? "dev" : t[0] == '/' ? "file" : "other";
+ mon_buf_printf(b, ",\"k\":\"%s\",\"p\":", k);
+ mon_buf_str(b, t);
+ }
+ mon_buf_printf(b, "}");
+ }
+ mon_buf_printf(b, "]");
+ free(si);
+ free(sidx);
+ free(fds);
+}
+
+static void cmdline_json(Buf *b, int pid) {
+ char p[64];
+ static char cmd[32768];
+ snprintf(p, sizeof p, "/proc/%d/cmdline", pid);
+ long k = mon_read_small(p, cmd, sizeof cmd);
+ mon_buf_printf(b, ",\"cmdline\":[");
+ int n = 0, cut = k >= (long)sizeof cmd - 1;
+ for (long i = 0; k > 0 && i < k && n < MAX_ARGS;) {
+ size_t l = strnlen(cmd + i, (size_t)(k - i));
+ char save = 0;
+ size_t keep = l;
+ if (keep > MAX_ARG_LEN) { keep = MAX_ARG_LEN; while (keep && ((unsigned char)cmd[i + keep] & 0xc0) == 0x80) keep--; cut = 1; }
+ if (keep < l) { save = cmd[i + keep]; cmd[i + keep] = 0; }
+ mon_buf_printf(b, "%s", n ? "," : "");
+ mon_buf_str(b, cmd + i);
+ if (keep < l) cmd[i + keep] = save;
+ n++;
+ i += (long)l + 1;
+ if (n == MAX_ARGS && i < k) cut = 1;
+ }
+ mon_buf_printf(b, "],\"cmdCut\":%s", cut ? "true" : "false");
+}
+
+void proc_detail_json(Buf *b, int pid, unsigned long long start, int full, int session_pid) {
+ ProcStat s;
+ if (pid <= 0 || pid > PROC_PID_MAX || proc_stat_read(pid, &s) || s.start != start) {
+ mon_buf_printf(b, "{\"pid\":%d,\"gone\":true}", pid);
+ return;
+ }
+ long hz = sysconf(_SC_CLK_TCK), page = sysconf(_SC_PAGESIZE);
+ char path[64];
+ static char st[8192], sm[4096];
+ snprintf(path, sizeof path, "/proc/%d/status", pid);
+ if (mon_read_small(path, st, sizeof st) <= 0) st[0] = 0;
+ unsigned ruid = 0, euid = 0;
+ const char *u = strstr(st, "\nUid:");
+ if (u) sscanf(u + 5, "%u %u", &ruid, &euid);
+ mon_buf_printf(b, "{\"pid\":%d,\"gone\":false,\"start\":%llu,\"hz\":%ld,\"name\":", pid, s.start, hz);
+ mon_buf_str(b, s.comm);
+ mon_buf_printf(b, ",\"state\":\"%c\",\"ppid\":%d,\"pgid\":%d,\"sid\":%d,\"uid\":%u,\"euid\":%u,"
+ "\"utime\":%llu,\"stime\":%llu,\"minflt\":%llu,\"majflt\":%llu,\"prio\":%ld,\"nice\":%ld,\"threads\":%ld,"
+ "\"startMs\":%.0f,\"vsize\":%llu,\"rss\":%llu",
+ isalpha((unsigned char)s.state) ? s.state : '?', s.ppid, s.pgid, s.sid, ruid, euid, s.utime, s.stime,
+ s.minflt, s.majflt, s.prio, s.nice, s.threads,
+ btime_s() ? ((double)btime_s() + (double)s.start / (double)hz) * 1000.0 : 0.0, s.vsize, s.rss * (unsigned long long)page);
+ num_or_null(b, "rssAnon", kv(st, "RssAnon"), 1024);
+ num_or_null(b, "rssFile", kv(st, "RssFile"), 1024);
+ num_or_null(b, "rssShmem", kv(st, "RssShmem"), 1024);
+ num_or_null(b, "swap", kv(st, "VmSwap"), 1024);
+ num_or_null(b, "vctx", kv(st, "voluntary_ctxt_switches"), 1);
+ num_or_null(b, "nvctx", kv(st, "nonvoluntary_ctxt_switches"), 1);
+ num_or_null(b, "seccomp", kv(st, "Seccomp"), 1);
+ num_or_null(b, "nnp", kv(st, "NoNewPrivs"), 1);
+ /* smaps_rollup needs ptrace read access: the owner (or root) only */
+ snprintf(path, sizeof path, "/proc/%d/smaps_rollup", pid);
+ if (full && mon_read_small(path, sm, sizeof sm) > 0) {
+ long long pc = kv(sm, "Private_Clean"), pd = kv(sm, "Private_Dirty"), sc = kv(sm, "Shared_Clean"), sd = kv(sm, "Shared_Dirty");
+ num_or_null(b, "private", pc >= 0 && pd >= 0 ? pc + pd : -1, 1024);
+ num_or_null(b, "shared", sc >= 0 && sd >= 0 ? sc + sd : -1, 1024);
+ num_or_null(b, "pss", kv(sm, "Pss"), 1024);
+ } else mon_buf_printf(b, ",\"private\":null,\"shared\":null,\"pss\":null");
+ /* cgroup v2 path (the app scope) */
+ char cg[1024] = "";
+ snprintf(path, sizeof path, "/proc/%d/cgroup", pid);
+ if (mon_read_small(path, cg, sizeof cg) > 0) {
+ char *z = strstr(cg, "0::");
+ if (z) { memmove(cg, z + 3, strlen(z + 3) + 1); cg[strcspn(cg, "\n")] = 0; } else cg[0] = 0;
+ }
+ mon_buf_printf(b, ",\"cgroup\":");
+ mon_buf_str(b, cg);
+ char exe[PATH_MAX] = "", cwd[PATH_MAX] = "", a1[64];
+ read_exe(pid, exe, sizeof exe);
+ read_argv1(pid, a1, sizeof a1);
+ const char *why = proc_protect_reason(pid, s.flags, s.comm, exe, a1, session_pid);
+ mon_buf_printf(b, ",\"prot\":");
+ if (why) mon_buf_str(b, why); else mon_buf_printf(b, "null");
+ mon_buf_printf(b, ",\"isolated\":%s", !strcmp(base_of(exe), "lord-server") && !strcmp(a1, "--app") ? "true" : "false");
+ mon_buf_printf(b, ",\"kthread\":%s", (s.flags & PF_KTHREAD_FLAG) || pid == 2 ? "true" : "false");
+ snprintf(path, sizeof path, "/proc/%d/cwd", pid);
+ if (full) { ssize_t k = readlink(path, cwd, sizeof cwd - 1); cwd[k > 0 ? k : 0] = 0; }
+ mon_buf_printf(b, ",\"exe\":");
+ if (full && exe[0]) mon_buf_str(b, exe); else mon_buf_printf(b, "null");
+ mon_buf_printf(b, ",\"cwd\":");
+ if (full && cwd[0]) mon_buf_str(b, cwd); else mon_buf_printf(b, "null");
+ cmdline_json(b, pid);
+ if (full) fds_json(b, pid); else mon_buf_printf(b, ",\"fds\":null,\"fdTotal\":null");
+ mon_buf_printf(b, "}");
+}
diff --git a/server/src/monitor/procctl.h b/server/src/monitor/procctl.h
new file mode 100644
index 0000000..24f3591
--- /dev/null
+++ b/server/src/monitor/procctl.h
@@ -0,0 +1,51 @@
+/* procctl.h — one process of the Monitor's Processes tab (see docs/MONITOR.md, "Process
+ * actions"): the protected list, a signal that cannot reach a reused PID, and the details that
+ * Get Info shows. Used by lord-server (the user's own processes) and by the root helper's
+ * proc-signal / proc-info actions (proc_admin.c, administrators only). Read-only /proc access and
+ * one syscall (pidfd_send_signal); nothing is executed. */
+#ifndef LORD_PROCCTL_H
+#define LORD_PROCCTL_H
+
+#include "monpriv.h"
+
+#define PROC_PID_MAX 4194304 /* the kernel's PID_MAX_LIMIT */
+
+typedef struct {
+ int pid, ppid, pgid, sid;
+ char state;
+ unsigned flags;
+ unsigned long long minflt, majflt, utime, stime, start, vsize, rss; /* start: ticks since boot; rss: pages */
+ long prio, nice, threads;
+ char comm[64];
+} ProcStat;
+
+/* Parses the text of /proc/<pid>/stat. 0 if it is well formed. */
+int proc_stat_parse(const char *txt, ProcStat *s);
+int proc_stat_read(int pid, ProcStat *s);
+
+/* Why a process may not be stopped from the Monitor, or NULL if it may:
+ * "init" PID 1 (and anything below it)
+ * "kernel" a kernel thread
+ * "session" the session's own lord-server (session_pid)
+ * "system" another part of LordOS or the desktop: lord-sessiond, lord-netperm, lord-netd,
+ * lord-fand, the helpers (lord-vault, lord-maild, lord-doc, lord-media), the root
+ * helper, any lord-server that is not an isolated app (`--app`), PipeWire,
+ * WirePlumber and the systemd managers.
+ * exe may be "" (unreadable); argv1 is the process's second argument or NULL. */
+const char *proc_protect_reason(int pid, unsigned flags, const char *comm, const char *exe, const char *argv1, int session_pid);
+/* Same, reading comm, flags, exe and the command line from /proc. */
+const char *proc_protected(int pid, int session_pid);
+
+/* Sends SIGTERM or SIGKILL to pid only if it is still the process that started at `start`
+ * (clock ticks after boot, field 22 of stat): pidfd_open, compare the start time, then
+ * pidfd_send_signal on that pidfd, so a PID reused in between is never hit. Returns NULL on
+ * success or an error code (errcode.h): proc.gone, proc.protected<Reason>, proc.denied,
+ * proc.failed. */
+const char *proc_signal(int pid, unsigned long long start, int sig, int session_pid);
+
+/* Get Info as JSON for pid, if it still started at `start` ({"pid":…,"gone":true} otherwise).
+ * full: also what only the owner or root can read (smaps_rollup, exe, cwd, open files and
+ * sockets); without it those fields are null. */
+void proc_detail_json(Buf *b, int pid, unsigned long long start, int full, int session_pid);
+
+#endif
diff --git a/server/src/ui/js_monitor.c b/server/src/ui/js_monitor.c
index 53f80be..ba3736a 100644
--- a/server/src/ui/js_monitor.c
+++ b/server/src/ui/js_monitor.c
@@ -13,10 +13,17 @@
* info() CPU model, cores, location by time zone, country database
* map(view) requests a frame of the vector map (another thread draws it; map.c)
* mapFrame() the latest ready frame { seq, width, height, lon, lat, ppd, ms, data } or null
+ * detail(pid, start) Get Info: which process the thread describes once per second (0: none)
+ * detailInfo() its latest details (procctl.c), or null if nothing new
+ * signal(pid, start, kind) stops one of the user's own processes: kind 'TERM' or 'KILL'; null or
+ * an error code (proc.gone, proc.protected…, proc.notOwn, proc.denied).
+ * Other users' processes go through the root helper (proc-signal,
+ * administrators only; sdk/monitor.js).
*/
#include "js_monitor.h"
#include "../monitor/mon.h"
#include "../monitor/map.h"
+#include "../monitor/procctl.h"
#include "../apps.h"
#include "js_sys.h"
#include "js_err.h"
@@ -27,8 +34,11 @@
#include <stdlib.h>
#include <string.h>
#include <strings.h>
+#include <signal.h>
+#include <sys/stat.h>
+#include <unistd.h>
-static uint64_t seq_sample, seq_procs, seq_conns;
+static uint64_t seq_sample, seq_procs, seq_conns, seq_detail;
static JSValue parse(JSContext *c, char *j, const char *what) {
if (!j) return JS_NULL;
@@ -305,6 +315,54 @@ static JSValue f_map_frame(JSContext *c, JSValueConst t, int argc, JSValueConst
return o;
}
+/* ---- one process: Get Info and stop ---- */
+
+/* pid (1..PID_MAX) and start time (an integer number of ticks, 0..2^53) from argv[0..1]. */
+static int arg_proc(JSContext *c, int argc, JSValueConst *argv, int *pid, unsigned long long *start) {
+ double p, st;
+ if (argc < 2 || !JS_IsNumber(argv[0]) || !JS_IsNumber(argv[1]) || JS_ToFloat64(c, &p, argv[0]) || JS_ToFloat64(c, &st, argv[1])) return -1;
+ if (!isfinite(p) || p != floor(p) || p < 0 || p > PROC_PID_MAX) return -1;
+ if (!isfinite(st) || st != floor(st) || st < 0 || st > 9007199254740992.0) return -1;
+ *pid = (int)p;
+ *start = (unsigned long long)st;
+ return 0;
+}
+
+static JSValue f_detail(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int pid;
+ unsigned long long start;
+ if (arg_proc(c, argc, argv, &pid, &start)) return js_throw_code(c, "sys.badArgument", NULL);
+ mon_detail(pid, start);
+ seq_detail = 0;
+ return JS_TRUE;
+}
+
+static JSValue f_detail_info(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return parse(c, mon_detail_json(&seq_detail), "<monitor.detail>");
+}
+
+static JSValue f_signal(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int pid;
+ unsigned long long start;
+ if (arg_proc(c, argc, argv, &pid, &start) || pid < 1 || argc < 3 || !JS_IsString(argv[2])) return js_throw_code(c, "sys.badArgument", NULL);
+ const char *k = JS_ToCString(c, argv[2]);
+ if (!k) return JS_EXCEPTION;
+ int sig = !strcmp(k, "TERM") ? SIGTERM : !strcmp(k, "KILL") ? SIGKILL : 0;
+ JS_FreeCString(c, k);
+ if (!sig) return js_throw_code(c, "sys.badArgument", NULL);
+ /* only the user's own processes here; the rest goes through the root helper (administrators) */
+ char p[64];
+ struct stat sb;
+ snprintf(p, sizeof p, "/proc/%d", pid);
+ if (stat(p, &sb)) return JS_NewString(c, "proc.gone");
+ if (sb.st_uid != getuid()) return JS_NewString(c, "proc.notOwn");
+ const char *e = proc_signal(pid, start, sig, (int)getpid());
+ return e ? JS_NewString(c, e) : JS_NULL;
+}
+
static const JSCFunctionListEntry monitor_funcs[] = {
JS_CFUNC_DEF("start", 0, f_start),
JS_CFUNC_DEF("stop", 0, f_stop),
@@ -315,13 +373,16 @@ static const JSCFunctionListEntry monitor_funcs[] = {
JS_CFUNC_DEF("info", 0, f_info),
JS_CFUNC_DEF("map", 1, f_map),
JS_CFUNC_DEF("mapFrame", 0, f_map_frame),
+ JS_CFUNC_DEF("detail", 2, f_detail),
+ JS_CFUNC_DEF("detailInfo", 0, f_detail_info),
+ JS_CFUNC_DEF("signal", 3, f_signal),
};
void js_monitor_register(JSContext *c, JSValue lord, const char *assets_dir) {
mon_init(assets_dir);
map_init(assets_dir);
mon_reset(); /* new context: the previous one's start() calls don't count */
- seq_sample = seq_procs = seq_conns = 0;
+ seq_sample = seq_procs = seq_conns = seq_detail = 0;
JSValue o = JS_NewObject(c);
JS_SetPropertyFunctionList(c, o, monitor_funcs, sizeof monitor_funcs / sizeof monitor_funcs[0]);
JS_SetPropertyStr(c, lord, "monitor", o);
diff --git a/server/tests/procctl_test.c b/server/tests/procctl_test.c
new file mode 100644
index 0000000..b64e84b
--- /dev/null
+++ b/server/tests/procctl_test.c
@@ -0,0 +1,104 @@
+/* procctl_test.c — the Monitor's process actions (src/monitor/procctl.c): stat parsing, the
+ * protected list, a signal that refuses a stale start time (the PID-reuse guard), TERM and KILL on
+ * real children, and the Get Info JSON (memory, a pipe, a listening TCP socket). */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include "../src/monitor/procctl.h"
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+static int checks, fails;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "%s:%d: CHECK(%s) failed\n", __FILE__, __LINE__, #c); } } while (0)
+#define STREQ(a, b) ((a) && (b) && !strcmp((a), (b)))
+
+static pid_t child(void) {
+ pid_t p = fork();
+ if (p == 0) { for (;;) pause(); }
+ struct timespec ts = { 0, 20 * 1000 * 1000 };
+ nanosleep(&ts, NULL);
+ return p;
+}
+
+int main(void) {
+ /* stat with a hostile name: spaces and parentheses inside comm */
+ ProcStat s;
+ CHECK(!proc_stat_parse("4242 (a) b (c) S 1 4242 4242 0 -1 4194560 10 0 2 0 7 3 0 0 20 0 5 0 123456 1000000 250 18446744073709551615", &s));
+ CHECK(s.pid == 4242 && STREQ(s.comm, "a) b (c") && s.state == 'S' && s.ppid == 1 && s.pgid == 4242);
+ CHECK(s.minflt == 10 && s.majflt == 2 && s.utime == 7 && s.stime == 3 && s.prio == 20 && s.threads == 5);
+ CHECK(s.start == 123456 && s.vsize == 1000000 && s.rss == 250);
+ CHECK(proc_stat_parse("garbage", &s) == -1);
+ CHECK(proc_stat_parse("12 (x) S 1 2", &s) == -1);
+
+ /* the protected list */
+ CHECK(STREQ(proc_protect_reason(1, 0, "systemd", "/usr/lib/systemd/systemd", NULL, 999), "init"));
+ CHECK(STREQ(proc_protect_reason(2, 0x00200000, "kthreadd", "", NULL, 999), "kernel"));
+ CHECK(STREQ(proc_protect_reason(77, 0x00200000, "kworker/0:1", "", NULL, 999), "kernel"));
+ CHECK(STREQ(proc_protect_reason(999, 0, "lord-server", "/usr/lib/lordos/bin/lord-server", NULL, 999), "session"));
+ CHECK(STREQ(proc_protect_reason(500, 0, "lord-server", "/usr/lib/lordos/bin/lord-server", "--term-holder", 999), "system"));
+ CHECK(proc_protect_reason(501, 0, "lord-server", "/usr/lib/lordos/bin/lord-server", "--app", 999) == NULL);
+ const char *sys[] = { "lord-sessiond", "lord-netperm", "lord-netd", "lord-fand", "lord-vault", "lord-maild", "lord-doc", "lord-media",
+ "lord-admin", "pipewire", "pipewire-pulse", "wireplumber" };
+ for (size_t i = 0; i < sizeof sys / sizeof sys[0]; i++) CHECK(STREQ(proc_protect_reason(600, 0, sys[i], "", NULL, 999), "system"));
+ CHECK(STREQ(proc_protect_reason(601, 0, "x", "/usr/bin/pipewire (deleted)", NULL, 999), "system"));
+ CHECK(proc_protect_reason(602, 0, "firefox-esr", "/usr/lib/firefox-esr/firefox-esr", NULL, 999) == NULL);
+ CHECK(proc_protect_reason(603, 0, "lord-serverx", "", NULL, 999) == NULL);
+
+ /* signals: a stale start time is refused and the process survives */
+ pid_t a = child();
+ ProcStat cs;
+ CHECK(!proc_stat_read(a, &cs));
+ CHECK(STREQ(proc_signal(a, cs.start + 1, SIGTERM, getpid()), "proc.gone"));
+ CHECK(kill(a, 0) == 0);
+ CHECK(STREQ(proc_signal(a, cs.start, SIGHUP, getpid()), "proc.badArgument"));
+ CHECK(proc_signal(a, cs.start, SIGTERM, getpid()) == NULL);
+ int st = 0;
+ CHECK(waitpid(a, &st, 0) == a && WIFSIGNALED(st) && WTERMSIG(st) == SIGTERM);
+ /* the same pid again after it is gone (the reuse case: no process, or another one) */
+ const char *again = proc_signal(a, cs.start, SIGKILL, getpid());
+ CHECK(STREQ(again, "proc.gone"));
+ pid_t b = child();
+ CHECK(!proc_stat_read(b, &cs));
+ CHECK(proc_signal(b, cs.start, SIGKILL, getpid()) == NULL);
+ CHECK(waitpid(b, &st, 0) == b && WIFSIGNALED(st) && WTERMSIG(st) == SIGKILL);
+ /* the session itself and PID 1 */
+ ProcStat me;
+ CHECK(!proc_stat_read(getpid(), &me));
+ CHECK(STREQ(proc_signal(getpid(), me.start, SIGTERM, getpid()), "proc.protectedSession"));
+ CHECK(STREQ(proc_signal(1, 0, SIGTERM, getpid()), "proc.protectedInit"));
+ CHECK(STREQ(proc_signal(0, 0, SIGTERM, getpid()), "proc.badArgument"));
+ CHECK(STREQ(proc_signal(PROC_PID_MAX + 1, 0, SIGTERM, getpid()), "proc.badArgument"));
+
+ /* Get Info: a pipe and a listening TCP socket show up among the open files */
+ int pp[2];
+ CHECK(!pipe(pp));
+ int ls = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in sa = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ CHECK(ls >= 0 && !bind(ls, (struct sockaddr *)&sa, sizeof sa) && !listen(ls, 1));
+ Buf j = { 0 };
+ proc_detail_json(&j, getpid(), me.start, 1, 1);
+ CHECK(j.p && strstr(j.p, "\"gone\":false"));
+ CHECK(j.p && strstr(j.p, "\"k\":\"pipe\""));
+ CHECK(j.p && strstr(j.p, "\"proto\":\"TCP\"") && strstr(j.p, "\"local\":\"127.0.0.1:") && strstr(j.p, "\"state\":\"LISTEN\""));
+ CHECK(j.p && strstr(j.p, "\"exe\":\"/") && strstr(j.p, "\"cmdline\":[\""));
+ CHECK(j.p && strstr(j.p, "\"private\":") && !strstr(j.p, "\"private\":null"));
+ mon_buf_free(&j);
+ proc_detail_json(&j, getpid(), me.start, 0, 1); /* not the owner: no private parts */
+ CHECK(j.p && strstr(j.p, "\"fds\":null") && strstr(j.p, "\"exe\":null") && strstr(j.p, "\"private\":null"));
+ mon_buf_free(&j);
+ proc_detail_json(&j, getpid(), me.start + 7, 1, 1); /* another start time: gone */
+ CHECK(j.p && strstr(j.p, "\"gone\":true") && !strstr(j.p, "\"fds\""));
+ mon_buf_free(&j);
+
+ printf("procctl-test: %d checks, %d failed\n", checks, fails);
+ return fails ? 1 : 0;
+}