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.

Checkpoint: passwords and keyring, mail, settings sections, disks, app isolation (camera, multi-window, root-owned scopes), polish batch 1, ISO packaging

Federico Pereira5f21ae271c0f
diff --git a/apps/README.md b/apps/README.md
index 57d7f14..9a1f9e7 100644
--- a/apps/README.md
+++ b/apps/README.md
@@ -79,8 +79,8 @@ desde la Tienda (ver `docs/APPS-NATIVAS.md`).
| Ventanas (medios) | `wm.setProtected(id, on)` (negra en capturas, grabaciones y escritorio remoto), `wm.setFullscreen(id, on)`, `wm.setPip(id, frame)`, `useWindowState(clave, inicial)`, `useAppWindow().mode` (`'window'`, `'fullscreen'` o `'pip'`) |
| Markdown | `<Markdown source base width onLink onToggleTask />`, `markdownHeadings(texto)`, `toggleTask` — ver `docs/NOTAS.md` |
| Escritorio | `registerWidgetType(tipo, Componente)`, `setWidgets(tipo, [{ id, x, y, w, h, pinned }])`: widgets entre el fondo y las ventanas |
-| Avisos (M9) | `notify({ app, title, body, actions: [{ id, label, primary, run }], sound, sticky, timeout, onClose })` → id, `dismissNotification(id)`, `useNotifications()`, `notifyHistory`; `registerStatusItem(id, Componente)` (íconos de estado en la barra del tema) — ver `docs/SISTEMA.md` |
-| Reloj y Ayuda (M9) | `clockAlarms`, `clockTimer`/`timerStart…`, `stopwatch`/`swStart…` (siguen con la app cerrada); `lord.time.zoneOffset(zona, t)`; `help.list/read/search/open/startTour`; `registerSpotlightSource(id, fn)`; `weekdayName(d)` |
+| Notifications (M9) | `notify({ app, title, body, actions: [{ id, label, primary, run }], sound, sticky, timeout, onClose })` → id, `dismissNotification(id)`, `useNotifications()`, `notifyHistory`; `registerStatusItem(id, Component)` (status icons in the theme's bar) — see `docs/SYSTEM.md` |
+| Clock and Help (M9) | `clockAlarms`, `clockTimer`/`timerStart…`, `stopwatch`/`swStart…` (keep running with the app closed); `lord.time.zoneOffset(zone, t)`; `help.list/read/search/open/startTour`; `registerSpotlightSource(id, fn)`; `weekdayName(d)` |
| Documentos (M9) | `pdf.open(ruta \| { blob })` (página, búsqueda, índice, enlaces, formularios, anotaciones, guardar copia), `<DocImage image>`, `archive.list/extract/create`, `fontInfo/fontSample/fontGrid`, `pdfThumb`, `makeTextPdf`/`makeImagePdf`: todo en el ayudante encerrado `lord-doc` — ver `docs/DOCUMENTOS.md` |
| Imprimir (M9) | `print.open({ title, path \| doc \| text \| image })` abre el diálogo del sistema; `print.printers/jobs/cancel/add/remove/setDefault/discover/scanCaps/scan` — ver `docs/IMPRESION.md` |
| Emojis (M9) | `emoji.open()` (❖.), `emoji.search/name/withTone/insert`, `EmojiGrid`, `EmojiToneBar` |
diff --git a/apps/backup/index.jsx b/apps/backup/index.jsx
index 3c7166d..25dd7d7 100644
--- a/apps/backup/index.jsx
+++ b/apps/backup/index.jsx
@@ -1,15 +1,15 @@
-// Copias de seguridad — instantáneas programadas de la carpeta personal en un disco externo o una
-// carpeta, como Time Machine (ver docs/SISTEMA.md). El motor es de lord-server (lord.backup): un
-// hilo con la prioridad más baja que copia solo lo que cambió y enlaza el resto. Esta app elige el
-// destino, la frecuencia y las exclusiones, muestra el progreso y deja recorrer las copias por fecha
-// y restaurar un archivo, una carpeta o todo.
+// Backups — scheduled snapshots of the home folder to an external disk or a folder, like Time
+// Machine (see docs/SYSTEM.md). The engine lives in lord-server (lord.backup): a lowest-priority
+// thread that copies only what changed and hard-links the rest. This app picks the destination,
+// schedule and exclusions, shows progress, and lets you browse backups by date and restore a
+// file, a folder or everything.
import {
- View, Text, ScrollView, Segmented, Toggle, Button, TextInput, useTheme, useBackup, backup, fs, wm, t as tr,
+ View, Text, ScrollView, Segmented, Toggle, Button, TextInput, useTheme, useBackup, backup, fs, wm, t as tr, tOptional,
formatBytes, formatDate, formatTime, formatNumber, direction,
} from '@lordos/sdk';
import { useEffect, useMemo, useState } from 'react';
-// ---- ícono: reloj con la flecha que vuelve (dibujado con View) ----
+// ---- icon: a clock with a returning arrow (drawn with View) ----
export function Icon({ size }) {
const s = size, ring = s * 0.62, bw = Math.max(1.5, s * 0.06);
return (
@@ -19,23 +19,25 @@ export function Icon({ size }) {
<View style={{ position: 'absolute', left: ring / 2 - bw / 2 - bw, top: ring * 0.16, width: bw, height: ring * 0.36, backgroundColor: '#fff', borderRadius: bw / 2 }} />
<View style={{ position: 'absolute', left: ring / 2 - bw, top: ring / 2 - bw * 1.5, width: ring * 0.3, height: bw, backgroundColor: '#fff', borderRadius: bw / 2 }} />
</View>
- {/* el corte de la flecha (arriba a la izquierda) y su punta */}
+ {/* the arrow's gap (top left) and its head */}
<View style={{ position: 'absolute', left: s * 0.13, top: s * 0.17, width: s * 0.2, height: s * 0.2, backgroundColor: '#25744a', borderRadius: s * 0.04 }} />
<View style={{ position: 'absolute', left: s * 0.16, top: s * 0.3, width: s * 0.17, height: bw * 1.4, backgroundColor: '#fff', borderRadius: bw }} />
<View style={{ position: 'absolute', left: s * 0.26, top: s * 0.2, width: bw * 1.4, height: s * 0.13, backgroundColor: '#fff', borderRadius: bw }} />
- {/* disco abajo */}
+ {/* disk at the bottom */}
<View style={{ position: 'absolute', bottom: s * 0.08, width: s * 0.5, height: s * 0.07, borderRadius: s * 0.03, backgroundColor: 'rgba(255,255,255,0.55)' }} />
</View>
);
}
-// ---- utilidades ----
+// ---- helpers ----
const when = (sec) => {
if (!sec) return '';
const d = new Date(sec * 1000), now = new Date();
const same = d.toDateString() === now.toDateString();
return same ? tr('backup.todayAt', { time: formatTime(d) }) : `${formatDate(d, 'short')} ${formatTime(d)}`;
};
+// error codes from C (backup.c) → translated text; anything else is shown as is
+const errText = (e) => (e ? tOptional(`backup.err.${e}`) || e : '');
const pct = (a, b) => (b > 0 ? Math.min(1, a / b) : 0);
const join = (a, b) => (a ? `${a}/${b}` : b);
@@ -88,7 +90,7 @@ function Confirm({ title, body, ok, onOk, onCancel, danger }) {
);
}
-// ---- encabezado: estado y botones ----
+// ---- header: status and buttons ----
function Header({ st }) {
const th = useTheme();
const [err, setErr] = useState('');
@@ -143,7 +145,7 @@ function Header({ st }) {
);
}
-// ---- Ajustes ----
+// ---- Settings ----
function Settings({ st }) {
const th = useTheme();
const [cfg, setCfg] = useState(() => backup.config() || { dest: '', interval: 'hourly', pauseOnBattery: true, exclude: [] });
@@ -158,7 +160,7 @@ function Settings({ st }) {
};
const expand = (p) => (p.startsWith('~') ? home + p.slice(1) : p);
const short = (p) => (home && p.startsWith(home) ? `~${p.slice(home.length)}` : p);
- useEffect(() => { const id = setInterval(() => { try { setVols(fs.volumes()); } catch (e) { /* sin discos */ } }, 5000); return () => clearInterval(id); }, []);
+ useEffect(() => { const id = setInterval(() => { try { setVols(fs.volumes()); } catch (e) { /* no disks */ } }, 5000); return () => clearInterval(id); }, []);
const removable = vols.filter((v) => v.path !== home && v.path !== '/');
return (
<ScrollView style={{ flex: 1 }}>
@@ -225,7 +227,7 @@ function Settings({ st }) {
);
}
-// ---- Cifrado (Monocypher: XChaCha20-Poly1305 por trozos, clave con Argon2id) ----
+// ---- Encryption (Monocypher: chunked XChaCha20-Poly1305, key from Argon2id) ----
function Encryption({ st, cfg, save }) {
const th = useTheme();
const [p1, setP1] = useState('');
@@ -244,7 +246,7 @@ function Encryption({ st, cfg, save }) {
run(() => { if (!cfg.encrypt) save({ ...cfg, encrypt: true }); backup.unlock(p1, true); });
};
const setup = !destEnc && (wantOn || cfg.encrypt);
- const msg = busy ? tr('backup.encWorking') : u && u.done && !u.ok ? u.error : err;
+ const msg = busy ? tr('backup.encWorking') : u && u.done && !u.ok ? errText(u.error) : err;
return (
<Card title={tr('backup.encryption')}>
{!destEnc && !setup ? (
@@ -284,7 +286,7 @@ function Encryption({ st, cfg, save }) {
);
}
-// ---- Copias: línea de tiempo y explorador ----
+// ---- Backups: timeline and browser ----
function Browser({ st }) {
const th = useTheme();
const [snaps, setSnaps] = useState(() => backup.list());
@@ -306,7 +308,7 @@ function Browser({ st }) {
}, [sel, rel]);
const busy = st && st.state !== 'idle' && st.state !== 'nodest';
const restore = (r) => { setErr(''); try { backup.restore(sel, r, { replace }); } catch (e) { setErr(String(e.message || e)); } };
- // días agrupados
+ // grouped by day
const groups = [];
for (const s of list) {
const d = new Date(s.time * 1000);
@@ -384,7 +386,7 @@ function Browser({ st }) {
<View style={{ padding: 12, gap: 8 }}>
{rr && rr.done && rr.id === sel ? (
<Label size={12} dim>{rr.ok ? tr('backup.restoredInfo', { count: rr.files, both: rr.keptBoth, replaced: rr.replaced })
- : tr('backup.restoreFailed', { error: rr.error || tr('backup.restoreErrors', { count: rr.errors }) })}</Label>
+ : tr('backup.restoreFailed', { error: errText(rr.error) || tr('backup.restoreErrors', { count: rr.errors }) })}</Label>
) : null}
{err && items.length ? <Label size={12} style={{ color: '#e5534b' }}>{err}</Label> : null}
<Row>
diff --git a/apps/backup/manifest.json b/apps/backup/manifest.json
index 3ef83e3..e16ee73 100644
--- a/apps/backup/manifest.json
+++ b/apps/backup/manifest.json
@@ -1,7 +1,7 @@
{
"id": "backup",
- "name": "Copias de seguridad",
- "description": "Copias programadas de la carpeta personal en un disco externo o una carpeta, con restauración por fecha",
+ "name": "Backups",
+ "description": "Scheduled backups of the home folder to an external disk or a folder, with restore by date",
"size": [
980,
640
diff --git a/apps/calculator/index.jsx b/apps/calculator/index.jsx
index f90fd29..b1e5708 100644
--- a/apps/calculator/index.jsx
+++ b/apps/calculator/index.jsx
@@ -75,24 +75,43 @@ export default function Calculator() {
// separador decimal de la región (1,5 o 1.5); internamente siempre '.'
const dec = formatNumber(1.5, 1)[1];
- const show = (x) => x.replace(/\./g, dec);
- const color = (k) => (k === '=' ? t.accent : '÷×-+'.includes(k) ? '#ff9f0a' : 'C()⌫'.includes(k) ? t.control : t.hover);
+ // on screen, the typographic minus (−) instead of the hyphen
+ const show = (x) => x.replace(/\./g, dec).replace(/-/g, '−');
+ const shown = /\d/.test(result) ? show(result) : result;
+ // the big number shrinks so it never gets clipped
+ const big = shown.length <= 8 ? 44 : shown.length <= 11 ? 34 : 26;
return (
- <View style={{ flex: 1, padding: 14, gap: 8, backgroundColor: t.mode === 'dark' ? '#18181b' : '#f4f4f6' }}>
- <View style={{ height: 86, justifyContent: 'flex-end', alignItems: 'flex-end', paddingHorizontal: 8, marginBottom: 4 }}>
- <Text style={{ fontSize: 14, color: t.textDim, whiteSpace: 'nowrap' }}>{show(expr) || ' '}</Text>
- <Text style={{ fontSize: 38, fontWeight: 600, color: t.text, whiteSpace: 'nowrap' }}>{/\d/.test(result) ? show(result) : result}</Text>
+ // the calculator is always left to right (as on macOS), also in Arabic or Hebrew
+ <View style={{ flex: 1, padding: 16, gap: 8, direction: 'ltr', backgroundColor: t.mode === 'dark' ? '#1c1c1e' : '#f5f5f7' }}>
+ <View style={{ height: 92, justifyContent: 'flex-end', alignItems: 'flex-end', paddingHorizontal: 6, marginBottom: 4, overflow: 'hidden' }}>
+ <Text style={{ fontSize: 13, color: t.textDim, whiteSpace: 'nowrap' }}>{show(expr) || ' '}</Text>
+ <Text style={{ fontSize: big, fontWeight: 400, color: t.text, whiteSpace: 'nowrap' }}>{shown}</Text>
</View>
{KEYS.map((row, r) => (
<View key={r} style={{ flexDirection: 'row', gap: 8, flex: 1 }}>
- {row.map((k) => (
- <View key={k} onClick={() => press(k)} style={{ flex: 1, borderRadius: 12, alignItems: 'center', justifyContent: 'center',
- backgroundColor: color(k) }}>
- <Text style={{ fontSize: 20, fontWeight: 500, color: k === '=' || '÷×-+'.includes(k) ? '#fff' : t.text }}>{k === '.' ? dec : k}</Text>
- </View>
- ))}
+ {row.map((k) => <Key key={k} k={k} label={k === '.' ? dec : k === '-' ? '−' : k} onPress={() => press(k)} />)}
</View>
))}
</View>
);
}
+
+// Key: digits, functions (C, parentheses, delete) and operators in orange; = in the accent color
+// (the primary action). Lightens on hover and dims while pressed.
+function Key({ k, label, onPress }) {
+ const t = useTheme();
+ const [hover, setHover] = useState(false);
+ const [down, setDown] = useState(false);
+ const dark = t.mode === 'dark';
+ const op = '÷×-+'.includes(k), fn = 'C()⌫'.includes(k);
+ const bg = k === '=' ? t.accent : op ? '#ff9f0a' : fn ? (dark ? '#4a4a50' : '#d4d4d9') : (dark ? '#333338' : '#ffffff');
+ return (
+ <View onMouseDown={() => setDown(true)} onMouseUp={() => setDown(false)} onClick={onPress}
+ onMouseEnter={() => setHover(true)} onMouseLeave={() => { setHover(false); setDown(false); }}
+ style={{ flex: 1, borderRadius: 12, alignItems: 'center', justifyContent: 'center', backgroundColor: bg,
+ opacity: down ? 0.7 : hover ? 0.88 : 1, boxShadow: dark ? 'none' : '0 1px 1px rgba(0,0,0,0.08)' }}>
+ <Text style={{ fontSize: op || k === '=' ? 24 : 20, fontWeight: op || k === '=' ? 500 : 400,
+ color: op || k === '=' ? '#fff' : t.text }}>{label}</Text>
+ </View>
+ );
+}
diff --git a/apps/calculator/manifest.json b/apps/calculator/manifest.json
index 5236df0..28e2071 100644
--- a/apps/calculator/manifest.json
+++ b/apps/calculator/manifest.json
@@ -8,5 +8,9 @@
],
"dock": true,
"permissions": [],
- "category": "Utility"
+ "category": "Utility",
+ "minSize": [
+ 260,
+ 380
+ ]
}
diff --git a/apps/clock/index.jsx b/apps/clock/index.jsx
index 1a71400..9b4611b 100644
--- a/apps/clock/index.jsx
+++ b/apps/clock/index.jsx
@@ -1,7 +1,7 @@
-// Reloj — reloj mundial, alarmas, temporizador y cronómetro (docs/SISTEMA.md).
-// Las alarmas, el temporizador y el cronómetro viven en el SDK (sdk/alarms.js): siguen andando y
-// suenan con la ventana cerrada. La hora de otras ciudades sale de tzdata con un lector propio
-// (lord.time.zoneOffset, server/src/ui/tzif.c), sin cambiar la zona de la sesión.
+// Clock — world clock, alarms, timer and stopwatch (docs/SYSTEM.md).
+// Alarms, the timer and the stopwatch live in the SDK (sdk/alarms.js): they keep running and ring
+// with the window closed. Other cities' times come from tzdata through our own reader
+// (lord.time.zoneOffset, server/src/ui/tzif.c), without changing the session time zone.
import {
View, Text, useTheme, useSettings, useStore, useAppWindow, t as tr, formatTime, weekdayName, formatNumber,
Segmented, Toggle, Button, Stepper, TextInput, ScrollView, clockAlarms, clockTimer, timerStart, timerPause, timerResume,
@@ -9,7 +9,7 @@ import {
} from '@lordos/sdk';
import { useEffect, useMemo, useState } from 'react';
-// ---- esfera analógica sin rotaciones: las agujas son puntos a lo largo del radio ----
+// ---- analog face without rotations: the hands are dots along the radius ----
function Face({ size, h, m, s, dark, accent }) {
const r = size / 2;
@@ -51,12 +51,12 @@ export function Icon({ size: s }) {
);
}
-// ---- utilidades ----
+// ---- utilities ----
const pad = (n) => String(n).padStart(2, '0');
const localOffset = (d) => -d.getTimezoneOffset() * 60;
-// Fecha "corrida" a la zona: sus getHours() dan la hora local de esa ciudad.
+// Date "shifted" to the zone: its getHours() give that city's local time.
function zoneDate(zone, now) {
let z = null;
try { z = lord.time.zoneOffset(zone, Math.floor(now / 1000)); } catch (e) { z = null; }
@@ -86,7 +86,7 @@ function inWords(ms) {
return hh ? tr('clock.inHours', { h: hh, m: mm }) : tr('clock.inMinutes', { m: mm });
}
-// ---- reloj mundial ----
+// ---- world clock ----
function ZonePicker({ onPick, onClose }) {
const t = useTheme();
@@ -148,7 +148,7 @@ function World() {
const now = useTick(1000);
const cities = s.clock?.cities || [];
let localZone = 'UTC';
- try { localZone = lord.time.zone(); } catch (e) { /* sin zona */ }
+ try { localZone = lord.time.zone(); } catch (e) { /* no zone */ }
const save = (list) => set({ clock: { ...(s.clock || {}), cities: list } });
return (
<View style={{ flex: 1 }}>
@@ -166,9 +166,9 @@ function World() {
);
}
-// ---- alarmas ----
+// ---- alarms ----
-// la semana empieza el lunes (como en la mayoría de las regiones de es y pt)
+// the week starts on Monday (as in most es and pt regions)
const weekOrder = () => [1, 2, 3, 4, 5, 6, 0];
function daysText(days) {
@@ -232,7 +232,7 @@ function AlarmEditor({ alarm, onClose }) {
function Alarms() {
const t = useTheme();
const [s] = useSettings();
- const [editing, setEditing] = useState(null); // null | 'new' | alarma
+ const [editing, setEditing] = useState(null); // null | 'new' | alarm
const now = useTick(30000);
const alarms = (s.clock?.alarms || []).slice().sort((a, b) => a.h * 60 + a.m - (b.h * 60 + b.m));
const next = alarms.map((a) => nextFire(a, now)).filter((x) => x != null).sort((a, b) => a - b)[0];
@@ -265,7 +265,7 @@ function Alarms() {
);
}
-// ---- temporizador ----
+// ---- timer ----
function Timer() {
const t = useTheme();
@@ -318,7 +318,7 @@ function Timer() {
);
}
-// ---- cronómetro ----
+// ---- stopwatch ----
function Stopwatch() {
const t = useTheme();
@@ -352,7 +352,7 @@ function Stopwatch() {
);
}
-// ---- ventana ----
+// ---- window ----
let lastTab = 'world';
diff --git a/apps/disks/dialogs.jsx b/apps/disks/dialogs.jsx
index 205c4c4..634e6c1 100644
--- a/apps/disks/dialogs.jsx
+++ b/apps/disks/dialogs.jsx
@@ -1,8 +1,8 @@
-// dialogs.jsx — los diálogos de Discos: formatear, renombrar, borrar y crear un USB de arranque.
+// dialogs.jsx — the Disks dialogs: format, rename, erase and create a bootable USB.
//
-// Todo lo que borra datos pasa por la misma confirmación: dice exactamente qué se pierde (modelo,
-// tamaño, cada partición con su etiqueta, sistema de archivos y dónde está montada) y, si es el
-// disco entero, pide escribir su nombre (sdb). El ayudante vuelve a validar todo del lado root.
+// Everything that erases data goes through the same confirmation: it says exactly what is lost
+// (model, size, each partition with its label, file system and mount point) and, for a whole
+// disk, asks to type its name (sdb). The helper validates everything again on the root side.
import { View, Text, ScrollView, Button, TextInput, Segmented, useTheme, useLocale, admin, fs, formatBytes, formatNumber } from '@lordos/sdk';
import { useMemo, useState } from 'react';
import { PartGlyph } from './icons.jsx';
@@ -23,7 +23,7 @@ function Card({ title, children }) {
);
}
-// Lo que se va a borrar, con todos sus datos.
+// What will be erased, with all its details.
function WhatErased({ disk, part }) {
const t = useTheme();
const { t: tr } = useLocale();
@@ -49,7 +49,7 @@ function WhatErased({ disk, part }) {
);
}
-// Paso final común: lo que se borra, el nombre escrito (disco entero) y el botón rojo.
+// Common final step: what gets erased, the typed name (whole disk) and the red button.
function Confirm({ disk, part, action, onBack, onGo }) {
const t = useTheme();
const { t: tr } = useLocale();
@@ -100,7 +100,7 @@ const parseProgress = (line) => {
return o;
};
-// Corre una acción larga con progreso; done(texto) o el error.
+// Runs a long action with progress; ends with the result text or the error.
function useJob() {
const [state, setState] = useState({ running: false, progress: null, result: null, error: null });
const start = (action, arg) => {
@@ -226,7 +226,7 @@ function ImageDialog({ disk, onClose }) {
const found = useMemo(() => {
const out = [];
for (const ext of ['.iso', '.img']) {
- try { for (const f of fs.search(home, ext, { limit: 40, depth: 4 })) if (!f.dir && f.name.toLowerCase().endsWith(ext)) out.push(f); } catch (e) { /* sin permiso */ }
+ try { for (const f of fs.search(home, ext, { limit: 40, depth: 4 })) if (!f.dir && f.name.toLowerCase().endsWith(ext)) out.push(f); } catch (e) { /* no permission */ }
}
return out.sort((a, b) => (b.mtime || 0) - (a.mtime || 0)).slice(0, 12);
}, [home]);
diff --git a/apps/disks/health.jsx b/apps/disks/health.jsx
index 6592b43..2e8d9be 100644
--- a/apps/disks/health.jsx
+++ b/apps/disks/health.jsx
@@ -1,9 +1,9 @@
-// health.jsx — salud del disco (SMART). Se lee solo cuando se pide (acción disk-smart): nunca en
-// segundo plano, así no se despierta el disco ni se frena nada.
+// health.jsx — disk health (SMART). Read only on request (disk-smart action), never in the
+// background, so the disk is not woken up and nothing stalls.
import { View, Text, Button, useTheme, useLocale, admin, formatBytes, formatNumber } from '@lordos/sdk';
import { useEffect, useState } from 'react';
-const cache = new Map(); // disco → último resultado (mientras la app está abierta)
+const cache = new Map(); // disk → last result (while the app is open)
const HEALTH_COLOR = { ok: '#30d158', warning: '#ff9f0a', failing: '#ff453a', unknown: '#8e8e93' };
const KNOWN = [1, 3, 4, 5, 7, 9, 10, 12, 177, 183, 184, 187, 188, 190, 192, 193, 194, 196, 197, 198, 199, 231, 233, 241, 242];
@@ -16,7 +16,7 @@ function readSmart(name) {
try {
if (line.startsWith('smart ')) res.summary = JSON.parse(line.slice(6));
else if (line.startsWith('attr ')) res.attrs.push(JSON.parse(line.slice(5)));
- } catch (e) { /* línea rota */ }
+ } catch (e) { /* malformed line */ }
}, { quiet: true }).then((ms) => ({ ...res, ms }));
}
diff --git a/apps/disks/icons.jsx b/apps/disks/icons.jsx
index 488af65..c479de8 100644
--- a/apps/disks/icons.jsx
+++ b/apps/disks/icons.jsx
@@ -1,5 +1,5 @@
-// icons.jsx — ícono de la app Discos y glifos de los discos, dibujados con View (sin fuentes de
-// íconos): un disco duro plateado con su plato, el brazo y la luz de actividad.
+// icons.jsx — the Disks app icon and disk glyphs, drawn with View (no icon fonts): a silver hard
+// drive with its platter, arm and activity light.
import { View } from '@lordos/sdk';
export function DisksIcon({ size: s = 32 }) {
@@ -7,18 +7,18 @@ export function DisksIcon({ size: s = 32 }) {
return (
<View style={{ width: s, height: s, borderRadius: r, overflow: 'hidden', alignItems: 'center', justifyContent: 'center',
background: 'linear-gradient(160deg, #5e6b7d, #2b323d)', boxShadow: `0 ${s * 0.04}px ${s * 0.12}px rgba(0,0,0,0.35)` }}>
- {/* carcasa */}
+ {/* case */}
<View style={{ width: s * 0.7, height: s * 0.56, borderRadius: s * 0.08, background: 'linear-gradient(180deg, #f2f4f7, #b9c0ca)',
alignItems: 'center', justifyContent: 'center', boxShadow: `0 ${s * 0.02}px ${s * 0.05}px rgba(0,0,0,0.4)` }}>
- {/* plato */}
+ {/* platter */}
<View style={{ width: s * 0.4, height: s * 0.4, borderRadius: s * 0.2, background: 'linear-gradient(140deg, #ffffff, #8f9aa8)',
border: `${Math.max(1, s * 0.02)}px solid #7d8794`, alignItems: 'center', justifyContent: 'center' }}>
<View style={{ width: s * 0.1, height: s * 0.1, borderRadius: s * 0.05, backgroundColor: '#5b6573' }} />
</View>
- {/* brazo */}
+ {/* arm */}
<View style={{ position: 'absolute', right: s * 0.08, top: s * 0.08, width: s * 0.05, height: s * 0.26, borderRadius: s * 0.025,
backgroundColor: '#4b5563' }} />
- {/* luz */}
+ {/* light */}
<View style={{ position: 'absolute', left: s * 0.06, bottom: s * 0.05, width: s * 0.06, height: s * 0.06, borderRadius: s * 0.03,
backgroundColor: '#30d158' }} />
</View>
@@ -26,7 +26,7 @@ export function DisksIcon({ size: s = 32 }) {
);
}
-// Glifo de un disco según su conexión: interno (gris), extraíble/USB (naranja), NVMe (azul), imagen.
+// Disk glyph by connection: internal (gray), removable/USB (orange), NVMe (blue), image.
export function DriveGlyph({ disk, size = 18 }) {
const usb = disk.removable || disk.transport === 'usb' || disk.transport === 'mmc';
const color = disk.transport === 'loop' ? '#a78bfa' : usb ? '#f59e0b' : disk.transport === 'nvme' ? '#3b82f6' : '#8e96a3';
@@ -42,7 +42,7 @@ export function DriveGlyph({ disk, size = 18 }) {
);
}
-// Glifo de una partición: una porción con el color del sistema de archivos.
+// Partition glyph: a block in the file system's color.
export const FS_COLORS = { vfat: '#22c55e', exfat: '#14b8a6', ntfs: '#3b82f6', ext4: '#f97316', ext3: '#fb923c', ext2: '#fdba74',
btrfs: '#eab308', xfs: '#ec4899', swap: '#8b5cf6', iso9660: '#a78bfa', crypto_LUKS: '#ef4444', '': '#9ca3af' };
export const fsColor = (fs) => FS_COLORS[fs] || '#64748b';
diff --git a/apps/disks/index.jsx b/apps/disks/index.jsx
index 627cee9..bf6c90a 100644
--- a/apps/disks/index.jsx
+++ b/apps/disks/index.jsx
@@ -1,11 +1,12 @@
-// Discos — la utilidad de discos de LordOS, como Utilidad de Discos de macOS o GNOME Discos (ver
-// docs/SISTEMA.md, «Discos»). A la izquierda los discos y sus particiones; a la derecha el uso, los
-// datos, la salud (SMART) y las acciones: montar, desmontar, expulsar, formatear, renombrar, borrar
-// y crear un USB de arranque desde una imagen.
+// Disks — the LordOS disk utility, like macOS Disk Utility or GNOME Disks (see docs/SYSTEM.md,
+// "Disks"). On the left, the disks and their partitions; on the right, usage, details, health
+// (SMART) and the actions: mount, unmount, eject, format, rename, erase and create a bootable USB
+// from an image.
//
-// La lista la lee lord-server sin root (lord.disks, actualizada sola con los avisos de montajes y de
-// udev). Todo lo que cambia algo va por el ayudante, con las acciones cerradas disk-*, que vuelven a
-// validar del lado root: nunca el disco del sistema, y los discos internos solo un administrador.
+// lord-server reads the list without root (lord.disks, refreshed by itself on mount and udev
+// events). Anything that changes something goes through the helper with the closed disk-*
+// actions, which validate again on the root side: never the system disk, and internal disks only
+// for an administrator.
import { View, Text, ScrollView, Button, useTheme, useLocale, useSystemInfo, admin, useDisks, disks, formatBytes } from '@lordos/sdk';
import { useEffect, useMemo, useState } from 'react';
import { DisksIcon, DriveGlyph, PartGlyph, fsColor } from './icons.jsx';
@@ -37,7 +38,7 @@ function Row({ label, value }) {
);
}
-// Barra de uso: un disco muestra sus particiones a escala; una partición, lo usado y lo libre.
+// Usage bar: a disk shows its partitions to scale; a partition, used and free space.
function UsageBar({ disk, part }) {
const t = useTheme();
const { t: tr } = useLocale();
@@ -220,7 +221,7 @@ export default function Disks() {
const [sel, setSel] = useState({ disk: null, part: null });
const [dialog, setDialog] = useState(null);
const tools = useMemo(() => disks.tools(), []);
- // elegir algo al abrir (el primer extraíble, si hay) y no perder la elección si desaparece
+ // pick something on open (the first removable, if any) and keep a valid selection if it disappears
const disk = list.find((d) => d.name === sel.disk) || list.find((d) => d.removable) || list[0];
const part = disk && sel.part ? disk.partitions.find((p) => p.name === sel.part) || null : null;
if (!disks.available()) {
diff --git a/apps/disks/manifest.json b/apps/disks/manifest.json
index 359c958..ab61e05 100644
--- a/apps/disks/manifest.json
+++ b/apps/disks/manifest.json
@@ -1,7 +1,7 @@
{
"id": "disks",
- "name": "Discos",
- "description": "Discos y pendrives: uso, salud (SMART), montar, formatear, borrar y crear un USB de arranque",
+ "name": "Disks",
+ "description": "Disks and USB sticks: usage, health (SMART), mount, format, erase and create a bootable USB",
"size": [960, 620],
"minSize": [760, 480],
"dock": false,
diff --git a/apps/editor/index.jsx b/apps/editor/index.jsx
index 2bd27eb..da258fb 100644
--- a/apps/editor/index.jsx
+++ b/apps/editor/index.jsx
@@ -3,7 +3,7 @@
// archivo del proyecto (❖T), resaltado de sintaxis propio y métodos de entrada.
// Ver docs/EDITOR.md.
import {
- View, Text, TextInput, Button, ScrollView, useTheme, useLocale, useAppWindow, useKeyboard, wm, fs, formatBytes, addListener, hasTextFocus, print,
+ View, Text, TextInput, Button, ScrollView, ToolbarButton, direction, useTheme, useLocale, useAppWindow, useKeyboard, wm, fs, formatBytes, addListener, hasTextFocus, print,
} from '@lordos/sdk';
import { useEffect, useMemo, useReducer, useRef, useState } from 'react';
import { Doc, cursorAt, hasSel, selStart, selEnd } from './buffer.js';
@@ -91,10 +91,10 @@ function Tree({ t, root, open, expanded, onToggle, active }) {
walk(root, 0);
return rows.map((r) => (
<View key={r.p} onClick={() => (r.dir ? onToggle(r.p) : open(`${fs.home()}/${r.p}`))}
- style={{ height: 22, flexDirection: 'row', alignItems: 'center', paddingLeft: 8 + r.depth * 14, gap: 5,
- backgroundColor: active === `${fs.home()}/${r.p}` ? t.accent : 'transparent', borderRadius: 4 }}>
- <Text style={{ width: 10, fontSize: 9, color: active === `${fs.home()}/${r.p}` ? '#fff' : t.textDim }}>{r.dir ? (expanded.has(r.p) ? '▾' : '▸') : ''}</Text>
- <Text style={{ fontSize: 12, color: active === `${fs.home()}/${r.p}` ? '#fff' : r.dir ? t.text : t.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{r.name}</Text>
+ style={{ height: 24, flexDirection: 'row', alignItems: 'center', paddingLeft: 6 + r.depth * 14, paddingRight: 8, gap: 4,
+ backgroundColor: active === `${fs.home()}/${r.p}` ? t.accent : 'transparent', borderRadius: 6 }}>
+ <Text style={{ width: 12, fontSize: 10, textAlign: 'center', color: active === `${fs.home()}/${r.p}` ? '#fff' : t.textDim }}>{r.dir ? (expanded.has(r.p) ? '▾' : '▸') : ''}</Text>
+ <Text style={{ flex: 1, fontSize: 13, color: active === `${fs.home()}/${r.p}` ? '#fff' : t.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{r.name}</Text>
</View>
));
}
@@ -111,11 +111,11 @@ function FileDialog({ t, tr, mode, start, initialName, onPick, onCancel }) {
const pickDir = mode === 'folder';
return (
<View onClick={onCancel} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.35)', alignItems: 'center' }}>
- <View onClick={(e) => e.stopPropagation()} style={{ marginTop: 40, width: 460, height: 380, padding: 12, gap: 8, borderRadius: 12,
+ <View onClick={(e) => e.stopPropagation()} style={{ marginTop: 40, width: 480, height: 400, padding: 20, gap: 12, borderRadius: 12,
backgroundColor: t.windowBg, border: `1px solid ${t.separator}`, boxShadow: '0 16px 40px rgba(0,0,0,0.45)' }}>
- <Text style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{title}</Text>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{title}</Text>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
- <Button label="‹" onClick={() => setDir(dirOf(dir))} />
+ <ToolbarButton icon={direction() === 'rtl' ? '›' : '‹'} iconSize={18} onClick={() => setDir(dirOf(dir))} />
<Text style={{ flex: 1, fontSize: 12, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{`~/${dir}`}</Text>
</View>
<View style={{ flex: 1, borderRadius: 8, border: `1px solid ${t.separator}` }}>
@@ -123,9 +123,9 @@ function FileDialog({ t, tr, mode, start, initialName, onPick, onCancel }) {
{error && <Text style={{ fontSize: 12, color: '#ff453a', margin: 6 }}>{error}</Text>}
{entries.map((e) => (
<View key={e.name} onClick={() => { if (e.dir) setDir(dir ? `${dir}/${e.name}` : e.name); else if (mode === 'save') setName(e.name); else if (!pickDir) onPick(`${fs.home()}/${dir ? `${dir}/` : ''}${e.name}`); }}
- style={{ height: 24, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 8, borderRadius: 5 }}>
+ style={{ height: 26, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 8, borderRadius: 6 }}>
<Text style={{ width: 14, fontSize: 11, color: t.textDim }}>{e.dir ? '▸' : ''}</Text>
- <Text style={{ flex: 1, fontSize: 12, color: e.dir || !pickDir ? t.text : t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{e.name}</Text>
+ <Text style={{ flex: 1, fontSize: 13, color: e.dir || !pickDir ? t.text : t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{e.name}</Text>
{!e.dir && <Text style={{ fontSize: 11, color: t.textDim }}>{formatBytes(e.size)}</Text>}
</View>
))}
@@ -153,9 +153,9 @@ function Picker({ t, title, placeholder, items, onPick, onCancel, render = (x) =
}, [q, items]);
return (
<View onClick={onCancel} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, alignItems: 'center' }}>
- <View onClick={(e) => e.stopPropagation()} style={{ marginTop: 30, width: 480, padding: 10, gap: 6, borderRadius: 12,
+ <View onClick={(e) => e.stopPropagation()} style={{ marginTop: 30, width: 480, padding: 12, gap: 8, borderRadius: 12,
backgroundColor: t.windowBg, border: `1px solid ${t.separator}`, boxShadow: '0 16px 40px rgba(0,0,0,0.45)' }}>
- {title && <Text style={{ fontSize: 12, fontWeight: 700, color: t.textDim }}>{title}</Text>}
+ {title && <Text style={{ fontSize: 11, fontWeight: 600, color: t.textDim, marginLeft: 4 }}>{title}</Text>}
<TextInput value={q} onChange={(v) => { setQ(v); setSel(0); }} placeholder={placeholder} autoFocus onCancel={onCancel}
onSubmit={() => shown[sel] && onPick(shown[sel])}
onKeyDown={(e) => {
@@ -165,7 +165,7 @@ function Picker({ t, title, placeholder, items, onPick, onCancel, render = (x) =
}} />
<View style={{ maxHeight: 330, overflow: 'hidden' }}>
{shown.map((x, i) => (
- <View key={x.key} onClick={() => onPick(x)} style={{ height: 26, justifyContent: 'center', paddingHorizontal: 8, borderRadius: 5,
+ <View key={x.key} onClick={() => onPick(x)} style={{ height: 28, justifyContent: 'center', paddingHorizontal: 10, borderRadius: 6,
backgroundColor: i === sel ? t.accent : 'transparent' }}>
{render(x, i === sel)}
</View>
@@ -196,27 +196,25 @@ function findMatches(doc, q, { regex, caseSensitive }) {
function FindBar({ t, tr, find, setFind, count, current, error, onNext, onPrev, onReplace, onReplaceAll, onClose }) {
const toggle = (k) => setFind({ ...find, [k]: !find[k] });
- const Chip = ({ k, label }) => (
- <View onClick={() => toggle(k)} style={{ height: 24, paddingHorizontal: 8, borderRadius: 6, justifyContent: 'center', backgroundColor: find[k] ? t.accent : t.control }}>
- <Text style={{ fontSize: 11, fontWeight: 700, color: find[k] ? '#fff' : t.text, fontFamily: 'monospace' }}>{label}</Text>
- </View>
+ const Chip = ({ k, label, title }) => (
+ <ToolbarButton label={label} title={title} active={find[k]} onClick={() => toggle(k)} style={{ minWidth: 34 }} />
);
return (
- <View style={{ padding: 8, gap: 6, backgroundColor: t.sidebarBg }}>
+ <View style={{ paddingVertical: 8, paddingHorizontal: 12, gap: 8, backgroundColor: t.sidebarBg }}>
<View style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 1, backgroundColor: t.separator }} />
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<TextInput value={find.query} onChange={(query) => setFind({ ...find, query })} placeholder={tr('editor.find.placeholder')} autoFocus style={{ flex: 1 }}
onSubmit={onNext} onCancel={onClose}
onKeyDown={(e) => { if (e.key === 'Enter' && e.shift) { onPrev(); return true; } return false; }} />
- <Chip k="regex" label=".*" />
- <Chip k="caseSensitive" label="Aa" />
+ <Chip k="regex" label=".*" title={tr('editor.find.regex')} />
+ <Chip k="caseSensitive" label="Aa" title={tr('editor.find.case')} />
<Text style={{ width: 92, fontSize: 11, color: error ? '#ff453a' : t.textDim, textAlign: 'center' }}>
{error ? tr('editor.find.badRegex') : find.query ? tr('editor.find.count', { current: count ? current + 1 : 0, count }) : ''}</Text>
- <Button label="↑" onClick={onPrev} />
- <Button label="↓" onClick={onNext} />
- <Button label="×" onClick={onClose} />
+ <ToolbarButton icon="↑" title={tr('editor.find.prev')} onClick={onPrev} />
+ <ToolbarButton icon="↓" title={tr('editor.find.next')} onClick={onNext} />
+ <ToolbarButton icon="✕" iconSize={12} title={tr('editor.find.close')} onClick={onClose} />
</View>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
<TextInput value={find.replace} onChange={(replace) => setFind({ ...find, replace })} placeholder={tr('editor.find.replacePlaceholder')} style={{ flex: 1 }}
onSubmit={onReplace} onCancel={onClose} />
<Button label={tr('editor.find.replace')} onClick={onReplace} />
@@ -424,16 +422,14 @@ export default function Editor() {
return (
<View style={{ flex: 1, flexDirection: 'row', backgroundColor: t.editorBg }}>
{root !== null && (
- <View style={{ width: 200, backgroundColor: t.sidebarBg }}>
+ <View style={{ width: 220, backgroundColor: t.sidebarBg }}>
<View style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 1, backgroundColor: t.separator }} />
- <View style={{ height: 30, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 10, gap: 6 }}>
- <Text style={{ flex: 1, fontSize: 11, fontWeight: 700, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>
- {(root ? baseName(root) : tr('editor.home')).toUpperCase()}</Text>
- <View onClick={() => setOverlay('folder')} style={{ paddingHorizontal: 6, paddingVertical: 2, borderRadius: 5, backgroundColor: t.control }}>
- <Text style={{ fontSize: 11, color: t.text }}>…</Text>
- </View>
+ <View style={{ height: 34, flexDirection: 'row', alignItems: 'center', paddingLeft: 18, paddingRight: 8, gap: 6 }}>
+ <Text style={{ flex: 1, fontSize: 11, fontWeight: 600, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>
+ {root ? baseName(root) : tr('editor.home')}</Text>
+ <ToolbarButton icon="⋯" small title={tr('editor.cmd.openFolder')} onClick={() => setOverlay('folder')} />
</View>
- <ScrollView style={{ flex: 1, paddingHorizontal: 4 }}>
+ <ScrollView style={{ flex: 1, paddingHorizontal: 8 }}>
<Tree t={t} root={root} open={(p) => openPath(p, { fromTree: true })} active={tab.path} expanded={expanded}
onToggle={(p) => setExpanded((s) => { const n = new Set(s); if (n.has(p)) n.delete(p); else n.add(p); return n; })} />
</ScrollView>
@@ -441,12 +437,12 @@ export default function Editor() {
)}
<View style={{ flex: 1 }}>
{/* pestañas */}
- <View style={{ height: 32, flexDirection: 'row', backgroundColor: t.sidebarBg, direction: 'ltr' }}>
+ <View style={{ height: 34, flexDirection: 'row', backgroundColor: t.sidebarBg, direction: 'ltr' }}>
<View style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 1, backgroundColor: t.separator }} />
{tabs.map((x) => {
const on = x.id === tab.id;
return (
- <View key={x.id} onClick={() => setActiveId(x.id)} style={{ maxWidth: 200, paddingLeft: 12, paddingRight: 6, flexDirection: 'row', alignItems: 'center', gap: 6,
+ <View key={x.id} onClick={() => setActiveId(x.id)} style={{ maxWidth: 200, paddingLeft: 14, paddingRight: 8, flexDirection: 'row', alignItems: 'center', gap: 6,
backgroundColor: on ? t.editorBg : 'transparent' }}>
<View style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 1, backgroundColor: t.separator }} />
<Text style={{ fontSize: 12, color: on ? t.text : t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{x.path ? baseName(x.path) : tr('editor.untitled')}</Text>
@@ -463,7 +459,7 @@ export default function Editor() {
{find.open && <FindBar t={t} tr={tr} find={find} setFind={setFind} count={found.list.length} current={current} error={found.error}
onNext={nextMatch} onPrev={prevMatch} onReplace={replaceOne} onReplaceAll={replaceAll} onClose={() => setFind((f) => ({ ...f, open: false }))} />}
{/* barra de estado */}
- <View style={{ height: 24, flexDirection: 'row', alignItems: 'center', gap: 16, paddingHorizontal: 12, backgroundColor: t.sidebarBg,
+ <View style={{ height: 26, flexDirection: 'row', alignItems: 'center', gap: 16, paddingHorizontal: 14, backgroundColor: t.sidebarBg,
direction: 'ltr' }}>
<View style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 1, backgroundColor: t.separator }} />
<Text style={{ fontSize: 11, color: t.textDim }}>{tr('editor.status.position', { line: k.l + 1, col })}</Text>
@@ -513,9 +509,9 @@ export default function Editor() {
)}
{overlay === 'gotoLine' && (
<View onClick={() => setOverlay(null)} style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, alignItems: 'center' }}>
- <View onClick={(e) => e.stopPropagation()} style={{ marginTop: 30, width: 320, padding: 10, gap: 6, borderRadius: 12, backgroundColor: t.windowBg,
+ <View onClick={(e) => e.stopPropagation()} style={{ marginTop: 30, width: 320, padding: 12, gap: 8, borderRadius: 12, backgroundColor: t.windowBg,
border: `1px solid ${t.separator}`, boxShadow: '0 16px 40px rgba(0,0,0,0.45)' }}>
- <Text style={{ fontSize: 12, fontWeight: 700, color: t.textDim }}>{tr('editor.gotoLine.title', { count: doc.lineCount })}</Text>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: t.textDim, marginLeft: 4 }}>{tr('editor.gotoLine.title', { count: doc.lineCount })}</Text>
<TextInput value={lineQuery} onChange={(v) => setLineQuery(v.replace(/[^\d:]/g, ''))} placeholder={tr('editor.gotoLine.placeholder')} autoFocus
onCancel={() => setOverlay(null)}
onSubmit={() => {
@@ -528,11 +524,11 @@ export default function Editor() {
)}
{confirmTab && (
<View style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.35)', alignItems: 'center' }}>
- <View style={{ marginTop: 60, width: 380, padding: 16, gap: 10, borderRadius: 12, backgroundColor: t.windowBg, border: `1px solid ${t.separator}`,
+ <View style={{ marginTop: 60, width: 400, padding: 20, gap: 8, borderRadius: 12, backgroundColor: t.windowBg, border: `1px solid ${t.separator}`,
boxShadow: '0 16px 40px rgba(0,0,0,0.45)' }}>
- <Text style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{tr('editor.confirm.title', { name: confirmTab.path ? baseName(confirmTab.path) : tr('editor.untitled') })}</Text>
- <Text style={{ fontSize: 12, color: t.textDim }}>{tr('editor.confirm.body')}</Text>
- <View style={{ flexDirection: 'row', gap: 8, justifyContent: 'flex-end' }}>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: t.text }}>{tr('editor.confirm.title', { name: confirmTab.path ? baseName(confirmTab.path) : tr('editor.untitled') })}</Text>
+ <Text style={{ fontSize: 13, color: t.textDim, lineHeight: 1.4 }}>{tr('editor.confirm.body')}</Text>
+ <View style={{ flexDirection: 'row', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
<Button label={tr('editor.confirm.discard')} onClick={() => {
const win = overlay.window;
confirmTab.doc.markSaved();
diff --git a/apps/files/ops.js b/apps/files/ops.js
index aab6483..7f9388c 100644
--- a/apps/files/ops.js
+++ b/apps/files/ops.js
@@ -1,6 +1,6 @@
// ops.js — lo que comparten las ventanas de Archivos: portapapeles de archivos, tareas de
// copia en curso, etiquetas de colores y abrir archivos con la app que corresponde.
-import { createStore, fs, wm, launchApp, archive } from '@lordos/sdk';
+import { createStore, fs, wm, launchApp, archive, defaultOpenerId, nativeOf } from '@lordos/sdk';
import { kindOf, mimeOf, appOpens, isTextual, isImage } from './kinds.js';
// Cambia cada vez que algo cambió en disco (copia terminada, papelera…): las vistas se recargan.
@@ -113,7 +113,16 @@ export function openersFor(e, linuxApps, t) {
if (isTextual(e) || k === 'other') out.push({ id: 'editor', label: t('apps.editor'), run: () => wm.open('editor', { args: { path: e.path } }) });
const mime = mimeOf(e);
for (const a of linuxApps) {
- if (a.kind === 'linux' && appOpens(a.mimeTypes, mime)) out.push({ id: a.id, label: a.name, run: () => lord.apps.launchWith(a.desktopId, e.path) });
+ if (a.kind === 'linux' && appOpens(a.mimeTypes, mime)) out.push({ id: a.id, desktopId: a.desktopId, label: a.name, run: () => lord.apps.launchWith(a.desktopId, e.path) });
+ }
+ // the default app for this type (Settings → Default Apps, ~/.config/mimeapps.list) goes first,
+ // marked; the type comes from the system's MIME database when it knows the name
+ const def = defaultOpenerId((typeof lord.mime !== 'undefined' && lord.mime.guess(e.name)) || mime);
+ const native = nativeOf(def);
+ const i = def ? out.findIndex((o) => (native ? o.id === native : o.desktopId && `${o.desktopId}.desktop` === def)) : -1;
+ if (i >= 0) {
+ const [d] = out.splice(i, 1);
+ out.unshift({ ...d, label: t('prefs.defaults.tag', { name: d.label }), isDefault: true });
}
return out;
}
diff --git a/apps/fonts/index.jsx b/apps/fonts/index.jsx
index 4ccbf8a..d582dfc 100644
--- a/apps/fonts/index.jsx
+++ b/apps/fonts/index.jsx
@@ -4,7 +4,7 @@
// lord-doc (FreeType), así una fuente rota o maliciosa no afecta al escritorio.
import {
View, Text, TextInput, Slider, Button, Segmented, useTheme, useAppWindow, useKeyboard, wm, fs, clipboard, DocImage, releaseImage,
- fontInfo, fontSample, fontGrid, formatBytes, t as tr,
+ fontInfo, fontSample, fontGrid, formatBytes, t as tr, SidebarItem, SectionTitle, SearchField, GroupBox, FormRow, EmptyState,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
import { BLOCKS } from './blocks.js';
@@ -85,12 +85,12 @@ function CharMap({ font, ranges, th }) {
const size = cur ? cur[2] - cur[1] + 1 : 0;
const pages = Math.ceil(size / 256);
return (
- <View style={{ flex: 1, flexDirection: 'row', gap: 12 }}>
- <View style={{ width: 190 }}>
+ <View style={{ flex: 1, flexDirection: 'row', gap: 16 }}>
+ <View style={{ width: 200 }}>
<View style={{ flex: 1, overflow: 'hidden' }}>
{blocks.slice(0, 40).map((b, i) => (
- <View key={b[0]} onClick={() => setBlock(i)} style={{ height: 24, paddingHorizontal: 8, justifyContent: 'center', borderRadius: 5, backgroundColor: i === block ? th.accent : 'transparent' }}>
- <Text style={{ fontSize: 12, color: i === block ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{tr(`fonts.block.${b[0]}`)}</Text>
+ <View key={b[0]} onClick={() => setBlock(i)} style={{ height: 26, paddingHorizontal: 10, justifyContent: 'center', borderRadius: 6, backgroundColor: i === block ? th.accent : 'transparent' }}>
+ <Text style={{ fontSize: 13, color: i === block ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{tr(`fonts.block.${b[0]}`)}</Text>
</View>
))}
</View>
@@ -113,7 +113,7 @@ function CharMap({ font, ranges, th }) {
</View>
</View>
{pick != null && (
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, padding: 8, borderRadius: 8, backgroundColor: th.control }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 8, paddingHorizontal: 12, borderRadius: 10, backgroundColor: th.control }}>
<Text style={{ fontSize: 28, color: th.text, minWidth: 40, textAlign: 'center' }}>{String.fromCodePoint(pick)}</Text>
<Text style={{ flex: 1, fontSize: 12, color: th.textDim }}>{`U+${pick.toString(16).toUpperCase().padStart(4, '0')}`}</Text>
<Button label={tr('fonts.copy')} onClick={() => clipboard.set(String.fromCodePoint(pick))} />
@@ -142,7 +142,7 @@ export default function Fonts() {
const [file, setFile] = useState(() => (args?.path && FONT_EXT.test(args.path) ? args.path : null));
useEffect(() => { if (args?.path && args?.nonce && FONT_EXT.test(args.path)) setFile(args.path); }, [args?.nonce]);
useEffect(() => { if (!msg) return undefined; const id = setTimeout(() => setMsg(null), 4000); return () => clearTimeout(id); }, [msg]);
- useEffect(() => { const id = setInterval(() => { if (pane.current) { const w = lord.getLayout(pane.current.id)[2] - 32; if (Math.abs(w - width) > 8) setWidth(w); } }, 300); return () => clearInterval(id); }, [width]);
+ useEffect(() => { const id = setInterval(() => { if (pane.current) { const w = lord.getLayout(pane.current.id)[2] - 48; if (Math.abs(w - width) > 8) setWidth(w); } }, 300); return () => clearInterval(id); }, [width]);
const visible = fams.filter((f) => (coll === 'all' || (coll === 'user' && f.user) || (coll === 'mono' && f.mono) || (coll === 'color' && f.color))
&& (!q || f.family.toLowerCase().includes(q.toLowerCase())));
@@ -201,22 +201,23 @@ export default function Fonts() {
const colls = [['all', tr('fonts.coll.all')], ['user', tr('fonts.coll.user')], ['mono', tr('fonts.coll.mono')], ['color', tr('fonts.coll.color')]];
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
- <View style={{ width: 230, backgroundColor: th.sidebarBg, padding: 8, gap: 6 }}>
+ <View style={{ width: 230, backgroundColor: th.sidebarBg, paddingTop: 12, paddingHorizontal: 10, gap: 2 }}>
+ <View style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 1, backgroundColor: th.separator }} />
+ <SearchField value={q} onChange={setQ} placeholder={tr('fonts.search')} style={{ marginBottom: 6 }} />
+ <SectionTitle>{tr('fonts.collections')}</SectionTitle>
{colls.map(([k, l]) => (
- <View key={k} onClick={() => { setColl(k); setSel(null); }} style={{ height: 24, paddingHorizontal: 8, justifyContent: 'center', borderRadius: 6, backgroundColor: coll === k ? (th.mode === 'dark' ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.08)') : 'transparent' }}>
- <Text style={{ fontSize: 13, color: th.text }}>{l}</Text>
- </View>
+ <SidebarItem key={k} label={l} selected={coll === k} onClick={() => { setColl(k); setSel(null); }} />
))}
- <TextInput value={q} onChange={setQ} placeholder={tr('fonts.search')} onCancel={() => setQ('')} style={{ height: 26, marginTop: 6 }} />
- <Text style={{ fontSize: 11, color: th.textDim, marginLeft: 4 }}>{tr('fonts.families', { count: visible.length })}</Text>
+ <View style={{ height: 6 }} />
+ <SectionTitle>{tr('fonts.families', { count: visible.length })}</SectionTitle>
<FamilyList list={visible} fileFont={fileFont} current={fam} onPick={(f) => setSel(f.file ? 'file' : f.family)} th={th} />
</View>
- <View ref={pane} style={{ flex: 1, padding: 16, gap: 10 }}>
- {!fam ? <Text style={{ fontSize: 13, color: th.textDim }}>{tr('fonts.none')}</Text> : (
+ <View ref={pane} style={{ flex: 1, paddingVertical: 20, paddingHorizontal: 24, gap: 14 }}>
+ {!fam ? <EmptyState icon="A" title={tr('fonts.none')} /> : (
<>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <View style={{ flex: 1 }}>
- <Text style={{ fontSize: 20, fontWeight: 700, color: th.text }}>{fam.family}</Text>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12 }}>
+ <View style={{ flex: 1, gap: 2, overflow: 'hidden' }}>
+ <Text style={{ fontSize: 22, fontWeight: 600, color: th.text, whiteSpace: 'nowrap' }}>{fam.family}</Text>
<Text style={{ fontSize: 12, color: th.textDim }}>{fam.file ? tr('fonts.notInstalled') : tr('fonts.styles', { count: fam.styles.length })}</Text>
</View>
{fam.file && !already ? <Button primary label={tr('fonts.install')} onClick={install} /> : null}
@@ -226,41 +227,41 @@ export default function Fonts() {
{fam.styles.length > 1 && (
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6 }}>
{fam.styles.map((s, i) => (
- <View key={`${s.path}#${s.index}`} onClick={() => setStyleIdx(i)} style={{ paddingHorizontal: 10, height: 24, borderRadius: 12, justifyContent: 'center', backgroundColor: i === styleIdx ? th.accent : th.control }}>
+ <View key={`${s.path}#${s.index}`} onClick={() => setStyleIdx(i)} style={{ paddingHorizontal: 12, height: 24, borderRadius: 12, justifyContent: 'center', backgroundColor: i === styleIdx ? th.accent : th.control }}>
<Text style={{ fontSize: 12, color: i === styleIdx ? '#fff' : th.text }}>{s.style}</Text>
</View>
))}
</View>
)}
- <Segmented value={tab} onChange={setTab} options={[['sample', tr('fonts.tab.sample')], ['chars', tr('fonts.tab.chars')], ['info', tr('fonts.tab.info')]]} />
+ <Segmented appearance="neutral" value={tab} onChange={setTab} style={{ alignSelf: 'center' }}
+ options={[['sample', tr('fonts.tab.sample')], ['chars', tr('fonts.tab.chars')], ['info', tr('fonts.tab.info')]]} />
{tab === 'sample' && (
- <View style={{ flex: 1, gap: 10 }}>
- <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
- <TextInput value={text} onChange={setText} placeholder={tr('fonts.typeHere')} style={{ flex: 1, height: 28 }} />
- <Slider value={size} min={8} max={120} onChange={(v) => setSize(Math.round(v))} width={140} />
- <Text style={{ width: 44, fontSize: 12, color: th.textDim }}>{`${size} px`}</Text>
+ <View style={{ flex: 1, gap: 12 }}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12 }}>
+ <TextInput value={text} onChange={setText} placeholder={tr('fonts.typeHere')} style={{ flex: 1 }} />
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, direction: 'ltr' }}>
+ <Text style={{ fontSize: 11, color: th.textDim }}>A</Text>
+ <Slider value={size} min={8} max={120} onChange={(v) => setSize(Math.round(v))} width={120} />
+ <Text style={{ fontSize: 17, color: th.textDim }}>A</Text>
+ </View>
+ <Text style={{ width: 48, fontSize: 12, color: th.textDim, textAlign: 'end' }}>{`${size} px`}</Text>
</View>
- <View style={{ flex: 1, overflow: 'hidden', borderRadius: 10, padding: 8, backgroundColor: th.mode === 'dark' ? '#1c1c20' : '#ffffff', border: `1px solid ${th.separator}` }}>
- <Sample font={font} text={sampleText} size={size} width={width - 20} th={th} />
- <View style={{ height: 1, backgroundColor: th.separator, marginVertical: 8 }} />
- <Sample font={font} text={tr('fonts.alphabet')} size={18} width={width - 20} th={th} extra={[12, 18, 24, 36]} />
+ <View style={{ flex: 1, overflow: 'hidden', borderRadius: 10, paddingVertical: 14, paddingHorizontal: 16, backgroundColor: th.mode === 'dark' ? '#1c1c20' : '#ffffff', border: `1px solid ${th.separator}` }}>
+ <Sample font={font} text={sampleText} size={size} width={width - 36} th={th} />
+ <View style={{ height: 1, backgroundColor: th.separator, marginVertical: 14 }} />
+ <Sample font={font} text={tr('fonts.alphabet')} size={18} width={width - 36} th={th} extra={[12, 18, 24, 36]} />
</View>
</View>
)}
{tab === 'chars' && info && !info.error && <CharMap font={font} ranges={info.ranges || []} th={th} />}
{tab === 'info' && (
<View style={{ gap: 4 }}>
- {info?.error ? <Text style={{ fontSize: 12, color: '#ff453a' }}>{tr('fonts.invalid')}</Text> : info && [
+ {info?.error ? <Text style={{ fontSize: 12, color: '#ff453a' }}>{tr('fonts.invalid')}</Text> : info && <GroupBox>{[
[tr('fonts.info.family'), info.family], [tr('fonts.info.style'), info.style], [tr('fonts.info.ps'), info.ps],
[tr('fonts.info.glyphs'), String(info.glyphs)], [tr('fonts.info.chars'), String(info.chars)],
[tr('fonts.info.kind'), [info.mono ? tr('fonts.coll.mono') : null, info.color ? tr('fonts.coll.color') : null, info.scalable ? tr('fonts.scalable') : tr('fonts.bitmap')].filter(Boolean).join(' · ')],
[tr('fonts.info.file'), font.path], [tr('fonts.info.size'), (() => { try { return formatBytes(fs.stat(font.path).size); } catch (e) { return '—'; } })()],
- ].map(([k, v]) => (
- <View key={k} style={{ flexDirection: 'row', gap: 10 }}>
- <Text style={{ width: 140, fontSize: 12, color: th.textDim, textAlign: 'end' }}>{k}</Text>
- <Text style={{ flex: 1, fontSize: 12, color: th.text }}>{v}</Text>
- </View>
- ))}
+ ].map(([k, v]) => <FormRow key={k} label={k} labelWidth={150} minHeight={32}>{v}</FormRow>)}</GroupBox>}
</View>
)}
</>
@@ -274,16 +275,16 @@ export default function Fonts() {
function FamilyList({ list, fileFont, current, onPick, th }) {
const [offset, setOffset] = useState(0);
const all = fileFont ? [fileFont, ...list] : list;
- const ROW = 24;
+ const ROW = 26;
const from = Math.floor(offset / ROW);
return (
<View onWheel={(e) => setOffset((o) => Math.max(0, Math.min(Math.max(0, all.length * ROW - 300), o + e.deltaY)))} style={{ flex: 1, overflow: 'hidden' }}>
{all.slice(from, from + 40).map((f, i) => {
const on = current && current.family === f.family && !!current.file === !!f.file;
return (
- <View key={`${f.file ? 'file:' : ''}${f.family}`} onClick={() => onPick(f)} style={{ position: 'absolute', left: 0, right: 0, top: (from + i) * ROW - offset, height: ROW, paddingHorizontal: 8,
- flexDirection: 'row', alignItems: 'center', gap: 6, borderRadius: 5, backgroundColor: on ? th.accent : 'transparent' }}>
- <Text style={{ flex: 1, fontSize: 12, color: on ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{f.family}</Text>
+ <View key={`${f.file ? 'file:' : ''}${f.family}`} onClick={() => onPick(f)} style={{ position: 'absolute', left: 0, right: 0, top: (from + i) * ROW - offset, height: ROW, paddingHorizontal: 10,
+ flexDirection: 'row', alignItems: 'center', gap: 6, borderRadius: 6, backgroundColor: on ? th.accent : 'transparent' }}>
+ <Text style={{ flex: 1, fontSize: 13, color: on ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{f.family}</Text>
{f.file ? <Text style={{ fontSize: 10, color: on ? '#fff' : th.accent }}>{tr('fonts.new')}</Text> : f.user ? <Text style={{ fontSize: 10, color: on ? '#fff' : th.textDim }}>●</Text> : null}
</View>
);
diff --git a/apps/help/index.jsx b/apps/help/index.jsx
index bf8f028..ce5aafe 100644
--- a/apps/help/index.jsx
+++ b/apps/help/index.jsx
@@ -1,7 +1,7 @@
-// Ayuda — artículos de ayuda de cada app y función, con búsqueda, y el recorrido «Bienvenido a
-// LordOS» del primer ingreso (docs/SISTEMA.md). Los artículos son markdown en
-// assets/help/<idioma>/ y los lee el SDK (sdk/help.js → lord.help). Los enlaces settings:<sección>,
-// app:<id> y help:<artículo> abren Ajustes, una app u otro artículo.
+// Help — help articles for every app and feature, with search, and the first-login "Welcome to
+// LordOS" tour (docs/SYSTEM.md). Articles are markdown in assets/help/<lang>/ (English is the
+// default) and are read by the SDK (sdk/help.js → lord.help). The links settings:<section>,
+// app:<id> and help:<article> open Settings, an app or another article.
import {
View, Text, useTheme, useAppWindow, useLocale, t as tr, help, Markdown, ScrollView, TextInput, SidebarItem, Button,
getApp, wm, appName, settings,
@@ -21,7 +21,7 @@ export function Icon({ size: s }) {
const SECTIONS = ['start', 'desktop', 'apps', 'system', 'settings'];
-// ---- recorrido de bienvenida ----
+// ---- welcome tour ----
function TourArt({ step }) {
const t = useTheme();
@@ -74,7 +74,7 @@ function Tour({ onDone }) {
);
}
-// ---- artículos ----
+// ---- articles ----
function Article({ id, onOpen }) {
const t = useTheme();
diff --git a/apps/logs/index.jsx b/apps/logs/index.jsx
index 5adce41..91e376a 100644
--- a/apps/logs/index.jsx
+++ b/apps/logs/index.jsx
@@ -1,4 +1,4 @@
-// Registros — visor de registros estilo Consola de macOS (ver docs/SISTEMA.md, «Registros»).
+// Registros — visor de registros estilo Consola de macOS (ver docs/SYSTEM.md, «Registros»).
//
// Fuentes (barra lateral):
// - LordOS: los registros de la sesión (~/.cache/lordos/*.log: session.log…);
diff --git a/apps/notes/index.jsx b/apps/notes/index.jsx
index 3c0fe93..c67a311 100644
--- a/apps/notes/index.jsx
+++ b/apps/notes/index.jsx
@@ -2,7 +2,8 @@
// notas que viven en el escritorio como widgets (se mueven, cambian de tamaño y vuelven al
// iniciar sesión). Todo se guarda solo en ~/Notas/<nota>/nota.md (ver store.js y docs/NOTAS.md).
import {
- View, Text, useTheme, useLocale, useAppWindow, useStore, useKeyboard, Button, TextInput, ScrollView, ThemeProvider,
+ View, Text, useTheme, useLocale, useAppWindow, useStore, useKeyboard, Button, TextInput, ScrollView, ThemeProvider, Segmented,
+ Toolbar, ToolbarButton, ToolbarSpacer, MenuButton, SearchField, EmptyState, textDirection,
Markdown, markdownHeadings, toggleTask, wm, fs, formatBytes, addListener, screen, t, print,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
@@ -57,7 +58,7 @@ function EmojiPicker({ onPick, onClose, x = 0, y = 0 }) {
const [cat, setCat] = useState('caras');
const list = (q ? searchEmoji(q) : EMOJIS.filter((e) => e.cat === cat)).slice(0, 96);
return (
- <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: x, top: y, width: 300, padding: 8, gap: 6, borderRadius: 10,
+ <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: x, top: y, width: 308, padding: 10, gap: 8, borderRadius: 12,
backgroundColor: th.windowBg, border: `1px solid ${th.separator}`, boxShadow: '0 12px 30px rgba(0,0,0,0.35)' }}>
<TextInput value={q} onChange={setQ} placeholder={tr('notes.emoji.search')} autoFocus onCancel={onClose}
onSubmit={() => list[0] && onPick(list[0].ch)} />
@@ -92,17 +93,17 @@ function FilePicker({ onPick, onClose, images }) {
try { entries = fs.list(dir || '.').filter((e) => !e.name.startsWith('.') && (e.dir || !images || isImage(e.name))); } catch (e) { entries = []; }
entries.sort((a, b) => (b.dir - a.dir) || a.name.localeCompare(b.name));
return (
- <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 40, top: 50, right: 40, bottom: 40, padding: 10, gap: 6, borderRadius: 10,
+ <View onMouseDown={(e) => e.stopPropagation?.()} style={{ position: 'absolute', left: 32, top: 52, right: 32, bottom: 32, padding: 16, gap: 10, borderRadius: 12,
backgroundColor: th.windowBg, border: `1px solid ${th.separator}`, boxShadow: '0 14px 36px rgba(0,0,0,0.4)' }}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
- <Button label="‹" onClick={() => setDir(dir.split('/').slice(0, -1).join('/'))} />
- <Text style={{ flex: 1, fontSize: 13, fontWeight: 600, color: th.text }}>{`~/${dir}`}</Text>
+ <ToolbarButton icon="‹" iconSize={18} onClick={() => setDir(dir.split('/').slice(0, -1).join('/'))} />
+ <Text style={{ flex: 1, fontSize: 13, fontWeight: 600, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{`~/${dir}`}</Text>
<Button label={tr('notes.close')} onClick={onClose} />
</View>
<ScrollView style={{ flex: 1 }}>
{entries.map((e) => (
<View key={e.name} onClick={() => (e.dir ? setDir(dir ? `${dir}/${e.name}` : e.name) : onPick(`${fs.home()}/${dir ? `${dir}/` : ''}${e.name}`))}
- style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingVertical: 5, paddingHorizontal: 6, borderRadius: 5 }}>
+ style={{ height: 28, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 8, borderRadius: 6 }}>
<Text style={{ fontSize: 15 }}>{e.dir ? '📁' : isImage(e.name) ? '🖼️' : '📄'}</Text>
<Text style={{ flex: 1, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{e.name}</Text>
{!e.dir && <Text style={{ fontSize: 11, color: th.textDim }}>{formatBytes(e.size)}</Text>}
@@ -152,21 +153,23 @@ function NoteBody({ note, mode, onMode, editorApi, compact, showToc, size = 14,
sc.scrollTo(lord.getLayout(n.id)[1] - lord.getLayout(sc.inner.current.id)[1] - 4);
};
return (
- <View ref={box} style={{ flex: 1, flexDirection: 'row' }}>
+ // the note's own direction (an Arabic note reads right to left even in a Spanish interface)
+ <View ref={box} style={{ flex: 1, flexDirection: 'row', direction: textDirection(note.body) }}>
{showToc && toc.length > 1 && (
- <View style={{ width: 170, paddingVertical: 12, paddingHorizontal: 10, gap: 2, borderRight: `1px solid ${th.separator}` }}>
- <Text style={{ fontSize: 10, fontWeight: 700, color: th.textDim, marginBottom: 4 }}>{t('notes.toc')}</Text>
+ <View style={{ width: 180, paddingTop: 20, paddingHorizontal: 16, gap: 2 }}>
+ <View style={{ position: 'absolute', right: 0, top: 16, bottom: 16, width: 1, backgroundColor: th.separator }} />
+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginBottom: 6 }}>{t('notes.toc')}</Text>
{toc.map((h) => (
- <View key={h.id} onClick={() => jump(h.id)} style={{ paddingVertical: 3, paddingLeft: (h.level - 1) * 10 }}>
+ <View key={h.id} onClick={() => jump(h.id)} style={{ paddingVertical: 4, paddingLeft: (h.level - 1) * 10 }}>
<Text style={{ fontSize: 12, color: h.level === 1 ? th.text : th.textDim, fontWeight: h.level === 1 ? 600 : 400, whiteSpace: 'nowrap', overflow: 'hidden' }}>{h.text}</Text>
</View>
))}
</View>
)}
<ScrollView scrollRef={scroll} style={{ flex: 1 }}>
- <View onDoubleClick={() => onMode('edit')} style={{ padding: compact ? 10 : 18, minHeight: 60 }}>
+ <View onDoubleClick={() => onMode('edit')} style={{ paddingVertical: compact ? 10 : 20, paddingHorizontal: compact ? 10 : 28, minHeight: 60 }}>
{note.body.trim() ? (
- <Markdown source={note.body} base={absFolder(note.slug)} width={Math.max(80, w - (showToc && toc.length > 1 ? 170 : 0) - (compact ? 20 : 36))} size={size}
+ <Markdown source={note.body} base={absFolder(note.slug)} width={Math.max(80, w - (showToc && toc.length > 1 ? 180 : 0) - (compact ? 20 : 56))} size={size}
emoji={emojiFor} onLink={(u) => openLink(note.slug, u)} onHeadingRef={(id, n) => { if (n) heads.current.set(id, n); }}
onToggleTask={(line) => updateNote(note.slug, { body: toggleTask(note.body, line) })} />
) : <Text style={{ fontSize: 13, color: th.textDim }}>{t('notes.empty')}</Text>}
@@ -320,72 +323,83 @@ export default function Notes() {
] },
]);
});
- const colorBar = note && (
- <View style={{ flexDirection: 'row', gap: 5, alignItems: 'center' }}>
- {COLORS.map((c) => <Dot key={c} color={c} size={14} selected={c === note.color} onClick={() => updateNote(note.slug, { color: c }, { touch: false })} />)}
- </View>
- );
- const ToolBtn = ({ label, onClick, active }) => (
- <View onClick={onClick} style={{ height: 26, paddingHorizontal: 9, borderRadius: 6, justifyContent: 'center', backgroundColor: active ? th.accent : th.control }}>
- <Text style={{ fontSize: 12, color: active ? '#fff' : th.text, whiteSpace: 'nowrap' }}>{label}</Text>
- </View>
- );
+ // window width: a narrower sidebar and a compact toolbar in small windows
+ const root = useRef(null);
+ const [winW, setWinW] = useState(860);
+ useEffect(() => {
+ const id = setInterval(() => { if (root.current) { const w = lord.getLayout(root.current.id)[2]; if (Math.abs(w - winW) > 2) setWinW(w); } }, 300);
+ return () => clearInterval(id);
+ }, [winW]);
+ const sideW = winW < 720 ? 200 : 240;
+ const compact = winW - sideW < 470;
+ const colorItems = note ? COLORS.map((c) => ({ label: tr(`notes.color.${c}`), checked: c === note.color, onClick: () => updateNote(note.slug, { color: c }, { touch: false }) })) : [];
return (
- <View style={{ flex: 1, flexDirection: 'row' }}>
- <View style={{ width: 230, backgroundColor: th.sidebarBg, padding: 8, gap: 6 }}>
- <View style={{ flexDirection: 'row', gap: 6 }}>
- <TextInput value={q} onChange={setQ} placeholder={tr('notes.search')} onCancel={() => setQ('')} style={{ flex: 1 }} />
- <Button label="+" onClick={newNote} />
+ <View ref={root} style={{ flex: 1, flexDirection: 'row' }}>
+ <View style={{ width: sideW, backgroundColor: th.sidebarBg, paddingTop: 12, paddingHorizontal: 10, gap: 10 }}>
+ <View style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 1, backgroundColor: th.separator }} />
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
+ <SearchField value={q} onChange={setQ} placeholder={tr('notes.search')} style={{ flex: 1 }} />
+ <ToolbarButton icon="✎" title={tr('notes.new')} onClick={newNote} />
</View>
<ScrollView style={{ flex: 1 }}>
{shown.map((n) => {
const on = note && n.slug === note.slug;
+ const pv = previewOf(n.body);
return (
- <View key={n.slug} onClick={() => { setSel(n.slug); setMode('read'); }} style={{ flexDirection: 'row', gap: 8, padding: 8, borderRadius: 8, marginBottom: 2,
- backgroundColor: on ? th.accent : 'transparent' }}>
- <View style={{ width: 10, height: 34, borderRadius: 3, backgroundColor: PAPER[n.color][1] }} />
+ <View key={n.slug} onClick={() => { setSel(n.slug); setMode('read'); }} style={{ flexDirection: 'row', gap: 10, paddingVertical: 9, paddingHorizontal: 10,
+ borderRadius: 8, marginBottom: 2, backgroundColor: on ? th.accent : 'transparent' }}>
+ <View style={{ width: 8, height: 8, borderRadius: 4, marginTop: 5, backgroundColor: PAPER[n.color][1], border: '1px solid rgba(0,0,0,0.12)' }} />
<View style={{ flex: 1, gap: 2 }}>
<Text style={{ fontSize: 13, fontWeight: 600, color: on ? '#fff' : th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{n.title || tr('notes.untitled')}</Text>
- <Text style={{ fontSize: 11, color: on ? 'rgba(255,255,255,0.8)' : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>
- {`${fmtDate(n.updated, formatDate)}${n.desktop ? ` · ${tr('notes.onDesktop')}` : ''}`}</Text>
+ <View style={{ flexDirection: 'row', gap: 6, overflow: 'hidden' }}>
+ <Text style={{ fontSize: 11, color: on ? 'rgba(255,255,255,0.85)' : th.text, whiteSpace: 'nowrap' }}>{fmtDate(n.updated, formatDate)}</Text>
+ <Text style={{ flex: 1, fontSize: 11, color: on ? 'rgba(255,255,255,0.75)' : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden',
+ direction: n.desktop ? 'inherit' : textDirection(pv) }}>{n.desktop ? tr('notes.onDesktop') : pv}</Text>
+ </View>
</View>
</View>
);
})}
- {!shown.length && <Text style={{ fontSize: 12, color: th.textDim, margin: 8 }}>{loaded ? tr('notes.none') : '…'}</Text>}
+ {!shown.length && <Text style={{ fontSize: 12, color: th.textDim, margin: 10 }}>{loaded ? tr('notes.none') : '…'}</Text>}
</ScrollView>
</View>
{note ? (
<View style={{ flex: 1 }}>
- <View style={{ flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', gap: 6, paddingHorizontal: 10, paddingVertical: 7, borderBottom: `1px solid ${th.separator}` }}>
- <ToolBtn label={tr('notes.read')} active={mode === 'read'} onClick={() => setMode('read')} />
- <ToolBtn label={tr('notes.edit')} active={mode === 'edit'} onClick={() => setMode('edit')} />
- <View style={{ width: 6 }} />
- {colorBar}
- <View style={{ width: 6 }} />
- <ToolBtn label="😀" onClick={() => setPanel(panel === 'emoji' ? null : 'emoji')} active={panel === 'emoji'} />
- <ToolBtn label={tr('notes.image')} onClick={() => setPanel('image')} />
- <ToolBtn label={tr('notes.attach')} onClick={() => setPanel('attach')} />
- <ToolBtn label={tr('notes.showDesktop')} active={note.desktop} onClick={cmd.desktop} />
- <View style={{ flex: 1 }} />
- <ToolBtn label={tr('notes.duplicate')} onClick={cmd.duplicate} />
- <ToolBtn label={tr('notes.delete')} onClick={cmd.del} />
- </View>
+ <Toolbar>
+ <Segmented appearance="neutral" value={mode} onChange={setMode} options={[['read', tr('notes.read')], ['edit', tr('notes.edit')]]} />
+ {!compact && <View style={{ flexDirection: 'row', gap: 6, alignItems: 'center', marginLeft: 8 }}>
+ {COLORS.map((c) => <Dot key={c} color={c} size={14} selected={c === note.color} onClick={() => updateNote(note.slug, { color: c }, { touch: false })} />)}
+ </View>}
+ <ToolbarSpacer />
+ <MenuButton icon="⊕" title={tr('notes.insert')} items={[
+ { label: tr('notes.insertEmoji'), onClick: () => setPanel('emoji') },
+ { label: tr('notes.insertImage'), onClick: () => setPanel('image') },
+ { label: tr('notes.insertFile'), onClick: () => setPanel('attach') },
+ ]} />
+ <MenuButton title={tr('notes.more')} items={[
+ { label: tr('notes.duplicate'), onClick: cmd.duplicate },
+ { label: tr('notes.showDesktop'), checked: !!note.desktop, onClick: cmd.desktop },
+ { label: tr('notes.openFolder'), onClick: cmd.folder },
+ ...(compact ? ['-', ...colorItems] : []),
+ '-',
+ { label: tr('notes.delete'), destructive: true, onClick: cmd.del },
+ ]} />
+ </Toolbar>
<View style={{ flex: 1, backgroundColor: PAPER[note.color][0] }}>
<ThemeProvider tokens={paperTokens(th)}>
- <NoteBody key={note.slug} note={note} mode={mode} onMode={setMode} editorApi={api} showToc={toc} onCommand={(b) => (b === 'n' ? cmd.new() : b === 'e' ? cmd.toggle() : null)} />
+ <NoteBody key={note.slug} note={note} mode={mode} onMode={setMode} editorApi={api} showToc={toc && winW - sideW >= 520} onCommand={(b) => (b === 'n' ? cmd.new() : b === 'e' ? cmd.toggle() : null)} />
</ThemeProvider>
</View>
- {panel === 'emoji' && <EmojiPicker x={180} y={40} onClose={() => setPanel(null)} onPick={(ch) => { insert(ch); setPanel(null); }} />}
+ {panel === 'emoji' && <EmojiPicker x={Math.max(8, winW - sideW - 316)} y={48} onClose={() => setPanel(null)} onPick={(ch) => { insert(ch); setPanel(null); }} />}
{(panel === 'attach' || panel === 'image') && (
<FilePicker images={panel === 'image'} onClose={() => setPanel(null)} onPick={(p) => { insert(attachFile(note.slug, p), true); setPanel(null); }} />
)}
{panel === 'delete' && (
<View style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center', backgroundColor: 'rgba(0,0,0,0.25)' }}>
- <View style={{ width: 320, padding: 16, gap: 10, borderRadius: 12, backgroundColor: th.windowBg, border: `1px solid ${th.separator}` }}>
- <Text style={{ fontSize: 14, fontWeight: 700, color: th.text }}>{tr('notes.deleteTitle', { title: note.title || tr('notes.untitled') })}</Text>
- <Text style={{ fontSize: 12, color: th.textDim, lineHeight: 1.4 }}>{tr('notes.deleteHint')}</Text>
- <View style={{ flexDirection: 'row', gap: 8, justifyContent: 'flex-end' }}>
+ <View style={{ width: 340, padding: 20, gap: 8, borderRadius: 12, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`, boxShadow: '0 16px 40px rgba(0,0,0,0.4)' }}>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: th.text }}>{tr('notes.deleteTitle', { title: note.title || tr('notes.untitled') })}</Text>
+ <Text style={{ fontSize: 13, color: th.textDim, lineHeight: 1.4 }}>{tr('notes.deleteHint')}</Text>
+ <View style={{ flexDirection: 'row', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
<Button label={tr('notes.cancel')} onClick={() => setPanel(null)} />
<Button primary label={tr('notes.delete')} onClick={() => { deleteNote(note.slug); setSel(null); setPanel(null); }} />
</View>
@@ -394,12 +408,15 @@ export default function Notes() {
)}
</View>
) : (
- <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: 10 }}>
- <Icon size={64} />
- <Text style={{ fontSize: 13, color: th.textDim }}>{tr('notes.none')}</Text>
- <Button primary label={tr('notes.new')} onClick={newNote} />
- </View>
+ <EmptyState icon={<Icon size={56} />} title={tr('notes.none')} hint={tr('notes.noneHint')}
+ action={<Button primary label={tr('notes.new')} onClick={newNote} />} />
)}
</View>
);
}
+
+// Preview line of a note: the first line with text after the title, without markdown marks.
+function previewOf(body) {
+ const lines = body.split('\n').map((l) => l.trim()).filter((l) => l && !/^(`{3,}|---|#)/.test(l));
+ return (lines[0] || '').replace(/^(>\s*|[-*+]\s+(\[[ xX]\]\s+)?|\d+[.)]\s+)/, '').replace(/[*_`~]|!\[[^\]]*\]\([^)]*\)/g, '').slice(0, 80);
+}
diff --git a/apps/passwords/ui.jsx b/apps/passwords/ui.jsx
index 5588c96..9039b55 100644
--- a/apps/passwords/ui.jsx
+++ b/apps/passwords/ui.jsx
@@ -11,7 +11,7 @@ export const RED = '#ff453a', ORANGE = '#ff9f0a', GREEN = '#30d158', YELLOW = '#
export function CatIcon({ cat, size = 28 }) {
const b = cat ? builtinById(cat.id) : null;
const color = cat?.color || b?.color || '#8e8e93';
- const icon = cat?.icon || b?.icon || '🗂️';
+ const icon = /^[a-z_-]+$/i.test(cat?.icon || '') ? '📁' : cat?.icon || b?.icon || '🗂️';
return (
<View style={{ width: size, height: size, borderRadius: size * 0.26, alignItems: 'center', justifyContent: 'center',
background: `linear-gradient(160deg, ${color}, ${shade(color, -0.25)})` }}>
diff --git a/apps/pdf/index.jsx b/apps/pdf/index.jsx
index 5308cc8..73d1cc3 100644
--- a/apps/pdf/index.jsx
+++ b/apps/pdf/index.jsx
@@ -4,8 +4,8 @@
// copia, modo oscuro con la página invertida e imprimir con el diálogo del sistema.
// Poppler corre en el ayudante encerrado lord-doc (ver docs/DOCUMENTOS.md); esta app solo pide.
import {
- View, Text, TextInput, useTheme, useAppWindow, useKeyboard, addListener, wm, fs, clipboard, pdf, print, DocImage, releaseImage,
- formatNumber, t as tr,
+ View, Text, TextInput, Button, useTheme, useAppWindow, useKeyboard, addListener, wm, fs, clipboard, pdf, print, DocImage, releaseImage,
+ formatNumber, direction, t as tr, Toolbar, ToolbarButton, ToolbarGroup, ToolbarSpacer, SearchField, EmptyState,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
import { PageCache } from './cache.js';
@@ -54,20 +54,34 @@ function ToolBtn({ label, onClick, active, disabled, th, title }) {
function Welcome({ onOpen, th }) {
const [list, setList] = useState(null);
useEffect(() => { const id = setTimeout(() => { try { setList(fs.search(fs.home(), '.pdf', { limit: 40, depth: 6 }).filter((e) => /\.pdf$/i.test(e.name))); } catch (e) { setList([]); } }, 30); return () => clearTimeout(id); }, []);
+ const box = th.mode === 'dark' ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.7)';
return (
- <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: 14, padding: 30 }}>
- <Icon size={72} />
- <Text style={{ fontSize: 16, fontWeight: 700, color: th.text }}>{tr('pdf.welcome')}</Text>
- <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>{tr('pdf.welcomeHint')}</Text>
- <View style={{ width: 420, maxHeight: 260, gap: 2 }}>
- {list == null ? <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>{tr('pdf.searching')}</Text>
- : list.length ? list.slice(0, 10).map((e) => (
- <View key={e.path} onClick={() => onOpen(e.path)} style={{ flexDirection: 'row', gap: 8, paddingHorizontal: 10, height: 26, alignItems: 'center', borderRadius: 6, backgroundColor: th.control }}>
- <Text style={{ fontSize: 12, color: '#ff453a', fontWeight: 700 }}>PDF</Text>
- <Text style={{ flex: 1, fontSize: 12, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{e.name}</Text>
- </View>
- )) : <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>{tr('pdf.noneFound')}</Text>}
- </View>
+ <View style={{ position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, direction: direction() }}>
+ <EmptyState icon={<Icon size={64} />} title={tr('pdf.welcome')} hint={tr('pdf.welcomeHint')} action={
+ <View style={{ width: 420, maxHeight: 300, gap: 6 }}>
+ {list == null ? <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>{tr('pdf.searching')}</Text>
+ : list.length ? (
+ <>
+ <Text style={{ fontSize: 11, fontWeight: 600, color: th.textDim, marginLeft: 8 }}>{tr('pdf.recent')}</Text>
+ <View style={{ borderRadius: 10, backgroundColor: box, border: `1px solid ${th.separator}`, overflow: 'hidden' }}>
+ {list.slice(0, 8).map((e, i) => <RecentRow key={e.path} e={e} first={i === 0} onOpen={onOpen} th={th} />)}
+ </View>
+ </>
+ ) : <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>{tr('pdf.noneFound')}</Text>}
+ </View>
+ } />
+ </View>
+ );
+}
+
+function RecentRow({ e, first, onOpen, th }) {
+ const [hover, setHover] = useState(false);
+ return (
+ <View onClick={() => onOpen(e.path)} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ height: 32, flexDirection: 'row', gap: 10, paddingHorizontal: 12, alignItems: 'center', backgroundColor: hover ? th.hover : 'transparent' }}>
+ {!first ? <View style={{ position: 'absolute', left: 12, right: 0, top: 0, height: 1, backgroundColor: th.separator }} /> : null}
+ <Text style={{ fontSize: 10, color: '#ff453a', fontWeight: 700 }}>PDF</Text>
+ <Text style={{ flex: 1, fontSize: 13, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{e.name}</Text>
</View>
);
}
@@ -561,44 +575,45 @@ export default function PdfViewer() {
}
const barBg = dark ? 'rgba(0,0,0,0.12)' : 'rgba(0,0,0,0.03)';
+ const winW = view.w + (side && doc ? 184 : 0);
const pageLabel = n ? tr('pdf.pageOf', { page: page + 1, count: n }) : '';
return (
<View style={{ flex: 1 }}>
- {/* barra de herramientas */}
- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 10 }}>
- <ToolBtn th={th} label="◧" active={!!side} onClick={() => setSide((s) => (s ? null : 'thumbs'))} />
- <Text style={{ fontSize: 14, fontWeight: 700, color: th.text, whiteSpace: 'nowrap', overflow: 'hidden', marginHorizontal: 6, maxWidth: 220 }}>{path ? fs.basename(path) : tr('apps.pdf')}</Text>
+ {/* toolbar: icon-only items with tooltips, as in Preview; the narrow window drops what is also in the menus */}
+ <Toolbar style={{ gap: 6 }}>
+ <ToolbarButton icon="◫" title={tr('pdf.tool.sidebar')} active={!!side} onClick={() => setSide((s) => (s ? null : 'thumbs'))} />
{goto != null ? (
<TextInput autoFocus value={goto} onChange={setGoto} placeholder={tr('pdf.goPlaceholder')} onCancel={() => setGoto(null)}
- onSubmit={() => { const v = Number(goto); setGoto(null); if (v >= 1) goPage(v - 1); }} style={{ width: 90, height: 24 }} />
+ onSubmit={() => { const v = Number(goto); setGoto(null); if (v >= 1) goPage(v - 1); }} style={{ width: 96 }} />
) : (
- <View onClick={() => doc && setGoto('')}><Text style={{ fontSize: 12, color: th.textDim, whiteSpace: 'nowrap' }}>{pageLabel}</Text></View>
+ <View onClick={() => doc && setGoto('')} style={{ paddingHorizontal: 4, overflow: 'hidden', flexShrink: 1 }}>
+ <Text style={{ fontSize: 12, color: th.textDim, whiteSpace: 'nowrap' }}>{winW < 640 ? (n ? `${page + 1} / ${n}` : '') : pageLabel}</Text>
+ </View>
)}
- <View style={{ flex: 1 }} />
- <View style={{ flexDirection: 'row', backgroundColor: th.control, borderRadius: 7, padding: 2, direction: 'ltr' }}>
- <ToolBtn th={th} label="−" onClick={() => zoomStep(-1)} disabled={!doc} />
- <View onClick={() => setZoomTo(zoom === 'width' ? 'page' : 'width')} style={{ minWidth: 46, alignItems: 'center', justifyContent: 'center' }}>
- <Text style={{ fontSize: 11, color: th.text }}>{doc ? `${formatNumber(pct)} %` : ''}</Text>
+ <ToolbarSpacer />
+ <ToolbarGroup style={{ direction: 'ltr' }}>
+ <ToolbarButton icon="−" small title={tr('pdf.zoom.out')} onClick={() => zoomStep(-1)} disabled={!doc} />
+ <View onClick={() => setZoomTo(zoom === 'width' ? 'page' : 'width')} style={{ minWidth: 48, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 11, fontWeight: 500, color: th.text }}>{doc ? `${formatNumber(pct)} %` : '—'}</Text>
</View>
- <ToolBtn th={th} label="+" onClick={() => zoomStep(1)} disabled={!doc} />
- </View>
- <ToolBtn th={th} label="↻" onClick={() => rotate(1)} disabled={!doc} />
- <View style={{ flexDirection: 'row', backgroundColor: th.control, borderRadius: 7, padding: 2 }}>
- <ToolBtn th={th} label="I" active={tool === 'select'} onClick={() => setTool('select')} disabled={!doc} />
- <ToolBtn th={th} label="▬" active={tool === 'highlight'} onClick={() => setTool('highlight')} disabled={!doc} />
- <ToolBtn th={th} label="✎" active={tool === 'ink'} onClick={() => setTool((x) => (x === 'ink' ? 'select' : 'ink'))} disabled={!doc} />
- <ToolBtn th={th} label="🗨" active={tool === 'note'} onClick={() => setTool('note')} disabled={!doc} />
- </View>
+ <ToolbarButton icon="+" small title={tr('pdf.zoom.in')} onClick={() => zoomStep(1)} disabled={!doc} />
+ </ToolbarGroup>
+ {winW >= 760 && <ToolbarButton icon="↻" title={tr('pdf.rotateRight')} onClick={() => rotate(1)} disabled={!doc} />}
+ <ToolbarGroup>
+ <ToolbarButton icon="I" small iconSize={13} title={tr('pdf.tool.select')} active={tool === 'select'} onClick={() => setTool('select')} disabled={!doc} />
+ <ToolbarButton icon="▬" small iconSize={11} title={tr('pdf.tool.highlight')} active={tool === 'highlight'} onClick={() => setTool('highlight')} disabled={!doc} />
+ <ToolbarButton icon="✎" small title={tr('pdf.tool.ink')} active={tool === 'ink'} onClick={() => setTool((x) => (x === 'ink' ? 'select' : 'ink'))} disabled={!doc} />
+ <ToolbarButton icon="▤" small title={tr('pdf.tool.note')} active={tool === 'note'} onClick={() => setTool('note')} disabled={!doc} />
+ </ToolbarGroup>
{(tool === 'highlight' || tool === 'ink') && (
- <View style={{ flexDirection: 'row', gap: 3 }}>
+ <View style={{ flexDirection: 'row', gap: 4 }}>
{TOOL_COLORS.map((c) => <View key={c} onClick={() => setColor(c)} style={{ width: 14, height: 14, borderRadius: 7, backgroundColor: c, border: `2px solid ${color === c ? th.text : 'transparent'}` }} />)}
</View>
)}
- <ToolBtn th={th} label="◐" active={invert} onClick={() => setInvert((v) => !v)} disabled={!doc} />
- <ToolBtn th={th} label="⎙" onClick={doPrint} disabled={!doc} />
- <FindField th={th} query={query} setQuery={setQuery} hits={hits} onFind={runFind} onNext={nextHit} focusReq={findRef} disabled={!doc} />
- </View>
- <View style={{ height: 1, backgroundColor: th.separator }} />
+ {winW >= 760 && <ToolbarButton icon="◐" title={tr('pdf.invert')} active={invert} onClick={() => setInvert((v) => !v)} disabled={!doc} />}
+ {winW >= 760 && <ToolbarButton icon="⎙" title={tr('pdf.menu.print')} onClick={doPrint} disabled={!doc} />}
+ <FindField th={th} query={query} setQuery={setQuery} hits={hits} onFind={runFind} onNext={nextHit} focusReq={findRef} disabled={!doc} width={winW < 760 ? 130 : 180} />
+ </Toolbar>
<View style={{ flex: 1, flexDirection: 'row' }}>
{side && doc && (
<Sidebar side={side} setSide={setSide} doc={doc} sizes={sizes} page={page} onPage={goPage} cache={thumbs.current} rot={rot} invert={invert} rev={rev} th={th} />
@@ -611,8 +626,8 @@ export default function PdfViewer() {
{!path && <Welcome th={th} onOpen={setPath} />}
{path && !doc && !error && !needPass && <Text style={{ margin: 40, fontSize: 13, color: th.textDim, textAlign: 'center' }}>{tr('pdf.opening')}</Text>}
{needPass && (
- <View style={{ position: 'absolute', left: view.w / 2 - 150, top: view.h / 2 - 60, width: 300, padding: 16, gap: 10, borderRadius: 12, backgroundColor: th.windowBg, boxShadow: '0 12px 30px rgba(0,0,0,0.4)' }}>
- <Text style={{ fontSize: 13, fontWeight: 700, color: th.text }}>{tr('pdf.passwordTitle')}</Text>
+ <View style={{ position: 'absolute', left: view.w / 2 - 160, top: view.h / 2 - 70, width: 320, padding: 20, gap: 12, borderRadius: 12, backgroundColor: th.windowBg, boxShadow: '0 12px 30px rgba(0,0,0,0.4)' }}>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: th.text }}>{tr('pdf.passwordTitle')}</Text>
<PassField onSubmit={(p) => setPassword(p)} />
{error ? <Text style={{ fontSize: 11, color: '#ff453a' }}>{error}</Text> : null}
</View>
@@ -620,10 +635,7 @@ export default function PdfViewer() {
{error && !needPass && (
<View style={{ position: 'absolute', left: 0, right: 0, top: view.h / 2 - 40, alignItems: 'center', gap: 10 }}>
<Text style={{ fontSize: 13, color: '#ff453a', textAlign: 'center' }}>{error}</Text>
- <View onClick={() => { const p = path; setError(null); setPath(null); setTimeout(() => setPath(p), 0); }}
- style={{ paddingHorizontal: 12, height: 26, borderRadius: 6, justifyContent: 'center', backgroundColor: th.control }}>
- <Text style={{ fontSize: 12, color: th.text }}>{tr('pdf.reopen')}</Text>
- </View>
+ <Button label={tr('pdf.reopen')} onClick={() => { const p = path; setError(null); setPath(null); setTimeout(() => setPath(p), 0); }} />
</View>
)}
{/* barra de desplazamiento */}
@@ -634,7 +646,8 @@ export default function PdfViewer() {
</View>
</View>
{/* barra de estado */}
- <View style={{ height: 24, flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 10, backgroundColor: barBg }}>
+ <View style={{ height: 26, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 12, backgroundColor: barBg }}>
+ <View style={{ position: 'absolute', left: 0, right: 0, top: 0, height: 1, backgroundColor: th.separator }} />
<Text style={{ flex: 1, fontSize: 11, color: msg ? th.accent : th.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>
{msg || (hits ? (hits.list.length ? tr('pdf.matches', { cur: hits.cur + 1, count: hits.list.length }) + (hits.done ? '' : '…') : hits.done ? tr('pdf.noMatches') : tr('pdf.searchingText'))
: selection?.text ? tr('pdf.selected', { count: selection.text.length }) : tool === 'ink' ? tr('pdf.inkHint') : tool === 'note' ? tr('pdf.noteTool') : tool === 'highlight' ? tr('pdf.highlightHint') : doc?.info.title || '')}
@@ -648,17 +661,17 @@ export default function PdfViewer() {
function PassField({ onSubmit }) {
const [v, setV] = useState('');
- return <TextInput autoFocus secure value={v} onChange={setV} onSubmit={() => onSubmit(v)} placeholder={tr('pdf.password')} style={{ height: 26 }} />;
+ return <TextInput autoFocus secure value={v} onChange={setV} onSubmit={() => onSubmit(v)} placeholder={tr('pdf.password')} />;
}
-function FindField({ th, query, setQuery, hits, onFind, onNext, focusReq, disabled }) {
+function FindField({ th, query, setQuery, hits, onFind, onNext, focusReq, disabled, width = 180 }) {
const [key, setKey] = useState(0);
useEffect(() => { if (focusReq.current) { focusReq.current = false; setKey((k) => k + 1); } });
useEffect(() => { const id = setTimeout(() => onFind(query), 350); return () => clearTimeout(id); }, [query]);
- if (disabled) return <View style={{ width: 170 }} />;
+ if (disabled) return <View style={{ width }} />;
return (
- <TextInput key={key} autoFocus={key > 0} value={query} onChange={setQuery} placeholder={tr('pdf.find')} onCancel={() => setQuery('')}
+ <SearchField key={key} autoFocus={key > 0} value={query} onChange={setQuery} placeholder={tr('pdf.find')}
onSubmit={() => (hits?.list.length ? onNext(1) : onFind(query))} onKeyDown={(e) => { if (e.key === 'Enter' && e.shift) { onNext(-1); return true; } return false; }}
- style={{ width: 170, height: 26 }} />
+ width={width} />
);
}
diff --git a/apps/pdf/sidebar.jsx b/apps/pdf/sidebar.jsx
index e9e1350..7ea38d2 100644
--- a/apps/pdf/sidebar.jsx
+++ b/apps/pdf/sidebar.jsx
@@ -4,7 +4,7 @@ import { View, Text, Segmented, DocImage, t as tr } from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
import { shown } from './geometry.js';
-const W = 168, TW = 112;
+const W = 184, TW = 116;
function Thumbs({ doc, sizes, page, onPage, cache, rot, invert, th }) {
const [offset, setOffset] = useState(0);
@@ -38,12 +38,12 @@ function Thumbs({ doc, sizes, page, onPage, cache, rot, invert, th }) {
const e = cache?.get(i, TW, rot, invert) || cache?.best(i, rot, invert, TW);
return (
<View key={i} onClick={() => onPage(i)} style={{ position: 'absolute', left: 0, right: 0, top: tops[i] - offset, alignItems: 'center', gap: 4 }}>
- <View style={{ width: TW + 6, height: th2 + 6, borderRadius: 4, alignItems: 'center', justifyContent: 'center', backgroundColor: i === page ? th.accent : 'transparent' }}>
+ <View style={{ width: TW + 8, height: th2 + 8, borderRadius: 5, alignItems: 'center', justifyContent: 'center', border: `3px solid ${i === page ? th.accent : 'transparent'}` }}>
<View style={{ width: TW, height: th2, backgroundColor: invert ? '#1b1b1f' : '#ffffff', boxShadow: '0 1px 4px rgba(0,0,0,0.35)' }}>
{e ? <DocImage image={e.image} style={{ width: TW, height: th2, objectFit: 'fill' }} /> : null}
</View>
</View>
- <Text style={{ fontSize: 10, color: i === page ? th.text : th.textDim }}>{String(i + 1)}</Text>
+ <Text style={{ fontSize: 11, fontWeight: i === page ? 600 : 400, color: i === page ? th.text : th.textDim }}>{String(i + 1)}</Text>
</View>
);
})}
@@ -57,11 +57,11 @@ function OutlineItems({ items, depth, onPage, page, th, open, toggle, path }) {
const isOpen = open.has(key) || (it.open && !open.has(`!${key}`));
return (
<View key={key}>
- <View onClick={() => it.page >= 0 && onPage(it.page)} style={{ flexDirection: 'row', alignItems: 'center', minHeight: 24, paddingRight: 6, paddingLeft: 4 + depth * 12, borderRadius: 5 }}>
+ <View onClick={() => it.page >= 0 && onPage(it.page)} style={{ flexDirection: 'row', alignItems: 'center', minHeight: 26, paddingRight: 8, paddingLeft: 4 + depth * 12, borderRadius: 6 }}>
<View onClick={(e) => { e.stopPropagation(); toggle(key, isOpen); }} style={{ width: 14, alignItems: 'center' }}>
{it.kids ? <Text style={{ fontSize: 8, color: th.textDim }}>{isOpen ? '▼' : '▶'}</Text> : null}
</View>
- <Text style={{ flex: 1, fontSize: 12, color: th.text, lineHeight: 16 }}>{it.title}</Text>
+ <Text style={{ flex: 1, fontSize: 12, fontWeight: depth === 0 ? 500 : 400, color: th.text, lineHeight: 16 }}>{it.title}</Text>
{it.page >= 0 ? <Text style={{ fontSize: 10, color: th.textDim }}>{String(it.page + 1)}</Text> : null}
</View>
{it.kids && isOpen ? <OutlineItems items={it.kids} depth={depth + 1} onPage={onPage} page={page} th={th} open={open} toggle={toggle} path={`${key}.`} /> : null}
@@ -80,7 +80,7 @@ function Outline({ doc, onPage, page, th }) {
if (!items.length) return <Text style={{ margin: 12, fontSize: 12, color: th.textDim }}>{tr('pdf.noOutline')}</Text>;
return (
<View onWheel={(e) => setOffset((o) => Math.max(0, o + e.deltaY))} style={{ flex: 1, overflow: 'hidden' }}>
- <View style={{ translateY: -offset, padding: 4 }}>
+ <View style={{ translateY: -offset, paddingHorizontal: 8, paddingVertical: 4 }}>
<OutlineItems items={items} depth={0} onPage={onPage} page={page} th={th} open={open} toggle={toggle} path="" />
</View>
</View>
@@ -90,8 +90,8 @@ function Outline({ doc, onPage, page, th }) {
export function Sidebar({ side, setSide, doc, sizes, page, onPage, cache, rot, invert, th }) {
return (
<View style={{ width: W, backgroundColor: th.sidebarBg }}>
- <View style={{ padding: 8, alignItems: 'center' }}>
- <Segmented value={side} onChange={setSide} options={[['thumbs', tr('pdf.side.thumbsShort')], ['outline', tr('pdf.side.outlineShort')]]} />
+ <View style={{ paddingHorizontal: 12, paddingTop: 10, paddingBottom: 6 }}>
+ <Segmented appearance="neutral" small fill value={side} onChange={setSide} options={[['thumbs', tr('pdf.side.thumbsShort')], ['outline', tr('pdf.side.outlineShort')]]} />
</View>
{side === 'thumbs'
? <Thumbs doc={doc} sizes={sizes} page={page} onPage={onPage} cache={cache} rot={rot} invert={invert} th={th} />
diff --git a/apps/photos/index.jsx b/apps/photos/index.jsx
index 34321c6..9053187 100644
--- a/apps/photos/index.jsx
+++ b/apps/photos/index.jsx
@@ -6,7 +6,7 @@
// (recorte, giro, brillo y contraste) se guardan como una copia: el original no se toca.
import {
View, Text, Image, MediaView, ScrollView, SidebarItem, SectionTitle, Button, Slider, useTheme, useAppWindow, useKeyboard, useWindowState, wm,
- t as tr, media, useThumb, userDirs, fs, addListener, direction, print,
+ t as tr, media, useThumb, userDirs, fs, addListener, direction, print, ThemeProvider, ToolbarButton, ToolbarGroup, EmptyState, useStore, windows,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
@@ -48,8 +48,8 @@ function Thumb({ e, size, selected, onOpen, onSelect }) {
const thumb = useThumb(e.path, 256);
return (
<View onClick={onSelect} onDoubleClick={onOpen} style={{ width: size, height: size, borderRadius: 6, overflow: 'hidden', backgroundColor: th.control,
- border: selected ? `2px solid ${th.accent}` : '2px solid transparent', alignItems: 'center', justifyContent: 'center' }}>
- {thumb ? <Image src={thumb} style={{ width: size - 4, height: size - 4, objectFit: 'cover' }} />
+ border: selected ? `3px solid ${th.accent}` : '0px solid transparent', alignItems: 'center', justifyContent: 'center' }}>
+ {thumb ? <Image src={thumb} style={{ width: selected ? size - 6 : size, height: selected ? size - 6 : size, objectFit: 'cover', borderRadius: selected ? 3 : 0 }} />
: <Text style={{ fontSize: 10, color: th.textDim }}>{e.name.split('.').pop().toUpperCase()}</Text>}
</View>
);
@@ -209,23 +209,29 @@ function Viewer({ list, index, setIndex, onClose, winId, mode }) {
};
const full = mode === 'fullscreen';
+ // the viewer is always dark (photos look best on a dark surround), in light mode too
return (
+ <ThemeProvider tokens={viewerTokens(th)}>
<View style={{ flex: 1, backgroundColor: full ? '#000' : '#141416' }}>
{!full && (
- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 4, backgroundColor: '#1d1d20' }}>
- <ToolBtn dark glyph={direction() === 'rtl' ? '›' : '‹'} label={tr('photos.library')} onClick={onClose} />
- <View style={{ flex: 1, alignItems: 'center' }}>
- <Text style={{ fontSize: 12, color: '#eee', whiteSpace: 'nowrap' }}>{baseName(path)}</Text>
- <Text style={{ fontSize: 10, color: '#999' }}>{info?.sourceWidth ? `${info.sourceWidth} × ${info.sourceHeight}` : ''}{list.length > 1 ? ` · ${index + 1} / ${list.length}` : ''}</Text>
+ <View style={{ height: 52, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 12, gap: 8, backgroundColor: '#1d1d20' }}>
+ <ToolbarButton icon={direction() === 'rtl' ? '›' : '‹'} iconSize={18} label={tr('photos.library')} onClick={onClose} />
+ <View style={{ flex: 1, alignItems: 'center', overflow: 'hidden' }}>
+ <Text style={{ fontSize: 13, fontWeight: 600, color: '#f5f5f7', whiteSpace: 'nowrap' }}>{baseName(path)}</Text>
+ <Text style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)', whiteSpace: 'nowrap' }}>{info?.sourceWidth ? `${info.sourceWidth} × ${info.sourceHeight}` : ''}{list.length > 1 ? ` · ${index + 1} / ${list.length}` : ''}</Text>
</View>
- <ToolBtn dark glyph="−" onClick={() => zoomBy(0.8)} />
- <ToolBtn dark glyph="⤢" label={zoom ? `${Math.round(zoom * 100)} %` : tr('photos.fit')} onClick={() => setZoomAt(zoom ? 0 : 1)} />
- <ToolBtn dark glyph="+" onClick={() => zoomBy(1.25)} />
- <ToolBtn dark glyph="⟲" onClick={() => setRot((r) => r - 90)} />
- <ToolBtn dark glyph="⟳" onClick={() => setRot((r) => r + 90)} />
- <ToolBtn dark glyph="✎" label={tr('photos.edit')} active={!!edit} onClick={() => setEdit(edit ? null : { bright: 0, contrast: 0, crop: null })} />
- <ToolBtn dark glyph="▶" label={tr('photos.slideshow')} onClick={() => setSlide(true)} />
- <ToolBtn dark glyph="⛶" onClick={() => wm.setFullscreen(winId, true)} />
+ <ToolbarGroup>
+ <ToolbarButton icon="−" small title={tr('photos.zoomOut')} onClick={() => zoomBy(0.8)} />
+ <View onClick={() => setZoomAt(zoom ? 0 : 1)} style={{ minWidth: 56, alignItems: 'center' }}>
+ <Text style={{ fontSize: 11, fontWeight: 500, color: '#f5f5f7', whiteSpace: 'nowrap' }}>{zoom ? `${Math.round(zoom * 100)} %` : tr('photos.fit')}</Text>
+ </View>
+ <ToolbarButton icon="+" small title={tr('photos.zoomIn')} onClick={() => zoomBy(1.25)} />
+ </ToolbarGroup>
+ <ToolbarButton icon="⟲" title={tr('photos.rotateLeft')} onClick={() => setRot((r) => r - 90)} />
+ <ToolbarButton icon="⟳" title={tr('photos.rotateRight')} onClick={() => setRot((r) => r + 90)} />
+ <ToolbarButton icon="▶" iconSize={13} title={tr('photos.slideshow')} onClick={() => setSlide(true)} />
+ <ToolbarButton icon="⛶" title={tr('photos.fullscreen')} onClick={() => wm.setFullscreen(winId, true)} />
+ <ToolbarButton icon="✎" label={tr('photos.edit')} active={!!edit} onClick={() => setEdit(edit ? null : { bright: 0, contrast: 0, crop: null })} />
</View>
)}
<View ref={box} style={{ flex: 1, overflow: 'hidden' }}
@@ -274,10 +280,10 @@ function Viewer({ list, index, setIndex, onClose, winId, mode }) {
</View>}
</View>
{edit && !full && (
- <View style={{ height: 56, flexDirection: 'row', alignItems: 'center', gap: 14, paddingHorizontal: 14, backgroundColor: '#1d1d20' }}>
+ <View style={{ height: 56, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, backgroundColor: '#1d1d20' }}>
<Text style={{ fontSize: 12, color: '#ccc' }}>{tr('photos.brightness')}</Text>
<Slider value={edit.bright} min={-100} max={100} width={130} onChange={(v) => setEdit({ ...edit, bright: Math.round(v) })} />
- <Text style={{ fontSize: 12, color: '#ccc' }}>{tr('photos.contrast')}</Text>
+ <Text style={{ fontSize: 12, color: '#ccc', marginLeft: 8 }}>{tr('photos.contrast')}</Text>
<Slider value={edit.contrast} min={-100} max={100} width={130} onChange={(v) => setEdit({ ...edit, contrast: Math.round(v) })} />
<Text style={{ fontSize: 11, color: '#999', flex: 1 }}>{edit.crop ? tr('photos.cropReady') : tr('photos.cropHint')}</Text>
<Button label={tr('photos.reset')} onClick={() => { setEdit({ bright: 0, contrast: 0, crop: null }); setRot(0); }} />
@@ -285,6 +291,25 @@ function Viewer({ list, index, setIndex, onClose, winId, mode }) {
</View>
)}
</View>
+ </ThemeProvider>
+ );
+}
+
+// Tokens for the viewer's always-dark chrome (toolbar buttons, tooltips, sliders).
+const viewerTokens = (th) => ({ ...th, mode: 'dark', text: '#f5f5f7', textDim: 'rgba(235,235,245,0.55)', hover: 'rgba(255,255,255,0.1)',
+ control: 'rgba(255,255,255,0.1)', separator: 'rgba(255,255,255,0.1)', windowBg: '#1f1f23', inputBg: '#2a2a2f' });
+
+// Small folder icon for the sidebar (the folder emoji is a color picture; macOS uses a line glyph).
+function FolderGlyph({ on }) {
+ const th = useTheme();
+ const c = on ? '#fff' : th.accent;
+ return (
+ <View style={{ width: 18, alignItems: 'center' }}>
+ <View style={{ width: 15, height: 11, marginTop: 2 }}>
+ <View style={{ position: 'absolute', left: 0, top: 0, width: 6, height: 3, borderRadius: 1, backgroundColor: c }} />
+ <View style={{ position: 'absolute', left: 0, top: 2, width: 15, height: 9, borderRadius: 2, border: `1.5px solid ${c}` }} />
+ </View>
+ </View>
);
}
@@ -299,6 +324,7 @@ export default function Photos() {
const [viewer, setViewer] = useWindowState('viewer', null); // { list, index } (sobrevive a la pantalla completa)
const [size, setSize] = useState(132);
const [rev, setRev] = useState(0);
+ const winW = useStore(windows, (ws) => ws.find((w) => w.id === win.id)?.w || 980);
useEffect(() => {
const out = [];
@@ -325,6 +351,8 @@ export default function Photos() {
onClose={() => { setViewer(null); wm.setTitle(win.id, null); wm.setFullscreen(win.id, false); }} />;
}
+ // narrow window (close to minSize): a smaller title so it is not clipped
+ const narrow = winW < 700;
// agrupado por mes, como una fototeca
const groups = [];
for (const e of items) {
@@ -335,32 +363,37 @@ export default function Photos() {
}
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
- <View style={{ width: 190, backgroundColor: th.sidebarBg, padding: 8, gap: 2 }}>
+ <View style={{ width: 210, backgroundColor: th.sidebarBg, paddingTop: 8, paddingHorizontal: 10, gap: 2 }}>
+ <View style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 1, backgroundColor: th.separator }} />
<SectionTitle>{tr('photos.library')}</SectionTitle>
<SidebarItem label={tr('photos.allPhotos')} icon="▦" selected={all && folder === dirs.pictures} onClick={() => { setFolder(dirs.pictures); setAll(true); }} />
+ <View style={{ height: 8 }} />
<SectionTitle>{tr('photos.folders')}</SectionTitle>
{subfolders(dirs.pictures).map((f) => (
- <SidebarItem key={f} label={baseName(f)} icon="📁" selected={!all && folder === f} onClick={() => { setFolder(f); setAll(false); }} />
+ <SidebarItem key={f} label={baseName(f)} icon={<FolderGlyph on={!all && folder === f} />} selected={!all && folder === f} onClick={() => { setFolder(f); setAll(false); }} />
))}
</View>
<View style={{ flex: 1 }}>
- <View style={{ height: 44, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, gap: 10 }}>
- <Text style={{ fontSize: 17, fontWeight: 700, color: th.text, flex: 1 }}>{all ? tr('photos.allPhotos') : baseName(folder)}</Text>
- <Text style={{ fontSize: 11, color: th.textDim }}>{tr('photos.count', { count: items.length })}</Text>
- <Slider value={size} min={80} max={240} width={100} onChange={(v) => setSize(Math.round(v))} />
- <View onClick={() => setRev((r) => r + 1)} style={{ paddingHorizontal: 6 }}><Text style={{ fontSize: 14, color: th.textDim }}>↻</Text></View>
+ <View style={{ height: 64, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 20, gap: 12 }}>
+ <View style={{ flex: 1, overflow: 'hidden' }}>
+ <Text style={{ fontSize: narrow ? 17 : 22, fontWeight: 600, color: th.text, whiteSpace: 'nowrap' }}>{all ? tr('photos.allPhotos') : baseName(folder)}</Text>
+ <Text style={{ fontSize: 11, color: th.textDim, whiteSpace: 'nowrap' }}>{tr('photos.count', { count: items.length })}</Text>
+ </View>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6, direction: 'ltr' }}>
+ {!narrow && <View style={{ width: 8, height: 8, borderRadius: 2, border: `1.5px solid ${th.textDim}` }} />}
+ <Slider value={size} min={80} max={240} width={narrow ? 72 : 96} onChange={(v) => setSize(Math.round(v))} />
+ {!narrow && <View style={{ width: 13, height: 13, borderRadius: 3, border: `1.5px solid ${th.textDim}` }} />}
+ </View>
+ <ToolbarButton icon="↻" title={tr('photos.refresh')} onClick={() => setRev((r) => r + 1)} />
</View>
- <ScrollView style={{ flex: 1, paddingHorizontal: 14 }}>
+ <ScrollView style={{ flex: 1, paddingHorizontal: 20 }}>
{!items.length && (
- <View style={{ padding: 40, alignItems: 'center', gap: 6 }}>
- <Text style={{ fontSize: 30 }}>🖼</Text>
- <Text style={{ fontSize: 13, color: th.textDim, textAlign: 'center' }}>{tr('photos.empty')}</Text>
- </View>
+ <EmptyState icon="▦" title={tr('photos.emptyTitle')} hint={tr('photos.empty')} style={{ paddingTop: 80 }} />
)}
{groups.map((g) => (
- <View key={g.k} style={{ gap: 8, marginBottom: 14 }}>
- <Text style={{ fontSize: 13, fontWeight: 600, color: th.text }}>{tr('photos.monthYear', { month: tr(`photos.month.${g.date.getMonth()}`), year: g.date.getFullYear() })}</Text>
- <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6 }}>
+ <View key={g.k} style={{ gap: 10, marginBottom: 24 }}>
+ <Text style={{ fontSize: 15, fontWeight: 600, color: th.text }}>{tr('photos.monthYear', { month: tr(`photos.month.${g.date.getMonth()}`), year: g.date.getFullYear() })}</Text>
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 4 }}>
{g.list.map((e) => (
<Thumb key={e.path} e={e} size={size} selected={sel === e.path} onSelect={() => setSel(e.path)}
onOpen={() => setViewer({ list: items, index: items.indexOf(e) })} />
diff --git a/apps/settings/Bluetooth.jsx b/apps/settings/Bluetooth.jsx
new file mode 100644
index 0000000..314abce
--- /dev/null
+++ b/apps/settings/Bluetooth.jsx
@@ -0,0 +1,117 @@
+// Settings → Bluetooth: on/off, my devices (connect, disconnect, forget) and nearby devices
+// (pair). BlueZ over the system bus, from lord-server (server/src/hw/bt.c); PIN and passkey
+// requests are drawn by the system (sdk/hardware.jsx, BluetoothPrompt). Headphones and speakers
+// show up in Sound through PipeWire. See docs/SETTINGS.md, "Bluetooth".
+import { View, Text, useTheme, useLocale, Toggle, Button, MenuButton, admin, useBluetooth, onBluetoothResult } from '@lordos/sdk';
+import { useEffect, useState } from 'react';
+import { GroupBox, SettingRow, PageHeader, Note, Stack } from './ui.jsx';
+
+const GLYPHS = [[/headset|headphones/, '🎧'], [/audio/, '🔊'], [/keyboard/, '⌨'], [/mouse|tablet/, '🖱'], [/gaming|joystick/, '🎮'],
+ [/phone/, '📱'], [/computer/, '💻'], [/camera/, '📷'], [/printer/, '⎙']];
+const glyphOf = (icon) => (GLYPHS.find(([re]) => re.test(icon || '')) || [null, 'ᛒ'])[1];
+
+export function BtIcon({ size = 44 }) {
+ return (
+ <View style={{ width: size, height: size, borderRadius: size * 0.24, background: 'linear-gradient(180deg, #3a9bff, #0a6cd6)', alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: size * 0.58, fontWeight: 700, color: '#fff', lineHeight: size }}>ᛒ</Text>
+ </View>
+ );
+}
+
+function DeviceIcon({ icon }) {
+ const t = useTheme();
+ return (
+ <View style={{ width: 28, height: 28, borderRadius: 14, backgroundColor: t.control, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 14, color: t.text }}>{glyphOf(icon)}</Text>
+ </View>
+ );
+}
+
+function Device({ d, tr }) {
+ const t = useTheme();
+ const status = d.busy ? tr('prefs.bt.working') : d.connected ? tr('prefs.bt.connected') : tr('prefs.bt.notConnected');
+ const battery = d.battery >= 0 ? ` · ${tr('prefs.bt.battery', { pct: d.battery })}` : '';
+ if (!d.paired) {
+ return (
+ <SettingRow icon={<DeviceIcon icon={d.icon} />} label={d.name} hint={d.rssi != null ? tr('prefs.bt.signal', { dbm: d.rssi }) : ''}>
+ {d.busy ? <Text style={{ fontSize: 12, color: t.textDim }}>{tr('prefs.bt.pairing')}</Text>
+ : <Button small label={tr('prefs.bt.connect')} onClick={() => lord.bt.pair(d.path)} />}
+ </SettingRow>
+ );
+ }
+ return (
+ <SettingRow icon={<DeviceIcon icon={d.icon} />} label={d.name} hint={`${status}${battery}`}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
+ {!d.busy && <Button small label={d.connected ? tr('prefs.bt.disconnect') : tr('prefs.bt.connect')}
+ onClick={() => (d.connected ? lord.bt.disconnect(d.path) : lord.bt.connect(d.path))} />}
+ <MenuButton small title={tr('prefs.bt.more')} items={[
+ { label: d.connected ? tr('prefs.bt.disconnect') : tr('prefs.bt.connect'), onClick: () => (d.connected ? lord.bt.disconnect(d.path) : lord.bt.connect(d.path)) },
+ '-',
+ { label: tr('prefs.bt.forget'), destructive: true, onClick: () => lord.bt.forget(d.path) },
+ ]} />
+ </View>
+ </SettingRow>
+ );
+}
+
+export function BluetoothSettings() {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const st = useBluetooth();
+ const [err, setErr] = useState('');
+ const a = st?.adapter;
+ // discovery while the page is open and Bluetooth is on (like macOS)
+ useEffect(() => {
+ if (!a?.powered) return undefined;
+ lord.bt.discover(true);
+ return () => lord.bt.discover(false);
+ }, [a?.powered, a?.path]);
+ useEffect(() => onBluetoothResult((r) => {
+ if (r.ok || r.op === 'stop') { if (r.ok && r.op !== 'stop') setErr(''); return; }
+ const key = /Blocked|rfkill/i.test(r.error) ? 'blocked' : /profile-unavailable|NotAvailable|NotSupported/i.test(r.error) ? 'noProfile'
+ : /AuthenticationFailed|AuthenticationRejected|Rejected/i.test(r.error) ? 'authFailed'
+ : /Canceled|AuthenticationCanceled/i.test(r.error) ? 'canceled' : /AlreadyExists/i.test(r.error) ? '' : 'failed';
+ if (key) setErr(key);
+ }), []);
+ if (!st || !st.available || !a) {
+ return (
+ <Stack>
+ <PageHeader icon={<BtIcon />} title={tr('prefs.bt.title')} subtitle={tr(st?.available ? 'prefs.bt.noAdapter' : 'prefs.bt.noService')} />
+ </Stack>
+ );
+ }
+ const mine = st.devices.filter((d) => d.paired).sort((x, y) => (y.connected - x.connected) || x.name.localeCompare(y.name));
+ const near = st.devices.filter((d) => !d.paired && (d.named || d.busy)).sort((x, y) => (y.rssi ?? -200) - (x.rssi ?? -200));
+ const togglePower = (on) => {
+ setErr('');
+ lord.bt.power(on);
+ };
+ return (
+ <Stack>
+ <PageHeader icon={<BtIcon />} title={tr('prefs.bt.title')}
+ subtitle={a.powered ? tr('prefs.bt.visibleAs', { name: a.name || a.address }) : tr('prefs.bt.offHint')}>
+ <Toggle on={a.powered} onChange={togglePower} />
+ </PageHeader>
+ {err === 'blocked' ? (
+ <GroupBox>
+ <SettingRow label={tr('prefs.bt.err.blocked')}>
+ <Button small label={tr('prefs.bt.unblock')} onClick={() => admin.run('bt-unblock').then(() => { setErr(''); lord.bt.power(true); }, (e) => setErr(e.message))} />
+ </SettingRow>
+ </GroupBox>
+ ) : err ? <Note tone="warn">{tr(`prefs.bt.err.${err}`) || err}</Note> : null}
+ {a.powered && (
+ <GroupBox title={tr('prefs.bt.myDevices')}>
+ {mine.length ? mine.map((d) => <Device key={d.path} d={d} tr={tr} />) : <SettingRow label={tr('prefs.bt.noDevices')} />}
+ </GroupBox>
+ )}
+ {a.powered && (
+ <GroupBox title={a.discovering ? tr('prefs.bt.nearbySearching') : tr('prefs.bt.nearby')} footer={tr('prefs.bt.nearbyHint')}>
+ {near.length ? near.map((d) => <Device key={d.path} d={d} tr={tr} />)
+ : <SettingRow label={a.discovering ? tr('prefs.bt.searching') : tr('prefs.bt.noneNearby')} />}
+ </GroupBox>
+ )}
+ {a.powered ? <Note>{tr('prefs.bt.audioHint')}</Note> : null}
+ {!st.agent && a.powered ? <Note tone="warn">{tr('prefs.bt.noAgent')}</Note> : null}
+ </Stack>
+ );
+}
diff --git a/apps/settings/DateTime.jsx b/apps/settings/DateTime.jsx
new file mode 100644
index 0000000..b144081
--- /dev/null
+++ b/apps/settings/DateTime.jsx
@@ -0,0 +1,133 @@
+// Settings → Date & Time: set the time automatically (NTP with systemd-timesyncd, closed admin action
+// time-ntp) or by hand (time-set), the time zone (chosen from a list: it is never guessed from the
+// network, so no IP is sent anywhere), the 12/24-hour clock and the menu bar clock format.
+// See docs/SETTINGS.md, "Date & Time".
+import {
+ View, Text, useTheme, useLocale, useSettings, Toggle, Button, TextInput, ScrollView, SearchField, admin, useTimedate, clockPrefs, menuClock,
+ formatDate, formatTime, useClock,
+} from '@lordos/sdk';
+import { useEffect, useState } from 'react';
+import { GroupBox, SettingRow, PopUp, Note, Stack } from './ui.jsx';
+
+const pad = (n) => String(n).padStart(2, '0');
+const isoDate = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+const offsetText = (sec) => {
+ const s = sec < 0 ? '−' : '+', a = Math.abs(sec);
+ return `UTC${s}${pad(Math.floor(a / 3600))}:${pad(Math.floor(a / 60) % 60)}`;
+};
+
+function ZonePicker({ zone, onPick, tr }) {
+ const t = useTheme();
+ const [q, setQ] = useState('');
+ const [all] = useState(() => lord.time.zones().sort());
+ const now = Math.floor(Date.now() / 1000);
+ const needle = q.trim().toLowerCase().replace(/ /g, '_');
+ const shown = (needle ? all.filter((z) => z.toLowerCase().includes(needle)) : all).slice(0, 400);
+ return (
+ <View style={{ gap: 8, paddingVertical: 8 }}>
+ <SearchField value={q} onChange={setQ} placeholder={tr('prefs.time.searchZone')} autoFocus />
+ <View style={{ height: 220, borderRadius: 8, border: `1px solid ${t.separator}` }}>
+ <ScrollView style={{ padding: 4 }}>
+ {shown.map((z) => {
+ const off = lord.time.zoneOffset ? lord.time.zoneOffset(z, now) : null;
+ const on = z === zone;
+ const parts = z.split('/');
+ return (
+ <View key={z} onClick={() => onPick(z)} style={{ height: 26, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 8, borderRadius: 5,
+ backgroundColor: on ? t.accent : 'transparent' }}>
+ <Text style={{ flex: 1, fontSize: 12, color: on ? '#fff' : t.text, whiteSpace: 'nowrap', textAlign: 'start' }}>{parts[parts.length - 1].replace(/_/g, ' ')}</Text>
+ <Text style={{ fontSize: 11, color: on ? '#fff' : t.textDim, whiteSpace: 'nowrap' }}>{parts.slice(0, -1).join(' / ').replace(/_/g, ' ')}</Text>
+ <Text style={{ width: 84, fontSize: 11, color: on ? '#fff' : t.textDim, textAlign: 'end', direction: 'ltr' }}>{off ? offsetText(off.offset) : ''}</Text>
+ </View>
+ );
+ })}
+ </ScrollView>
+ </View>
+ </View>
+ );
+}
+
+function ManualTime({ tr, onDone }) {
+ const now = new Date();
+ const [date, setDate] = useState(isoDate(now));
+ const [time, setTime] = useState(`${pad(now.getHours())}:${pad(now.getMinutes())}`);
+ const [err, setErr] = useState('');
+ const valid = /^\d{4}-\d{2}-\d{2}$/.test(date) && /^\d{2}:\d{2}$/.test(time);
+ return (
+ <View style={{ paddingVertical: 8, gap: 8 }}>
+ <View style={{ flexDirection: 'row', gap: 8, alignItems: 'center', direction: 'ltr' }}>
+ <View style={{ width: 130 }}><TextInput value={date} onChange={setDate} placeholder="2026-10-18" /></View>
+ <View style={{ width: 80 }}><TextInput value={time} onChange={setTime} placeholder="14:30" /></View>
+ <Button small primary label={tr('prefs.time.set')} disabled={!valid}
+ onClick={() => admin.run('time-set', `${date} ${time}:00`).then(() => { setErr(''); onDone(); }, (e) => setErr(e.message))} />
+ </View>
+ {err ? <Note tone="warn">{err}</Note> : <Note>{tr('prefs.time.manualHint')}</Note>}
+ </View>
+ );
+}
+
+export function DateTimeSettings() {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const [s, set] = useSettings();
+ const td = useTimedate();
+ const c = clockPrefs(s);
+ const [zone, setZone] = useState(() => lord.time.zone());
+ const [picking, setPicking] = useState(false);
+ const [editing, setEditing] = useState(false);
+ const [err, setErr] = useState('');
+ const isAdmin = admin.available();
+ useEffect(() => { lord.timedate.refresh(); }, []);
+ const clock = useClock((d) => `${formatDate(d, 'long')} · ${formatTime(d, { seconds: true })}`, 1000);
+ const preview = useClock((d) => menuClock(d), 1000);
+ const patch = (x) => set({ clock: { ...c, ...x } });
+ const ntp = !!td?.ntp;
+ const setNtp = (on) => admin.run('time-ntp', on ? 'on' : 'off').then(() => { setErr(''); lord.timedate.refresh(); }, (e) => setErr(e.message));
+ const pickZone = (z) => {
+ setPicking(false);
+ admin.run('timezone', z).then(() => { lord.time.reload(); setZone(z); setErr(''); lord.timedate.refresh(); }, (e) => setErr(e.message));
+ };
+ const now = Math.floor(Date.now() / 1000);
+ const off = lord.time.zoneOffset ? lord.time.zoneOffset(zone, now) : null;
+ return (
+ <Stack>
+ <GroupBox footer={isAdmin ? '' : tr('prefs.time.needAdmin')}>
+ <SettingRow label={tr('prefs.time.auto')} hint={!td ? '' : !td.canNTP ? tr('prefs.time.noNtp') : ntp ? tr(td.synced ? 'prefs.time.synced' : 'prefs.time.syncing') : tr('prefs.time.manual')}
+ disabled={!isAdmin || (td && !td.canNTP)}>
+ <Toggle on={ntp} onChange={setNtp} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.time.dateTime')} hint={clock}>
+ <Button small label={tr('prefs.time.change')} disabled={ntp || !isAdmin} onClick={() => setEditing(!editing)} />
+ </SettingRow>
+ {editing && !ntp ? <ManualTime tr={tr} onDone={() => setEditing(false)} /> : null}
+ </GroupBox>
+ <GroupBox title={tr('prefs.time.zone')} footer={tr('prefs.time.zoneFooter')}>
+ <SettingRow label={zone.split('/').pop().replace(/_/g, ' ')} hint={`${zone.replace(/_/g, ' ')}${off ? ` · ${offsetText(off.offset)} (${off.abbr})` : ''}`}>
+ <Button small label={tr('prefs.time.change')} disabled={!isAdmin} onClick={() => setPicking(!picking)} />
+ </SettingRow>
+ {picking ? <ZonePicker zone={zone} onPick={pickZone} tr={tr} /> : null}
+ </GroupBox>
+ {err ? <Note tone="warn">{err}</Note> : null}
+ <GroupBox title={tr('prefs.time.format')}>
+ <SettingRow label={tr('prefs.time.hour24')} hint={tr('prefs.time.hour24Hint')}>
+ <PopUp value={c.hour24} onChange={(hour24) => patch({ hour24 })}
+ options={[['auto', tr('prefs.time.byRegion')], ['24', tr('prefs.time.h24')], ['12', tr('prefs.time.h12')]]} />
+ </SettingRow>
+ </GroupBox>
+ <GroupBox title={tr('prefs.time.menuClock')}>
+ <SettingRow label={tr('prefs.time.showDate')}>
+ <PopUp value={c.date} onChange={(date) => patch({ date })}
+ options={[['short', tr('prefs.time.dateFull')], ['weekday', tr('prefs.time.dateWeekday')], ['none', tr('prefs.time.dateNone')]]} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.time.seconds')}>
+ <Toggle on={c.seconds} onChange={(seconds) => patch({ seconds })} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.time.preview')}>
+ <View style={{ paddingHorizontal: 10, height: 24, borderRadius: 6, justifyContent: 'center', backgroundColor: t.mode === 'dark' ? 'rgba(0,0,0,0.3)' : 'rgba(0,0,0,0.06)' }}>
+ <Text style={{ fontSize: 13, fontWeight: 500, color: t.text }}>{preview}</Text>
+ </View>
+ </SettingRow>
+ </GroupBox>
+ </Stack>
+ );
+}
diff --git a/apps/settings/DefaultApps.jsx b/apps/settings/DefaultApps.jsx
new file mode 100644
index 0000000..746a6b6
--- /dev/null
+++ b/apps/settings/DefaultApps.jsx
@@ -0,0 +1,41 @@
+// Settings → Default Apps: browser, mail, music, video, images, PDF, text editor and terminal, from
+// LordOS's own apps and the installed Linux apps (.desktop with MimeType). Saved in
+// ~/.config/mimeapps.list (and ~/.config/xdg-terminals.list), so Files' "Open With", double
+// clicks, lord.apps.launchWith and Linux apps (xdg-open) agree. See docs/SETTINGS.md.
+import { View, Text, useTheme, useLocale, useLauncherApps, DEFAULT_CATEGORIES, defaultFor, setDefaultFor, candidatesFor } from '@lordos/sdk';
+import { useState } from 'react';
+import { GroupBox, SettingRow, PopUp, Note, Stack, Badge } from './ui.jsx';
+
+const LOOK = {
+ browser: ['🌐', '#0a84ff'], mail: ['✉', '#30a0ff'], music: ['♪', '#ff375f'], video: ['▶', '#bf5af2'], images: ['▣', '#ff9f0a'],
+ pdf: ['⎙', '#ff453a'], text: ['✎', '#8e8e93'], terminal: ['>_', '#2c2c2e'],
+};
+
+export function DefaultAppsSettings() {
+ const { t: tr } = useLocale();
+ const apps = useLauncherApps();
+ const [rev, setRev] = useState(0);
+ const [err, setErr] = useState('');
+ return (
+ <Stack>
+ <GroupBox footer={tr('prefs.defaults.footer')}>
+ {DEFAULT_CATEGORIES.map((c) => {
+ const list = candidatesFor(c.id, apps);
+ const cur = defaultFor(c.id);
+ const opts = list.map((a) => [a.id, a.native ? a.name : `${a.name}`]);
+ if (cur && !opts.some(([id]) => id === cur)) opts.push([cur, tr('prefs.defaults.other', { id: cur.replace(/\.desktop$/, '') })]);
+ const [glyph, color] = LOOK[c.id];
+ return (
+ <SettingRow key={`${c.id}${rev}`} icon={<Badge glyph={glyph} color={color} />} label={tr(`prefs.defaults.cat.${c.id}`)}
+ hint={list.length ? '' : tr('prefs.defaults.none')}>
+ {opts.length ? <PopUp width={230} value={cur || ''} options={cur ? opts : [['', tr('prefs.defaults.choose')], ...opts]}
+ onChange={(id) => { if (id && !setDefaultFor(c.id, id)) setErr(tr('prefs.defaults.failed')); else setErr(''); setRev((r) => r + 1); }} /> : null}
+ </SettingRow>
+ );
+ })}
+ </GroupBox>
+ {err ? <Note tone="warn">{err}</Note> : null}
+ <Note>{tr('prefs.defaults.filesHint')}</Note>
+ </Stack>
+ );
+}
diff --git a/apps/settings/Displays.jsx b/apps/settings/Displays.jsx
new file mode 100644
index 0000000..c8b2470
--- /dev/null
+++ b/apps/settings/Displays.jsx
@@ -0,0 +1,184 @@
+// Settings → Displays: resolution, refresh rate, rotation, the main display, brightness and Night
+// Shift (docs/SETTINGS.md, "Displays"). Changes apply live with the system's 15-second "Keep these
+// display settings?" countdown (sdk/hardware.jsx) and are saved per display (EDID identity).
+import {
+ View, Text, useTheme, useLocale, useSettings, Slider, Toggle, Segmented, Button, admin, useDisplays, applyDisplay, DisplayGlyph,
+ nightPrefs, nightActive, setNightManual, previewNight, nightTick, sunTimes, formatTime,
+} from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+import { GroupBox, SettingRow, PopUp, Note, Stack, TimeField } from './ui.jsx';
+
+const hz = (mhz) => {
+ const v = mhz / 1000;
+ return Math.abs(v - Math.round(v)) < 0.005 ? String(Math.round(v)) : v.toFixed(2);
+};
+
+// The display drawn in the arrangement area: proportional to its resolution, with its name.
+function Arrangement({ outs, current, onPick, t, tr }) {
+ const maxW = 150, maxH = 96;
+ return (
+ <View style={{ height: 150, borderRadius: 10, alignItems: 'center', justifyContent: 'center', flexDirection: 'row', gap: 18,
+ backgroundColor: t.mode === 'dark' ? 'rgba(0,0,0,0.22)' : 'rgba(0,0,0,0.05)', border: `1px solid ${t.separator}` }}>
+ {outs.map((o) => {
+ const w = o.mode?.w || o.preferred.w || 16, h = o.mode?.h || o.preferred.h || 10;
+ const k = Math.min(maxW / w, maxH / h);
+ const on = o.id === current?.id;
+ return (
+ <View key={o.id} onClick={() => !on && onPick(o)} style={{ alignItems: 'center', gap: 6 }}>
+ <View style={{ width: Math.round(w * k), height: Math.round(h * k), borderRadius: 6, alignItems: 'center', justifyContent: 'center',
+ background: on ? 'linear-gradient(135deg, #3b6fd8, #8f4fd1)' : 'linear-gradient(135deg, #5b5f6a, #3a3d45)',
+ border: on ? `2px solid ${t.accent}` : `1px solid ${t.separator}`, boxShadow: '0 4px 14px rgba(0,0,0,0.3)' }}>
+ {on ? <View style={{ position: 'absolute', left: 3, right: 3, top: 3, height: 4, borderRadius: 2, backgroundColor: 'rgba(255,255,255,0.75)' }} /> : null}
+ <Text style={{ fontSize: 11, fontWeight: 600, color: '#fff' }}>{o.mode ? `${o.mode.w}×${o.mode.h}` : tr('prefs.display.notInUse')}</Text>
+ </View>
+ <Text style={{ fontSize: 11, color: on ? t.text : t.textDim }}>{o.name}</Text>
+ </View>
+ );
+ })}
+ </View>
+ );
+}
+
+function Brightness({ list }) {
+ const { t: tr } = useLocale();
+ const [vals, setVals] = useState({});
+ const timer = useRef(0);
+ const [err, setErr] = useState('');
+ if (!list.length) return <SettingRow label={tr('prefs.display.brightness')} hint={tr('prefs.display.noBacklight')} disabled />;
+ return list.map((b) => {
+ const v = vals[b.name] ?? b.value;
+ const set = (x) => {
+ const n = Math.max(1, Math.round(x)); // 0 turns some panels fully off
+ setVals((o) => ({ ...o, [b.name]: n }));
+ clearTimeout(timer.current);
+ timer.current = setTimeout(() => admin.run('display-brightness', `${b.name} ${n}`, undefined, { quiet: true }).then(() => setErr(''), (e) => setErr(e.message)), 120);
+ };
+ return (
+ <SettingRow key={b.name} label={tr('prefs.display.brightness')} hint={err || (list.length > 1 ? b.name : '')}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, direction: 'ltr' }}>
+ <Text style={{ fontSize: 12, color: '#8e8e93' }}>☼</Text>
+ <Slider value={v} min={0} max={b.max} width={200} onChange={set} />
+ <Text style={{ fontSize: 15, color: '#8e8e93' }}>☀</Text>
+ </View>
+ </SettingRow>
+ );
+ });
+}
+
+function NightShift() {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const [s, set] = useSettings();
+ const p = nightPrefs(s);
+ const [preview, setPreview] = useState(null);
+ const tm = useRef(0);
+ const patch = (x) => set({ night: { ...p, ...x } });
+ const sun = p.schedule === 'sun' ? sunTimes() : null;
+ const active = nightActive();
+ useEffect(() => { nightTick(); }, [s.night]);
+ const fmt = (m) => { const d = new Date(); d.setHours(Math.floor(m / 60), m % 60, 0, 0); return formatTime(d); };
+ const scheduleHint = p.schedule === 'sun'
+ ? (sun ? tr('prefs.night.sunHint', { set: fmt(sun.sunset), rise: fmt(sun.sunrise) }) : tr('prefs.night.noSun'))
+ : p.schedule === 'custom' ? tr('prefs.night.customHint') : tr('prefs.night.offHint');
+ return (
+ <GroupBox title={tr('prefs.night.title')} footer={tr('prefs.night.footer')}>
+ <SettingRow label={tr('prefs.night.schedule')} hint={scheduleHint}>
+ <PopUp value={p.schedule} onChange={(schedule) => patch({ schedule, manual: null })}
+ options={[['off', tr('prefs.night.off')], ['sun', tr('prefs.night.sun')], ['custom', tr('prefs.night.custom')]]} />
+ </SettingRow>
+ {p.schedule === 'custom' && (
+ <SettingRow label={tr('prefs.night.from')}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <TimeField value={p.from} onChange={(from) => patch({ from })} format={fmt} />
+ <Text style={{ fontSize: 12, color: t.textDim }}>{tr('prefs.night.to')}</Text>
+ <TimeField value={p.to} onChange={(to) => patch({ to })} format={fmt} />
+ </View>
+ </SettingRow>
+ )}
+ <SettingRow label={tr('prefs.night.now')}
+ hint={p.manual && Date.now() < p.manual.until ? tr(p.manual.on ? 'prefs.night.manualOn' : 'prefs.night.manualOff', { time: formatTime(new Date(p.manual.until)) }) : ''}>
+ <Toggle on={active} onChange={(on) => setNightManual(on)} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.night.temp')}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, direction: 'ltr' }}>
+ <Text style={{ fontSize: 11, color: t.textDim }}>{tr('prefs.night.lessWarm')}</Text>
+ {/* the slider goes from less warm (left) to more warm (right) */}
+ <Slider value={6500 - (preview ?? p.temp)} min={6500 - 6000} max={6500 - 1900} width={170}
+ onChange={(v) => { const k = Math.round(6500 - v); setPreview(k); previewNight(k); clearTimeout(tm.current);
+ tm.current = setTimeout(() => { setPreview(null); patch({ temp: k }); }, 400); }} />
+ <Text style={{ fontSize: 11, color: t.textDim }}>{tr('prefs.night.moreWarm')}</Text>
+ </View>
+ </SettingRow>
+ </GroupBox>
+ );
+}
+
+export function DisplaysSettings() {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const d = useDisplays();
+ const [msg, setMsg] = useState('');
+ if (!d) return <Note>{tr('prefs.display.unavailable')}</Note>;
+ const outs = d.outputs || [];
+ const cur = outs.find((o) => o.current) || outs[0];
+ if (!d.onMonitor || !cur) {
+ return (
+ <Stack>
+ <Note>{tr('prefs.display.notOnMonitor')}</Note>
+ <NightShift />
+ </Stack>
+ );
+ }
+ const mode = cur.mode || { w: cur.preferred.w, h: cur.preferred.h, refresh: 0 };
+ const res = cur.resolutions || [];
+ const curRes = res.find((r) => r.w === mode.w && r.h === mode.h) || res[0];
+ const go = (o, x) => { if (!applyDisplay(o, x)) setMsg(tr('prefs.display.failed')); else setMsg(''); };
+ const native = (r) => r.w === cur.preferred.w && r.h === cur.preferred.h;
+ const sizeLine = [cur.connector, cur.diagonal ? tr('prefs.display.inches', { n: (cur.diagonal / 10).toFixed(1) }) : '', `${mode.w} × ${mode.h}`].filter(Boolean).join(' · ');
+ return (
+ <Stack>
+ <Arrangement outs={outs} current={cur} t={t} tr={tr} onPick={(o) => go(o, { conn: o.id, w: 0, h: 0, refresh: 0, rotation: 0 })} />
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 12, marginTop: -6 }}>
+ <DisplayGlyph size={34} color={t.accent} />
+ <View style={{ flex: 1 }}>
+ <Text style={{ fontSize: 14, fontWeight: 700, color: t.text, textAlign: 'start' }}>{cur.name}</Text>
+ <Text style={{ fontSize: 11, color: t.textDim, textAlign: 'start' }}>{sizeLine}</Text>
+ </View>
+ </View>
+ <GroupBox>
+ <SettingRow label={tr('prefs.display.resolution')}>
+ <PopUp width={230} value={`${curRes?.w}x${curRes?.h}`} onChange={(v) => { const [w, h] = v.split('x').map(Number); go(cur, { w, h, refresh: 0, rotation: d.rotation }); }}
+ options={res.map((r) => [`${r.w}x${r.h}`, native(r) ? tr('prefs.display.native', { w: r.w, h: r.h }) : `${r.w} × ${r.h}`])} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.display.refresh')}>
+ <PopUp value={mode.refresh} onChange={(refresh) => go(cur, { w: mode.w, h: mode.h, refresh, rotation: d.rotation })}
+ options={(curRes?.rates || []).map((r) => [r, tr('prefs.display.hz', { hz: hz(r) })])} disabled={(curRes?.rates || []).length < 2} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.display.rotation')} hint={d.rotation ? tr('prefs.display.rotationHint') : ''}>
+ <PopUp value={d.rotation} onChange={(rotation) => go(cur, { w: mode.w, h: mode.h, refresh: mode.refresh, rotation })}
+ options={[[0, tr('prefs.display.rotStandard')], [1, '90°'], [2, '180°'], [3, '270°']]} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.display.scale')} hint={tr('prefs.display.scaleHint')} disabled>
+ <Segmented small value="100" onChange={() => {}} options={[['100', '100 %'], ['125', '125 %'], ['150', '150 %'], ['200', '200 %']]} />
+ </SettingRow>
+ </GroupBox>
+ {msg ? <Note tone="warn">{msg}</Note> : null}
+ <GroupBox>
+ <Brightness list={d.backlight || []} />
+ </GroupBox>
+ <NightShift />
+ {d.softTint ? <Note>{tr('prefs.night.software')}</Note> : null}
+ <GroupBox title={tr('prefs.display.multiple')} footer={tr('prefs.display.multipleHint')}>
+ <SettingRow label={tr('prefs.display.useAs')} disabled>
+ <Segmented small value="extend" onChange={() => {}} options={[['extend', tr('prefs.display.extend')], ['mirror', tr('prefs.display.mirror')]]} />
+ </SettingRow>
+ {outs.filter((o) => o.id !== cur.id).map((o) => (
+ <SettingRow key={o.id} label={o.name} hint={o.connector}>
+ <Button small label={tr('prefs.display.makeMain')} onClick={() => go(o, { conn: o.id, w: 0, h: 0, refresh: 0, rotation: 0 })} />
+ </SettingRow>
+ ))}
+ {outs.length < 2 ? <SettingRow label={tr('prefs.display.onlyOne')} /> : null}
+ </GroupBox>
+ </Stack>
+ );
+}
diff --git a/apps/settings/Network.jsx b/apps/settings/Network.jsx
index 9a32544..3ccf284 100644
--- a/apps/settings/Network.jsx
+++ b/apps/settings/Network.jsx
@@ -2,7 +2,7 @@
// (lord.net, netlink) y cambia por el ayudante de administración (acciones net-*). Ver docs/RED.md.
import {
View, Text, useTheme, useLocale, Button, Toggle, Segmented, TextInput, SectionTitle,
- admin, fs, formatBytes,
+ admin, fs, formatBytes, keyring, AutofillButton,
} from '@lordos/sdk';
import { useEffect, useState } from 'react';
@@ -177,6 +177,8 @@ function WifiPage({ net }) {
const connect = (n, password) => {
setPick(null);
setPass('');
+ // the password also goes to the session keyring (Passwords → Session keyring; docs/PASSWORDS.md)
+ if (password && n.ssid) keyring.set('settings', { service: `wifi:${n.ssid}`, secret: password, label: `Wi-Fi ${n.ssid}` }).catch(() => {});
run(setMsg, 'net-wifi-connect', `${dev}\n${n.ssid}\n${password || ''}`, tr('network.wifi.connecting', { ssid: n.ssid }));
};
return (
@@ -204,6 +206,7 @@ function WifiPage({ net }) {
<View style={{ flexDirection: 'row', gap: 8, paddingBottom: 10, paddingHorizontal: 4 }}>
<TextInput secure autoFocus value={pass} onChange={setPass} placeholder={tr('network.wifi.password')} onSubmit={() => connect(n, pass)}
onCancel={() => setPick(null)} style={{ flex: 1 }} />
+ <AutofillButton app="settings" service={`wifi:${n.ssid}`} ssid={n.ssid} onFill={({ password }) => setPass(password || '')} />
<Button primary label={tr('network.wifi.join')} onClick={() => connect(n, pass)} />
</View>
)}
@@ -379,11 +382,15 @@ function VpnPage({ net }) {
<View style={{ padding: 12, borderRadius: 10, backgroundColor: t.hover, gap: 8, marginBottom: 10 }}>
<Text style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{tr('network.vpn.authTitle', { name: auth.name })}</Text>
<TextInput value={auth.user} onChange={(user) => setAuth({ ...auth, user })} placeholder={tr('network.vpn.user')} />
- <TextInput secure value={auth.pass} onChange={(pass) => setAuth({ ...auth, pass })} placeholder={tr('network.vpn.password')} />
+ <View style={{ flexDirection: 'row', gap: 8, alignItems: 'center' }}>
+ <TextInput secure value={auth.pass} onChange={(pass) => setAuth({ ...auth, pass })} placeholder={tr('network.vpn.password')} style={{ flex: 1 }} />
+ <AutofillButton app="settings" service={`vpn:${auth.name}`} onFill={({ username, password }) => setAuth({ ...auth, user: username || auth.user, pass: password || '' })} />
+ </View>
<View style={{ flexDirection: 'row', gap: 8 }}>
<Button primary label={tr('network.vpn.saveConnect')} onClick={() => {
const a = auth;
setAuth(null);
+ if (a.pass) keyring.set('settings', { service: `vpn:${a.name}`, account: a.user, secret: a.pass, label: `VPN ${a.name}` }).catch(() => {});
run(setMsg, 'net-vpn-credentials', `${a.name}\n${a.user}\n${a.pass}`).then((r) => r != null && up({ name: a.name }));
}} />
<Button label={tr('network.cancel')} onClick={() => setAuth(null)} />
diff --git a/apps/settings/Notifications.jsx b/apps/settings/Notifications.jsx
new file mode 100644
index 0000000..f5b213e
--- /dev/null
+++ b/apps/settings/Notifications.jsx
@@ -0,0 +1,113 @@
+// Settings → Notifications: Do Not Disturb (now, or every day on a schedule), grouping, and per app:
+// allow, style (none / banners / alerts), sound and lock screen. Packages (.lpk) use the sandbox's
+// "notifications" permission for "allow", the same switch as Privacy & Security. Linux apps notify
+// through org.freedesktop.Notifications (server/src/hw/notifyd.c). See docs/SETTINGS.md.
+import {
+ View, Text, useTheme, useLocale, useSettings, Toggle, Segmented, Button, useStore, permsRev, packages, getApp, appName, useLauncherApps,
+ notifyPrefs, appNotifyPrefs, setAppNotifyPrefs, dndActive, notify,
+} from '@lordos/sdk';
+import { useState } from 'react';
+import { GroupBox, SettingRow, PopUp, Note, Stack, TimeField } from './ui.jsx';
+
+// Apps that can notify: the ones that already did, LordOS apps that use notifications and packages
+// that declare the permission.
+const BUILTIN = ['settings', 'backup', 'clock', 'terminal', 'store', 'mail', 'passwords', 'recorder', 'screenshots'];
+
+function AppIcon({ app, linux }) {
+ const t = useTheme();
+ if (app?.Icon) return <app.Icon size={28} />;
+ if (linux?.Icon) return <linux.Icon size={28} />;
+ return <View style={{ width: 28, height: 28, borderRadius: 7, backgroundColor: t.control }} />;
+}
+
+function AppRow({ id, name, app, linux, tr }) {
+ const t = useTheme();
+ const [s] = useSettings();
+ useStore(permsRev);
+ const [open, setOpen] = useState(false);
+ const p = appNotifyPrefs(id, s);
+ const summary = !p.allow ? tr('prefs.notif.off')
+ : [tr(`prefs.notif.style.${p.style}`), p.sound ? tr('prefs.notif.sound') : null].filter(Boolean).join(', ');
+ const set = (x) => setAppNotifyPrefs(id, x);
+ return (
+ <View>
+ <SettingRow icon={<AppIcon app={app} linux={linux} />} label={name} hint={summary} onClick={() => setOpen(!open)}>
+ <Text style={{ fontSize: 12, color: t.textDim }}>{open ? '⌃' : '⌄'}</Text>
+ </SettingRow>
+ {open && (
+ <View style={{ paddingBottom: 10, marginInlineStart: 40, gap: 2 }}>
+ <SettingRow label={tr('prefs.notif.allow')} hint={app?.package ? tr('prefs.notif.allowPackage') : ''}>
+ <Toggle on={p.allow} onChange={(allow) => set({ allow })} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.notif.styleLabel')} hint={tr(`prefs.notif.styleHint.${p.style}`)} disabled={!p.allow}>
+ <Segmented small value={p.style} onChange={(style) => p.allow && set({ style })}
+ options={['none', 'banner', 'alert'].map((x) => [x, tr(`prefs.notif.style.${x}`)])} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.notif.playSound')} disabled={!p.allow}>
+ <Toggle on={p.sound} onChange={(sound) => p.allow && set({ sound })} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.notif.lockScreen')} hint={tr('prefs.notif.lockScreenHint')} disabled>
+ <Toggle on={p.lock} onChange={() => {}} />
+ </SettingRow>
+ </View>
+ )}
+ </View>
+ );
+}
+
+export function NotificationsSettings() {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const [s, set] = useSettings();
+ const linux = useLauncherApps().filter((a) => a.kind === 'linux');
+ const p = notifyPrefs(s);
+ const patch = (x) => set({ notifications: { ...p, ...x } });
+ const now = dndActive();
+ // the list: seen + built-in + packages with the permission
+ const ids = [...new Set([...p.seen, ...BUILTIN.filter((id) => getApp(id)), ...packages.list().filter((x) => (x.permissions || []).includes('notifications')).map((x) => x.id)])];
+ const rows = ids.map((id) => {
+ if (id.startsWith('linux:')) {
+ const did = id.slice(6);
+ const la = linux.find((a) => a.desktopId === did || a.desktopId.toLowerCase() === did.toLowerCase());
+ return { id, name: la?.name || did, linux: la };
+ }
+ const app = getApp(id);
+ return app ? { id, name: appName(app), app } : null;
+ }).filter(Boolean).sort((a, b) => a.name.localeCompare(b.name));
+ const fmt = (m) => { const d = new Date(); d.setHours(Math.floor(m / 60), m % 60, 0, 0); return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; };
+ return (
+ <Stack>
+ <GroupBox title={tr('prefs.notif.focus')} footer={tr('prefs.notif.dndFooter')}>
+ <SettingRow icon={<View style={{ width: 28, height: 28, borderRadius: 7, backgroundColor: '#5e5ce6', alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 15, color: '#fff' }}>☾</Text></View>}
+ label={tr('prefs.notif.dnd')} hint={now ? tr('prefs.notif.dndOnHint') : tr('prefs.notif.dndOffHint')}>
+ <Toggle on={p.dnd === true} onChange={(on) => patch({ dnd: on })} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.notif.schedule')} hint={p.schedule.on ? tr('prefs.notif.scheduleHint', { from: fmt(p.schedule.from), to: fmt(p.schedule.to) }) : ''}>
+ <Toggle on={p.schedule.on} onChange={(on) => patch({ schedule: { ...p.schedule, on } })} />
+ </SettingRow>
+ {p.schedule.on && (
+ <SettingRow label={tr('prefs.notif.from')}>
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
+ <TimeField value={p.schedule.from} onChange={(from) => patch({ schedule: { ...p.schedule, from } })} />
+ <Text style={{ fontSize: 12, color: t.textDim }}>{tr('prefs.notif.to')}</Text>
+ <TimeField value={p.schedule.to} onChange={(to) => patch({ schedule: { ...p.schedule, to } })} />
+ </View>
+ </SettingRow>
+ )}
+ </GroupBox>
+ <GroupBox>
+ <SettingRow label={tr('prefs.notif.grouping')} hint={tr('prefs.notif.groupingHint')}>
+ <PopUp value={p.grouping} onChange={(grouping) => patch({ grouping })} options={[['app', tr('prefs.notif.byApp')], ['off', tr('prefs.notif.noGrouping')]]} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.notif.test')}>
+ <Button small label={tr('prefs.notif.testButton')} onClick={() => notify({ app: 'settings', title: tr('prefs.notif.testTitle'), body: tr('prefs.notif.testBody') })} />
+ </SettingRow>
+ </GroupBox>
+ <GroupBox title={tr('prefs.notif.apps')} footer={tr('prefs.notif.appsFooter')}>
+ {rows.map((r) => <AppRow key={r.id} {...r} tr={tr} />)}
+ </GroupBox>
+ </Stack>
+ );
+}
+
diff --git a/apps/settings/Power.jsx b/apps/settings/Power.jsx
new file mode 100644
index 0000000..d3b0f0a
--- /dev/null
+++ b/apps/settings/Power.jsx
@@ -0,0 +1,128 @@
+// Settings → Energy (Battery on laptops): battery state and health, power mode, screen off / lock /
+// sleep after N minutes, what the power button and the lid do (logind, closed admin action
+// power-buttons), the low-battery notice and the percentage in the menu bar. See docs/SETTINGS.md.
+import {
+ View, Text, useTheme, useLocale, useSettings, Toggle, Segmented, admin, useBattery, usePowerProfiles, onPowerProfileResult,
+ BatteryGlyph, powerPrefs,
+} from '@lordos/sdk';
+import { useEffect, useState } from 'react';
+import { GroupBox, SettingRow, PageHeader, PopUp, Note, Stack } from './ui.jsx';
+
+const mins = (m) => m * 60;
+const duration = (tr, m) => (m >= 60 ? tr('prefs.power.hm', { h: Math.floor(m / 60), m: m % 60 }) : tr('prefs.power.m', { m }));
+
+function BatteryCard({ b, tr }) {
+ const t = useTheme();
+ const main = b.supplies.find((s) => s.battery && !s.device) || {};
+ const status = b.charging ? (b.minutesLeft > 0 ? tr('prefs.power.chargingLeft', { time: duration(tr, b.minutesLeft) }) : tr('prefs.power.charging'))
+ : b.onAC ? tr('prefs.power.onACFull') : b.minutesLeft > 0 ? tr('prefs.power.left', { time: duration(tr, b.minutesLeft) }) : tr('prefs.power.onBattery');
+ const health = main.health >= 0 ? tr(main.health >= 80 ? 'prefs.power.healthNormal' : 'prefs.power.healthService', { pct: main.health }) : tr('prefs.power.healthUnknown');
+ return (
+ <PageHeader icon={<View style={{ width: 60, alignItems: 'center' }}><BatteryGlyph percent={b.percent} charging={b.charging} color={t.text} width={52} /></View>}
+ title={b.percent >= 0 ? `${b.percent} %` : tr('prefs.power.battery')} subtitle={`${status}\n${health}${main.cycles > 0 ? ` · ${tr('prefs.power.cycles', { n: main.cycles })}` : ''}`} />
+ );
+}
+
+function ProfileRow({ tr }) {
+ const p = usePowerProfiles();
+ const [err, setErr] = useState('');
+ const [pending, setPending] = useState(null);
+ useEffect(() => onPowerProfileResult((r) => {
+ if (r.ok || !pending) { setErr(''); return; }
+ // the daemon refused (polkit: the session is not "active" for logind): the closed admin action
+ admin.run('power-profile', pending).then(() => setErr(''), (e) => setErr(e.message));
+ }), [pending]);
+ const list = p?.profiles || [];
+ if (!list.length) return <SettingRow label={tr('prefs.power.mode')} hint={tr('prefs.power.noProfiles')} disabled />;
+ const set = (v) => {
+ setPending(v);
+ if (!(p.daemon && lord.power.setProfile(v))) admin.run('power-profile', v).then(() => setErr(''), (e) => setErr(e.message));
+ };
+ return (
+ <SettingRow label={tr('prefs.power.mode')} hint={err || (p.degraded ? tr('prefs.power.degraded') : tr(p.daemon ? 'prefs.power.modeHint' : 'prefs.power.modeGovernor', { gov: p.governor }))}>
+ <Segmented small value={p.active} onChange={set} options={['power-saver', 'balanced', 'performance'].filter((x) => list.includes(x)).map((x) => [x, tr(`prefs.power.profile.${x}`)])} />
+ </SettingRow>
+ );
+}
+
+function Buttons({ hasLid, tr }) {
+ const [b, setB] = useState(() => lord.power.buttons());
+ const [err, setErr] = useState('');
+ const isAdmin = admin.available();
+ const acts = () => ['suspend', 'hibernate', 'poweroff', 'ignore'].map((a) => [a, tr(`prefs.power.act.${a}`)]);
+ const save = (x) => {
+ const n = { ...b, ...x };
+ admin.run('power-buttons', `${n.power} ${n.lid} ${n.lidAC}`).then(() => { setB(lord.power.buttons()); setErr(''); }, (e) => setErr(e.message));
+ setB(n);
+ };
+ return (
+ <GroupBox title={tr('prefs.power.buttons')} footer={err || (isAdmin ? tr('prefs.power.buttonsHint') : tr('prefs.power.needAdmin'))}>
+ <SettingRow label={tr('prefs.power.powerKey')} disabled={!isAdmin}>
+ <PopUp value={b.power} options={acts(false)} onChange={(power) => save({ power })} disabled={!isAdmin} />
+ </SettingRow>
+ {hasLid && (
+ <SettingRow label={tr('prefs.power.lid')} disabled={!isAdmin}>
+ <PopUp value={b.lid} options={acts(true)} onChange={(lid) => save({ lid })} disabled={!isAdmin} />
+ </SettingRow>
+ )}
+ {hasLid && (
+ <SettingRow label={tr('prefs.power.lidAC')} disabled={!isAdmin}>
+ <PopUp value={b.lidAC} options={acts(true)} onChange={(lidAC) => save({ lidAC })} disabled={!isAdmin} />
+ </SettingRow>
+ )}
+ </GroupBox>
+ );
+}
+
+export function PowerSettings() {
+ const { t: tr } = useLocale();
+ const [s, set] = useSettings();
+ const b = useBattery();
+ const p = powerPrefs(s);
+ const patch = (x) => set({ power: { ...p, ...x } });
+ const hasBattery = !!b?.hasBattery;
+ const offOpts = [[0, tr('prefs.power.never')], [mins(1), duration(tr, 1)], [mins(2), duration(tr, 2)], [mins(3), duration(tr, 3)], [mins(5), duration(tr, 5)],
+ [mins(10), duration(tr, 10)], [mins(15), duration(tr, 15)], [mins(30), duration(tr, 30)], [mins(60), duration(tr, 60)]];
+ const sleepOpts = [[0, tr('prefs.power.never')], [mins(15), duration(tr, 15)], [mins(30), duration(tr, 30)], [mins(60), duration(tr, 60)], [mins(120), duration(tr, 120)], [mins(180), duration(tr, 180)]];
+ const lockOpts = [[0, tr('prefs.power.immediately')], [5, tr('prefs.power.secs', { s: 5 })], [60, duration(tr, 1)], [300, duration(tr, 5)], [900, duration(tr, 15)], [3600, duration(tr, 60)], [-1, tr('prefs.power.never')]];
+ return (
+ <Stack>
+ {hasBattery ? <BatteryCard b={b} tr={tr} /> : <Note>{tr('prefs.power.noBattery')}</Note>}
+ <GroupBox>
+ <ProfileRow tr={tr} />
+ </GroupBox>
+ <GroupBox title={tr('prefs.power.screenSleep')} footer={tr('prefs.power.screenSleepHint')}>
+ <SettingRow label={hasBattery ? tr('prefs.power.offAC') : tr('prefs.power.off')}>
+ <PopUp value={p.offAC} options={offOpts} onChange={(offAC) => patch({ offAC })} />
+ </SettingRow>
+ {hasBattery && (
+ <SettingRow label={tr('prefs.power.offBattery')}>
+ <PopUp value={p.offBattery} options={offOpts} onChange={(offBattery) => patch({ offBattery })} />
+ </SettingRow>
+ )}
+ <SettingRow label={tr('prefs.power.lock')}>
+ <PopUp value={p.lockDelay} options={lockOpts} onChange={(lockDelay) => patch({ lockDelay })} />
+ </SettingRow>
+ <SettingRow label={hasBattery ? tr('prefs.power.sleepAC') : tr('prefs.power.sleep')}>
+ <PopUp value={p.sleepAC} options={sleepOpts} onChange={(sleepAC) => patch({ sleepAC })} />
+ </SettingRow>
+ {hasBattery && (
+ <SettingRow label={tr('prefs.power.sleepBattery')}>
+ <PopUp value={p.sleepBattery} options={sleepOpts} onChange={(sleepBattery) => patch({ sleepBattery })} />
+ </SettingRow>
+ )}
+ </GroupBox>
+ <Buttons hasLid={hasBattery} tr={tr} />
+ {hasBattery && (
+ <GroupBox title={tr('prefs.power.battery')}>
+ <SettingRow label={tr('prefs.power.lowBattery')} hint={tr('prefs.power.lowBatteryHint')}>
+ <Toggle on={p.lowBattery} onChange={(lowBattery) => patch({ lowBattery })} />
+ </SettingRow>
+ <SettingRow label={tr('prefs.power.menuPercent')}>
+ <Toggle on={p.menuPercent} onChange={(menuPercent) => patch({ menuPercent })} />
+ </SettingRow>
+ </GroupBox>
+ )}
+ </Stack>
+ );
+}
diff --git a/apps/settings/index.jsx b/apps/settings/index.jsx
index 10d41a1..adcca5c 100644
--- a/apps/settings/index.jsx
+++ b/apps/settings/index.jsx
@@ -14,6 +14,13 @@ import { PrivacySettings } from './Privacy.jsx';
import { PrintersSettings } from './Printers.jsx';
import { TrackpadSettings } from './Trackpad.jsx';
import { DockSettings } from './Dock.jsx';
+// hardware pages (docs/SETTINGS.md)
+import { DisplaysSettings } from './Displays.jsx';
+import { BluetoothSettings } from './Bluetooth.jsx';
+import { PowerSettings } from './Power.jsx';
+import { NotificationsSettings } from './Notifications.jsx';
+import { DateTimeSettings } from './DateTime.jsx';
+import { DefaultAppsSettings } from './DefaultApps.jsx';
export function Icon({ size: s }) {
const dark = '#3b3e46';
@@ -339,10 +346,10 @@ function Session() {
// Grupos de la barra lateral (como en macOS / TangoOS): [id, componente, color del ícono, símbolo].
const GROUPS = [
- [['general', General, '#8e8e93', 'i'], ['appearance', Appearance, '#bf5af2', '◐'], ['wallpaper', Wallpapers, '#0a84ff', '▣'], ['dock', DockSettings, '#1c1c1e', '▁']],
- [['network', NetworkSettings, '#0a84ff', '⇅'], ['sound', SoundSettings, '#ff375f', '♪'], ['printers', PrintersSettings, '#636366', '⎙'], ['clipboard', ClipboardSettings, '#5e5ce6', '⎘'], ['sharing', SharingSettings, '#34c759', '⇄']],
- [['language', LanguageRegion, '#30b0c7', 'A'], ['keyboard', Keyboard, '#636366', '⌨'], ['trackpad', TrackpadSettings, '#8e8e93', '▭']],
- [['privacy', PrivacySettings, '#0a84ff', '🔒'], ['users', UsersSettings, '#0a84ff', '☺'], ['updates', Updates, '#64d2ff', '↻'], ['themes', Themes, '#ff9f0a', '◧'], ['session', Session, '#ff453a', '↪']],
+ [['general', General, '#8e8e93', 'i'], ['appearance', Appearance, '#bf5af2', '◐'], ['wallpaper', Wallpapers, '#0a84ff', '▣'], ['dock', DockSettings, '#1c1c1e', '▁'], ['displays', DisplaysSettings, '#0a84ff', '▭']],
+ [['network', NetworkSettings, '#0a84ff', '⇅'], ['bluetooth', BluetoothSettings, '#0a84ff', 'ᛒ'], ['sound', SoundSettings, '#ff375f', '♪'], ['notifications', NotificationsSettings, '#ff3b30', '◉'], ['printers', PrintersSettings, '#636366', '⎙'], ['clipboard', ClipboardSettings, '#5e5ce6', '⎘'], ['sharing', SharingSettings, '#34c759', '⇄']],
+ [['language', LanguageRegion, '#30b0c7', 'A'], ['datetime', DateTimeSettings, '#0a84ff', '◷'], ['keyboard', Keyboard, '#636366', '⌨'], ['trackpad', TrackpadSettings, '#8e8e93', '▭'], ['defaultapps', DefaultAppsSettings, '#8e8e93', '◫']],
+ [['power', PowerSettings, '#30d158', '⚡'], ['privacy', PrivacySettings, '#0a84ff', '🔒'], ['users', UsersSettings, '#0a84ff', '☺'], ['updates', Updates, '#64d2ff', '↻'], ['themes', Themes, '#ff9f0a', '◧'], ['session', Session, '#ff453a', '↪']],
];
const SECTIONS = GROUPS.flat();
diff --git a/apps/settings/ui.jsx b/apps/settings/ui.jsx
new file mode 100644
index 0000000..81fa443
--- /dev/null
+++ b/apps/settings/ui.jsx
@@ -0,0 +1,162 @@
+// ui.jsx — building blocks shared by the hardware pages of Settings (Displays, Bluetooth, Battery,
+// Notifications, Date & Time, Default Apps), on top of the SDK's GroupBox (docs/DESIGN.md): a row
+// with a hint, a pop-up button (macOS NSPopUpButton), a page header and a note.
+import { View, Text, useTheme, addListener, GroupBox, spacing, typeScale, createStore, useStore, screen, ScrollView } from '@lordos/sdk';
+import { useEffect, useRef, useState } from 'react';
+
+export { GroupBox };
+
+// A row of a GroupBox: label (and an optional hint below it) at the start, the control at the end.
+export function SettingRow({ label, hint, children, icon, disabled, onClick, minHeight = 40 }) {
+ const t = useTheme();
+ return (
+ <View onClick={disabled ? undefined : onClick} style={{ minHeight, flexDirection: 'row', alignItems: 'center', gap: spacing.m, paddingVertical: 7,
+ opacity: disabled ? 0.45 : 1 }}>
+ {icon || null}
+ <View style={{ flex: 1, gap: 2 }}>
+ <Text style={{ fontSize: typeScale.body, color: t.text, textAlign: 'start' }}>{label}</Text>
+ {hint ? <Text style={{ fontSize: typeScale.caption, color: t.textDim, lineHeight: 1.35, textAlign: 'start' }}>{hint}</Text> : null}
+ </View>
+ {children}
+ </View>
+ );
+}
+
+// Page header: a big icon, the title and one line of explanation (like the top of a macOS pane).
+export function PageHeader({ icon, title, subtitle, children }) {
+ const t = useTheme();
+ return (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.l, padding: spacing.l, borderRadius: 10,
+ backgroundColor: t.mode === 'dark' ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.025)', border: `1px solid ${t.separator}` }}>
+ {icon}
+ <View style={{ flex: 1, gap: 3 }}>
+ <Text style={{ fontSize: typeScale.headline, fontWeight: 700, color: t.text, textAlign: 'start' }}>{title}</Text>
+ {subtitle ? <Text style={{ fontSize: typeScale.callout, color: t.textDim, lineHeight: 1.4, textAlign: 'start' }}>{subtitle}</Text> : null}
+ </View>
+ {children}
+ </View>
+ );
+}
+
+// A rounded square with a glyph, as in the sidebar (also used in rows).
+export function Badge({ glyph, color, size = 26 }) {
+ return (
+ <View style={{ width: size, height: size, borderRadius: size * 0.24, backgroundColor: color, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: size * 0.55, fontWeight: 700, color: '#fff', lineHeight: size }}>{glyph}</Text>
+ </View>
+ );
+}
+
+// Informational text under a group, or a warning (tone 'warn').
+export function Note({ children, tone }) {
+ const t = useTheme();
+ return <Text style={{ fontSize: typeScale.caption, color: tone === 'warn' ? '#ff9f0a' : t.textDim, lineHeight: 1.4, marginHorizontal: spacing.s, textAlign: 'start' }}>{children}</Text>;
+}
+
+// The page: a column of groups. It also hosts the open pop-up menu (PopUpLayer), drawn last so it
+// covers the rows below its button (zIndex only orders siblings).
+export function Stack({ children, gap = 20 }) {
+ return (
+ <View style={{ gap, paddingBottom: 24 }}>
+ {children}
+ <PopUpLayer />
+ </View>
+ );
+}
+
+const popup = createStore(null); // { node, options, value, onChange, width }
+
+// Pop-up button: shows the current value with ▲▼ and opens the list of options below it (or above,
+// near the bottom of the screen). options = [[value, label]]; a value of '-' is a separator.
+export function PopUp({ value, options, onChange, width = 190, disabled }) {
+ const t = useTheme();
+ const [hover, setHover] = useState(false);
+ const btn = useRef(null);
+ const open = useStore(popup, (p) => !!p && p.node === btn.current);
+ useEffect(() => () => { if (popup.get()?.node === btn.current) popup.set(null); }, []);
+ const cur = options.find(([v]) => v === value);
+ const toggle = () => { if (disabled) return; popup.set(open ? null : { node: btn.current, options, value, onChange, width }); };
+ return (
+ <View ref={btn} onClick={toggle} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ width, height: 24, paddingHorizontal: 9, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 6,
+ backgroundColor: t.control, opacity: disabled ? 0.45 : hover || open ? 0.88 : 1, boxShadow: '0 1px 1px rgba(0,0,0,0.12)' }}>
+ <Text style={{ flex: 1, fontSize: 12, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' }}>{cur ? cur[1] : ''}</Text>
+ <View style={{ width: 16, height: 18, borderRadius: 4, backgroundColor: t.accent, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 8, color: '#fff', lineHeight: 8 }}>▲</Text>
+ <Text style={{ fontSize: 8, color: '#fff', lineHeight: 8 }}>▼</Text>
+ </View>
+ </View>
+ );
+}
+
+function PopUpLayer() {
+ const t = useTheme();
+ const p = useStore(popup);
+ const origin = useRef(null), menu = useRef(null);
+ const [, relayout] = useState(0);
+ useEffect(() => {
+ if (!p) return undefined;
+ relayout((x) => x + 1); // the origin is known after the first layout
+ return addListener('pointerdown', (e) => {
+ const inside = (n) => { if (!n) return false; const [x, y, w, h] = lord.getLayout(n.id); return e.x >= x && e.x <= x + w && e.y >= y && e.y <= y + h; };
+ if (!inside(menu.current) && !inside(p.node)) popup.set(null);
+ });
+ }, [p]);
+ const anchor = <View ref={origin} style={{ position: 'absolute', left: 0, top: 0, width: 0, height: 0 }} />;
+ if (!p || !p.node || !origin.current) return anchor;
+ const [ox, oy] = lord.getLayout(origin.current.id);
+ const [bx, by, bw, bh] = lord.getLayout(p.node.id);
+ const rows = p.options.length;
+ const mh = rows * 24 + 12;
+ const below = by + bh + 4 + Math.min(mh, 320) < screen.height - 70;
+ const height = Math.min(mh, 320);
+ const top = below ? by + bh + 4 - oy : by - 4 - height - oy;
+ return (
+ <>
+ {anchor}
+ <View ref={menu} style={{ position: 'absolute', left: bx - ox, top, width: Math.max(bw, p.width), height, padding: 5, borderRadius: 8, overflow: 'hidden',
+ backgroundColor: t.mode === 'dark' ? '#2c2c31' : '#ffffff', border: `1px solid ${t.separator}`, boxShadow: '0 10px 30px rgba(0,0,0,0.35)' }}>
+ <ScrollView style={{ flex: 1 }}>
+ {p.options.map(([v, label], i) => (v === '-' ? <View key={`s${i}`} style={{ height: 1, marginVertical: 4, marginHorizontal: 6, backgroundColor: t.separator }} />
+ : <PopRow key={String(v)} label={label} checked={v === p.value} onClick={() => { popup.set(null); if (v !== p.value) p.onChange(v); }} />))}
+ </ScrollView>
+ </View>
+ </>
+ );
+}
+
+function PopRow({ label, checked, onClick }) {
+ const t = useTheme();
+ const [hover, setHover] = useState(false);
+ return (
+ <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ height: 24, paddingHorizontal: 6, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 4, backgroundColor: hover ? t.accent : 'transparent' }}>
+ <Text style={{ width: 14, fontSize: 11, color: hover ? '#fff' : t.text }}>{checked ? '✓' : ''}</Text>
+ <Text style={{ flex: 1, fontSize: 12, whiteSpace: 'nowrap', color: hover ? '#fff' : t.text, textAlign: 'start' }}>{label}</Text>
+ </View>
+ );
+}
+
+// "HH:MM" ↔ minutes after midnight, and a compact time field made of two steppers.
+export const hhmm = (m) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
+
+export function TimeField({ value, onChange, format }) {
+ const t = useTheme();
+ const step = (d) => onChange((((value + d) % 1440) + 1440) % 1440);
+ const Arrow = ({ glyph, d }) => (
+ <View onClick={() => step(d)} style={{ width: 16, height: 11, alignItems: 'center', justifyContent: 'center' }}>
+ <Text style={{ fontSize: 7, color: t.textDim }}>{glyph}</Text>
+ </View>
+ );
+ return (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 2, direction: 'ltr' }}>
+ <View style={{ height: 24, minWidth: 66, paddingHorizontal: 8, borderRadius: 6, backgroundColor: t.control, justifyContent: 'center' }}>
+ <Text style={{ fontSize: 12, color: t.text, textAlign: 'center' }}>{format ? format(value) : hhmm(value)}</Text>
+ </View>
+ <View>
+ <Arrow glyph="▲" d={15} />
+ <Arrow glyph="▼" d={-15} />
+ </View>
+ </View>
+ );
+}
diff --git a/assets/locales/en/backup.json b/assets/locales/en/backup.json
index 80d33e8..2b2c148 100644
--- a/assets/locales/en/backup.json
+++ b/assets/locales/en/backup.json
@@ -22,7 +22,7 @@
"bytes": "{done} of {total}",
"cancel": "Cancel",
"dest": "Destination",
- "destHelp": "An external disk (ext4 recommended) or a folder. Backups are stored in LordOS-Copias.",
+ "destHelp": "An external disk (ext4 recommended) or a folder. Backups are stored in LordOS-Backups.",
"volFree": "{free} free of {total} · {fs}",
"noLinks": "no hard links: every backup takes full space",
"noDisks": "No external disks mounted. Connect one or choose a folder.",
@@ -104,5 +104,12 @@
"encLock": "Lock",
"encWorking": "Checking the passphrase…",
"notify.lockedTitle": "Backups are encrypted",
- "notify.lockedBody": "Enter the passphrase so scheduled backups can continue."
+ "notify.lockedBody": "Enter the passphrase so scheduled backups can continue.",
+ "err.wrong-passphrase": "Wrong passphrase",
+ "err.not-encrypted": "This destination is not encrypted",
+ "err.plain-backups-exist": "There are unencrypted backups on this destination: choose another one",
+ "err.setup-failed": "Couldn't turn on encryption",
+ "err.no-destination": "Choose a destination first",
+ "err.locked": "Backups are encrypted: unlock them first",
+ "err.interrupted": "It was interrupted"
}
\ No newline at end of file
diff --git a/assets/locales/en/editor.json b/assets/locales/en/editor.json
index 689365f..5707814 100644
--- a/assets/locales/en/editor.json
+++ b/assets/locales/en/editor.json
@@ -72,5 +72,10 @@
"status.tabs": "Tabs: {n}",
"tooBig": "is too big for the editor ({size}; max. 8 MB)",
"untitled": "Untitled",
- "cmd.print": "Print…"
+ "cmd.print": "Print…",
+ "find.prev": "Previous match",
+ "find.next": "Next match",
+ "find.close": "Close find",
+ "find.regex": "Regular expression",
+ "find.case": "Match case"
}
diff --git a/assets/locales/en/fonts.json b/assets/locales/en/fonts.json
index 1b2a2eb..7336299 100644
--- a/assets/locales/en/fonts.json
+++ b/assets/locales/en/fonts.json
@@ -85,5 +85,7 @@
"block.ligatures": "Ligatures",
"block.halfwidth": "Fullwidth forms",
"block.mathAlnum": "Math letters",
- "block.emoji": "Emoji & pictographs"
+ "block.emoji": "Emoji & pictographs",
+ "collections": "Collections",
+ "sizeTip": "Sample size"
}
diff --git a/assets/locales/en/notes.json b/assets/locales/en/notes.json
index dce6db0..c2dfbf7 100644
--- a/assets/locales/en/notes.json
+++ b/assets/locales/en/notes.json
@@ -39,7 +39,20 @@
"read": "Read",
"search": "Search notes",
"showDesktop": "On desktop",
- "toc": "CONTENTS",
+ "toc": "Contents",
"untitled": "Untitled",
- "print": "Print…"
+ "print": "Print…",
+ "insert": "Insert",
+ "insertEmoji": "Emoji…",
+ "insertImage": "Image…",
+ "insertFile": "Attachment…",
+ "more": "More",
+ "color": "Color",
+ "color.yellow": "Yellow",
+ "color.pink": "Pink",
+ "color.green": "Green",
+ "color.blue": "Blue",
+ "color.purple": "Purple",
+ "color.gray": "Gray",
+ "noneHint": "Create one with the ✎ button or ❖N."
}
diff --git a/assets/locales/en/passwords.json b/assets/locales/en/passwords.json
index a23ee7d..36ea5f7 100644
--- a/assets/locales/en/passwords.json
+++ b/assets/locales/en/passwords.json
@@ -427,5 +427,7 @@
"err.fido-denied": "Permission to use the key was denied.",
"err.unavailable": "The vault helper is not available.",
"err.bad-keyfile": "The KeePass key file is not valid.",
- "err.other": "Error: {code}"
+ "err.other": "Error: {code}",
+ "autofill.title": "Fill from Passwords",
+ "autofill.none": "Nothing saved for this (or Passwords is locked)."
}
diff --git a/assets/locales/en/pdf.json b/assets/locales/en/pdf.json
index 506362e..f50fefe 100644
--- a/assets/locales/en/pdf.json
+++ b/assets/locales/en/pdf.json
@@ -61,5 +61,12 @@
"zoom.page": "Whole page",
"go.page": "Go to page…",
"go.first": "First page",
- "go.last": "Last page"
+ "go.last": "Last page",
+ "tool.sidebar": "Show or hide the sidebar",
+ "tool.select": "Select text",
+ "tool.highlight": "Highlight",
+ "tool.ink": "Draw freehand",
+ "tool.note": "Add a note",
+ "tool.zoomToggle": "Fit width or whole page",
+ "recent": "PDFs in your folder"
}
diff --git a/assets/locales/en/photos.json b/assets/locales/en/photos.json
index c973bc3..48c3355 100644
--- a/assets/locales/en/photos.json
+++ b/assets/locales/en/photos.json
@@ -35,5 +35,13 @@
"month.11": "December",
"menu.file": "File",
"menu.print": "Print…",
- "menu.slideshow": "Slideshow"
+ "menu.slideshow": "Slideshow",
+ "refresh": "Reload the folder",
+ "zoomIn": "Zoom in",
+ "zoomOut": "Zoom out",
+ "rotateLeft": "Rotate left",
+ "rotateRight": "Rotate right",
+ "fullscreen": "Full screen",
+ "emptyTitle": "No photos",
+ "thumbSize": "Thumbnail size"
}
diff --git a/assets/locales/en/prefs.json b/assets/locales/en/prefs.json
new file mode 100644
index 0000000..326e021
--- /dev/null
+++ b/assets/locales/en/prefs.json
@@ -0,0 +1,229 @@
+{
+ "bt.audioHint": "Headphones and speakers also appear in Sound once they are connected.",
+ "bt.battery": "Battery {pct}%",
+ "bt.connect": "Connect",
+ "bt.connected": "Connected",
+ "bt.disconnect": "Disconnect",
+ "bt.err.authFailed": "Pairing failed: the code did not match or the device refused it.",
+ "bt.err.blocked": "Bluetooth is turned off by a hardware or software switch (rfkill).",
+ "bt.err.canceled": "Pairing was canceled.",
+ "bt.err.failed": "The device did not respond. Make sure it is on and nearby.",
+ "bt.err.noProfile": "Paired, but the device offers no service LordOS can connect to (audio, input).",
+ "bt.forget": "Forget This Device…",
+ "bt.more": "More",
+ "bt.myDevices": "My Devices",
+ "bt.nearby": "Nearby Devices",
+ "bt.nearbyHint": "Put the device in pairing mode to see it here.",
+ "bt.nearbySearching": "Nearby Devices — searching…",
+ "bt.noAdapter": "This computer has no Bluetooth adapter.",
+ "bt.noAgent": "LordOS could not register as the pairing agent: devices that ask for a code may not pair.",
+ "bt.noDevices": "No devices",
+ "bt.noService": "The Bluetooth service (bluez) is not running or not installed.",
+ "bt.noneNearby": "No devices found",
+ "bt.notConnected": "Not connected",
+ "bt.offHint": "Turn on Bluetooth to connect headphones, keyboards, mice and other devices.",
+ "bt.pairing": "Pairing…",
+ "bt.prompt.allow": "Allow",
+ "bt.prompt.authorize.body": "“{name}” wants to pair with this computer.",
+ "bt.prompt.authorize.placeholder": "",
+ "bt.prompt.authorize.title": "Bluetooth Pairing Request",
+ "bt.prompt.cancel": "Cancel",
+ "bt.prompt.confirm.body": "Make sure this code matches the one shown on “{name}”.",
+ "bt.prompt.confirm.placeholder": "",
+ "bt.prompt.confirm.title": "Pair with “{name}”?",
+ "bt.prompt.deny": "Deny",
+ "bt.prompt.display-passkey.body": "Type this code on “{name}”, then press Return on it.",
+ "bt.prompt.display-passkey.placeholder": "",
+ "bt.prompt.display-passkey.title": "Pairing with “{name}”",
+ "bt.prompt.display-pin.body": "Enter this PIN on “{name}”.",
+ "bt.prompt.display-pin.placeholder": "",
+ "bt.prompt.display-pin.title": "Pairing with “{name}”",
+ "bt.prompt.pair": "Pair",
+ "bt.prompt.passkey.body": "Enter the 6-digit code shown on “{name}”.",
+ "bt.prompt.passkey.placeholder": "000000",
+ "bt.prompt.passkey.title": "Pairing with “{name}”",
+ "bt.prompt.pin.body": "Enter the PIN for “{name}” (often 0000 or 1234; check its manual).",
+ "bt.prompt.pin.placeholder": "PIN",
+ "bt.prompt.pin.title": "Pairing with “{name}”",
+ "bt.prompt.service.body": "“{name}” wants to use a service on this computer.",
+ "bt.prompt.service.placeholder": "",
+ "bt.prompt.service.title": "Allow “{name}”?",
+ "bt.searching": "Searching…",
+ "bt.signal": "Signal {dbm} dBm",
+ "bt.title": "Bluetooth",
+ "bt.unblock": "Turn On",
+ "bt.visibleAs": "Now discoverable as “{name}”.",
+ "bt.working": "Connecting…",
+ "defaults.cat.browser": "Web browser",
+ "defaults.cat.images": "Images",
+ "defaults.cat.mail": "Email",
+ "defaults.cat.music": "Music",
+ "defaults.cat.pdf": "PDF documents",
+ "defaults.cat.terminal": "Terminal",
+ "defaults.cat.text": "Text editor",
+ "defaults.cat.video": "Video",
+ "defaults.choose": "Choose…",
+ "defaults.failed": "Could not save the choice in ~/.config/mimeapps.list.",
+ "defaults.filesHint": "Files opens documents with these apps when you double-click them, and lists them first in “Open With”.",
+ "defaults.footer": "Shared with Linux apps (GNOME, KDE, xdg-open) through ~/.config/mimeapps.list.",
+ "defaults.none": "No installed app can open these",
+ "defaults.other": "{id}",
+ "defaults.tag": "{name} (default)",
+ "display.brightness": "Brightness",
+ "display.extend": "Extend",
+ "display.failed": "That mode could not be used. The previous one is still active.",
+ "display.hz": "{hz} Hz",
+ "display.inches": "{n}-inch",
+ "display.keep": "Keep",
+ "display.keepBody": {
+ "one": "Your display settings will go back to the previous ones in {count} second.",
+ "other": "Your display settings will go back to the previous ones in {count} seconds."
+ },
+ "display.keepTitle": "Keep these display settings?",
+ "display.makeMain": "Use as Main Display",
+ "display.mirror": "Mirror",
+ "display.multiple": "Multiple displays",
+ "display.multipleHint": "LordOS drives one display at a time for now: extending the desktop or mirroring it on a second display is not available yet. You can choose which connected display to use.",
+ "display.native": "{w} × {h} (native)",
+ "display.noBacklight": "This display does not offer brightness control (external monitors and virtual machines).",
+ "display.notInUse": "Not in use",
+ "display.notOnMonitor": "This session is not on the monitor right now (it is being viewed from the network), so its displays cannot be changed. Night Shift settings still apply when it returns.",
+ "display.onlyOne": "Only one display is connected",
+ "display.refresh": "Refresh rate",
+ "display.resolution": "Resolution",
+ "display.revert": "Revert",
+ "display.rotStandard": "Standard",
+ "display.rotation": "Rotation",
+ "display.rotationHint": "A rotated screen is composed by the CPU.",
+ "display.scale": "Scale",
+ "display.scaleHint": "Not available yet: the interface is drawn at 100% (see docs/SETTINGS.md). On large screens, choose a lower resolution.",
+ "display.unavailable": "The display information is not available.",
+ "display.useAs": "Use as",
+ "night.custom": "Custom",
+ "night.customHint": "Night Shift turns on and off at these times every day.",
+ "night.footer": "Night Shift shifts the colors of your display to the warmer end of the spectrum after dark.",
+ "night.from": "From",
+ "night.lessWarm": "Less warm",
+ "night.manualOff": "Off until {time}",
+ "night.manualOn": "On until {time}",
+ "night.moreWarm": "More warm",
+ "night.noSun": "The sunset time is not known for this time zone: Night Shift uses 22:00 to 07:00.",
+ "night.now": "Turn on now",
+ "night.off": "Off",
+ "night.offHint": "Use the switch below to turn it on until tomorrow.",
+ "night.schedule": "Schedule",
+ "night.software": "This display has no color table (gamma LUT), so Night Shift tints the image by software.",
+ "night.sun": "Sunset to Sunrise",
+ "night.sunHint": "Today: from {set} to {rise}, for your time zone. Your location is never looked up on the network.",
+ "night.temp": "Color temperature",
+ "night.title": "Night Shift",
+ "night.to": "to",
+ "notif.allow": "Allow notifications",
+ "notif.allowPackage": "The same as the “Notifications” permission in Privacy & Security.",
+ "notif.apps": "Application notifications",
+ "notif.appsFooter": "Apps appear here after they send their first notification. Linux apps (GTK, Qt) notify through the standard freedesktop service.",
+ "notif.byApp": "By app",
+ "notif.dnd": "Do Not Disturb",
+ "notif.dndFooter": "While Do Not Disturb is on, notifications are kept silently and no banners are shown.",
+ "notif.dndOffHint": "Notifications are shown",
+ "notif.dndOnHint": "On: notifications are silenced",
+ "notif.focus": "Focus",
+ "notif.from": "From",
+ "notif.grouping": "Group notifications",
+ "notif.groupingHint": "Several banners from the same app are shown as one.",
+ "notif.lockScreen": "Show on lock screen",
+ "notif.lockScreenHint": "The lock screen does not show notifications yet.",
+ "notif.noGrouping": "Off",
+ "notif.off": "Off",
+ "notif.playSound": "Play sound for notifications",
+ "notif.schedule": "Turn on every day",
+ "notif.scheduleHint": "From {from} to {to}",
+ "notif.sound": "Sound",
+ "notif.style.alert": "Alerts",
+ "notif.style.banner": "Banners",
+ "notif.style.none": "None",
+ "notif.styleHint.alert": "Alerts stay on screen until you dismiss them.",
+ "notif.styleHint.banner": "Banners go away on their own after a few seconds.",
+ "notif.styleHint.none": "Kept quietly, without a banner.",
+ "notif.styleLabel": "Alert style",
+ "notif.test": "Try it",
+ "notif.testBody": "Notifications look like this.",
+ "notif.testButton": "Send a test notification",
+ "notif.testTitle": "Test notification",
+ "notif.to": "to",
+ "power.act.hibernate": "Hibernate",
+ "power.act.ignore": "Do nothing",
+ "power.act.poweroff": "Shut down",
+ "power.act.suspend": "Sleep",
+ "power.battery": "Battery",
+ "power.buttons": "Power button and lid",
+ "power.buttonsHint": "Handled by the system (systemd-logind) for every user.",
+ "power.charging": "Charging",
+ "power.chargingLeft": "Charging — {time} until full",
+ "power.criticalTitle": "Battery almost empty",
+ "power.cycles": "{n} cycles",
+ "power.degraded": "Performance mode is limited right now (the computer is too hot or on a lap).",
+ "power.healthNormal": "Battery health: {pct}% (normal)",
+ "power.healthService": "Battery health: {pct}% (service recommended)",
+ "power.healthUnknown": "Battery health: unknown",
+ "power.hm": "{h} h {m} min",
+ "power.immediately": "Immediately",
+ "power.left": "{time} remaining",
+ "power.lid": "When the lid is closed",
+ "power.lidAC": "When the lid is closed on power adapter",
+ "power.lock": "Require password after the display turns off",
+ "power.lowBattery": "Low battery notification",
+ "power.lowBatteryHint": "At 20%, 10% and 5%.",
+ "power.lowBody": "{pct}% left. Connect the power adapter.",
+ "power.lowTitle": "Low battery",
+ "power.m": "{m} min",
+ "power.menuPercent": "Show percentage in the menu bar",
+ "power.mode": "Energy mode",
+ "power.modeGovernor": "Without power-profiles-daemon: sets the CPU frequency governor (now: {gov}).",
+ "power.modeHint": "Through power-profiles-daemon.",
+ "power.needAdmin": "Only an administrator can change this.",
+ "power.never": "Never",
+ "power.noBattery": "This computer runs on power from the wall (no battery).",
+ "power.noProfiles": "Not available: install power-profiles-daemon, or this CPU does not allow changing its frequency.",
+ "power.off": "Turn display off when inactive",
+ "power.offAC": "Turn display off on power adapter when inactive",
+ "power.offBattery": "Turn display off on battery when inactive",
+ "power.onACFull": "Connected to the power adapter",
+ "power.onBattery": "On battery",
+ "power.powerKey": "When the power button is pressed",
+ "power.profile.balanced": "Balanced",
+ "power.profile.performance": "Performance",
+ "power.profile.power-saver": "Low Power",
+ "power.screenSleep": "Display and sleep",
+ "power.screenSleepHint": "Counted from the last time the keyboard, mouse or trackpad was used.",
+ "power.secs": "{s} seconds",
+ "power.sleep": "Sleep when inactive",
+ "power.sleepAC": "Sleep on power adapter when inactive",
+ "power.sleepBattery": "Sleep on battery when inactive",
+ "time.auto": "Set time and date automatically",
+ "time.byRegion": "Like the region",
+ "time.change": "Change…",
+ "time.dateFull": "Weekday and date",
+ "time.dateNone": "Time only",
+ "time.dateTime": "Date and time",
+ "time.dateWeekday": "Weekday",
+ "time.format": "Format",
+ "time.h12": "12-hour",
+ "time.h24": "24-hour",
+ "time.hour24": "Time format",
+ "time.hour24Hint": "“Like the region” follows Language & Region.",
+ "time.manual": "Set by hand",
+ "time.manualHint": "Year-month-day and hours:minutes.",
+ "time.menuClock": "Menu bar clock",
+ "time.needAdmin": "Only an administrator can change the date, the time and the time zone.",
+ "time.noNtp": "No time service (systemd-timesyncd) is installed.",
+ "time.preview": "Preview",
+ "time.searchZone": "Search for a city",
+ "time.seconds": "Show seconds",
+ "time.set": "Set",
+ "time.showDate": "Show date",
+ "time.synced": "Synchronized with the network time servers (systemd-timesyncd).",
+ "time.syncing": "Waiting for the first synchronization…",
+ "time.zone": "Time zone",
+ "time.zoneFooter": "Chosen by hand: LordOS never looks up your location on the network."
+}
diff --git a/assets/locales/en/settings.json b/assets/locales/en/settings.json
index 93790dc..075b021 100644
--- a/assets/locales/en/settings.json
+++ b/assets/locales/en/settings.json
@@ -224,5 +224,17 @@
"dock.recentsHint": "The last three apps used that aren't pinned, after a divider.",
"dock.taskbar": "Taskbar position",
"dock.taskbarHint": "Classic theme. Maximized windows don't go under the taskbar.",
- "dock.sidesHint": "Left and right are sides of the screen: they don't swap in a right-to-left language."
+ "dock.sidesHint": "Left and right are sides of the screen: they don't swap in a right-to-left language.",
+ "section.displays": "Displays",
+ "section.bluetooth": "Bluetooth",
+ "section.power": "Energy",
+ "section.notifications": "Notifications",
+ "section.datetime": "Date & Time",
+ "section.defaultapps": "Default Apps",
+ "keywords.displays": "display monitor screen resolution refresh rate hz rotation brightness night shift color temperature edid",
+ "keywords.bluetooth": "bluetooth pair pairing headphones headset speaker keyboard mouse wireless",
+ "keywords.power": "battery energy power profile low power performance sleep suspend lid power button screen off",
+ "keywords.notifications": "notifications alerts banners do not disturb focus sound",
+ "keywords.datetime": "date time clock ntp time zone 24-hour 12-hour menu bar seconds",
+ "keywords.defaultapps": "default apps browser mail music video images pdf text editor terminal open with mimeapps"
}
diff --git a/assets/locales/es/backup.json b/assets/locales/es/backup.json
index 2dde1f0..c9d1d91 100644
--- a/assets/locales/es/backup.json
+++ b/assets/locales/es/backup.json
@@ -22,7 +22,7 @@
"bytes": "{done} de {total}",
"cancel": "Cancelar",
"dest": "Destino",
- "destHelp": "Un disco externo (recomendado: ext4) o una carpeta. Las copias se guardan en LordOS-Copias.",
+ "destHelp": "Un disco externo (recomendado: ext4) o una carpeta. Las copias se guardan en LordOS-Backups.",
"volFree": "{free} libres de {total} · {fs}",
"noLinks": "sin enlaces duros: cada copia ocupa todo",
"noDisks": "No hay discos externos montados. Conectá uno o elegí una carpeta.",
@@ -104,5 +104,12 @@
"encLock": "Bloquear",
"encWorking": "Comprobando la frase…",
"notify.lockedTitle": "Las copias de seguridad están cifradas",
- "notify.lockedBody": "Escribí la frase para que sigan las copias programadas."
+ "notify.lockedBody": "Escribí la frase para que sigan las copias programadas.",
+ "err.wrong-passphrase": "Frase incorrecta",
+ "err.not-encrypted": "Este destino no está cifrado",
+ "err.plain-backups-exist": "Ya hay copias sin cifrar en este destino: elegí otro",
+ "err.setup-failed": "No se pudo activar el cifrado",
+ "err.no-destination": "Elegí un destino primero",
+ "err.locked": "Las copias están cifradas: desbloquealas primero",
+ "err.interrupted": "Se interrumpió"
}
\ No newline at end of file
diff --git a/assets/locales/es/editor.json b/assets/locales/es/editor.json
index 974b825..aa34d8f 100644
--- a/assets/locales/es/editor.json
+++ b/assets/locales/es/editor.json
@@ -72,5 +72,10 @@
"status.tabs": "Tabs: {n}",
"tooBig": "es demasiado grande para el editor ({size}; máx. 8 MB)",
"untitled": "Sin título",
- "cmd.print": "Imprimir…"
+ "cmd.print": "Imprimir…",
+ "find.prev": "Coincidencia anterior",
+ "find.next": "Coincidencia siguiente",
+ "find.close": "Cerrar la búsqueda",
+ "find.regex": "Expresión regular",
+ "find.case": "Distinguir mayúsculas y minúsculas"
}
diff --git a/assets/locales/es/fonts.json b/assets/locales/es/fonts.json
index 0202911..51ef7f6 100644
--- a/assets/locales/es/fonts.json
+++ b/assets/locales/es/fonts.json
@@ -85,5 +85,7 @@
"block.ligatures": "Ligaduras",
"block.halfwidth": "Ancho completo",
"block.mathAlnum": "Letras matemáticas",
- "block.emoji": "Emoji y pictogramas"
+ "block.emoji": "Emoji y pictogramas",
+ "collections": "Colecciones",
+ "sizeTip": "Tamaño de la muestra"
}
diff --git a/assets/locales/es/notes.json b/assets/locales/es/notes.json
index 77bf9df..4b72bf9 100644
--- a/assets/locales/es/notes.json
+++ b/assets/locales/es/notes.json
@@ -39,7 +39,20 @@
"read": "Leer",
"search": "Buscar en las notas",
"showDesktop": "En el escritorio",
- "toc": "ÍNDICE",
+ "toc": "Índice",
"untitled": "Sin título",
- "print": "Imprimir…"
+ "print": "Imprimir…",
+ "insert": "Insertar",
+ "insertEmoji": "Emoji…",
+ "insertImage": "Imagen…",
+ "insertFile": "Archivo adjunto…",
+ "more": "Más",
+ "color": "Color",
+ "color.yellow": "Amarillo",
+ "color.pink": "Rosa",
+ "color.green": "Verde",
+ "color.blue": "Azul",
+ "color.purple": "Violeta",
+ "color.gray": "Gris",
+ "noneHint": "Creá una con el botón ✎ o con ❖N."
}
diff --git a/assets/locales/es/passwords.json b/assets/locales/es/passwords.json
index 3145025..7c193ce 100644
--- a/assets/locales/es/passwords.json
+++ b/assets/locales/es/passwords.json
@@ -427,5 +427,7 @@
"err.fido-denied": "Permiso para usar la llave denegado.",
"err.unavailable": "El ayudante de la bóveda no está disponible.",
"err.bad-keyfile": "El archivo llave de KeePass no es válido.",
- "err.other": "Error: {code}"
+ "err.other": "Error: {code}",
+ "autofill.title": "Rellenar desde Contraseñas",
+ "autofill.none": "No hay nada guardado para esto (o Contraseñas está bloqueada)."
}
diff --git a/assets/locales/es/pdf.json b/assets/locales/es/pdf.json
index 2b58a56..b1941f7 100644
--- a/assets/locales/es/pdf.json
+++ b/assets/locales/es/pdf.json
@@ -61,5 +61,12 @@
"zoom.page": "Página entera",
"go.page": "Ir a la página…",
"go.first": "Primera página",
- "go.last": "Última página"
+ "go.last": "Última página",
+ "tool.sidebar": "Mostrar u ocultar la barra lateral",
+ "tool.select": "Seleccionar texto",
+ "tool.highlight": "Resaltar",
+ "tool.ink": "Dibujar a mano alzada",
+ "tool.note": "Agregar una nota",
+ "tool.zoomToggle": "Ajustar al ancho o a la página",
+ "recent": "PDF en tu carpeta"
}
diff --git a/assets/locales/es/photos.json b/assets/locales/es/photos.json
index c9842b1..650ebe2 100644
--- a/assets/locales/es/photos.json
+++ b/assets/locales/es/photos.json
@@ -35,5 +35,13 @@
"month.11": "diciembre",
"menu.file": "Archivo",
"menu.print": "Imprimir…",
- "menu.slideshow": "Presentación"
+ "menu.slideshow": "Presentación",
+ "refresh": "Volver a leer la carpeta",
+ "zoomIn": "Acercar",
+ "zoomOut": "Alejar",
+ "rotateLeft": "Girar a la izquierda",
+ "rotateRight": "Girar a la derecha",
+ "fullscreen": "Pantalla completa",
+ "emptyTitle": "No hay fotos",
+ "thumbSize": "Tamaño de las miniaturas"
}
diff --git a/assets/locales/es/prefs.json b/assets/locales/es/prefs.json
new file mode 100644
index 0000000..c3a0b3e
--- /dev/null
+++ b/assets/locales/es/prefs.json
@@ -0,0 +1,229 @@
+{
+ "bt.audioHint": "Los auriculares y parlantes aparecen también en Sonido cuando están conectados.",
+ "bt.battery": "Batería {pct} %",
+ "bt.connect": "Conectar",
+ "bt.connected": "Conectado",
+ "bt.disconnect": "Desconectar",
+ "bt.err.authFailed": "No se pudo vincular: el código no coincidió o el dispositivo lo rechazó.",
+ "bt.err.blocked": "El Bluetooth está apagado por un interruptor de hardware o de software (rfkill).",
+ "bt.err.canceled": "Se canceló la vinculación.",
+ "bt.err.failed": "El dispositivo no respondió. Fijate que esté encendido y cerca.",
+ "bt.err.noProfile": "Vinculado, pero el dispositivo no ofrece ningún servicio que LordOS pueda conectar (audio, entrada).",
+ "bt.forget": "Olvidar este dispositivo…",
+ "bt.more": "Más",
+ "bt.myDevices": "Mis dispositivos",
+ "bt.nearby": "Dispositivos cercanos",
+ "bt.nearbyHint": "Poné el dispositivo en modo de vinculación para verlo acá.",
+ "bt.nearbySearching": "Dispositivos cercanos — buscando…",
+ "bt.noAdapter": "Este equipo no tiene un adaptador Bluetooth.",
+ "bt.noAgent": "LordOS no pudo registrarse para vincular: los dispositivos que piden un código quizás no se vinculen.",
+ "bt.noDevices": "Ningún dispositivo",
+ "bt.noService": "El servicio de Bluetooth (bluez) no está corriendo o no está instalado.",
+ "bt.noneNearby": "No se encontraron dispositivos",
+ "bt.notConnected": "No conectado",
+ "bt.offHint": "Activá el Bluetooth para conectar auriculares, teclados, mouses y otros dispositivos.",
+ "bt.pairing": "Vinculando…",
+ "bt.prompt.allow": "Permitir",
+ "bt.prompt.authorize.body": "«{name}» quiere vincularse con este equipo.",
+ "bt.prompt.authorize.placeholder": "",
+ "bt.prompt.authorize.title": "Pedido de vinculación Bluetooth",
+ "bt.prompt.cancel": "Cancelar",
+ "bt.prompt.confirm.body": "Fijate que este código sea el mismo que muestra «{name}».",
+ "bt.prompt.confirm.placeholder": "",
+ "bt.prompt.confirm.title": "¿Vincular con «{name}»?",
+ "bt.prompt.deny": "Rechazar",
+ "bt.prompt.display-passkey.body": "Escribí este código en «{name}» y apretá Intro en él.",
+ "bt.prompt.display-passkey.placeholder": "",
+ "bt.prompt.display-passkey.title": "Vinculando con «{name}»",
+ "bt.prompt.display-pin.body": "Ingresá este PIN en «{name}».",
+ "bt.prompt.display-pin.placeholder": "",
+ "bt.prompt.display-pin.title": "Vinculando con «{name}»",
+ "bt.prompt.pair": "Vincular",
+ "bt.prompt.passkey.body": "Ingresá el código de 6 dígitos que muestra «{name}».",
+ "bt.prompt.passkey.placeholder": "000000",
+ "bt.prompt.passkey.title": "Vinculando con «{name}»",
+ "bt.prompt.pin.body": "Ingresá el PIN de «{name}» (suele ser 0000 o 1234; mirá su manual).",
+ "bt.prompt.pin.placeholder": "PIN",
+ "bt.prompt.pin.title": "Vinculando con «{name}»",
+ "bt.prompt.service.body": "«{name}» quiere usar un servicio de este equipo.",
+ "bt.prompt.service.placeholder": "",
+ "bt.prompt.service.title": "¿Permitir a «{name}»?",
+ "bt.searching": "Buscando…",
+ "bt.signal": "Señal {dbm} dBm",
+ "bt.title": "Bluetooth",
+ "bt.unblock": "Activar",
+ "bt.visibleAs": "Visible como «{name}».",
+ "bt.working": "Conectando…",
+ "defaults.cat.browser": "Navegador web",
+ "defaults.cat.images": "Imágenes",
+ "defaults.cat.mail": "Correo",
+ "defaults.cat.music": "Música",
+ "defaults.cat.pdf": "Documentos PDF",
+ "defaults.cat.terminal": "Terminal",
+ "defaults.cat.text": "Editor de texto",
+ "defaults.cat.video": "Video",
+ "defaults.choose": "Elegir…",
+ "defaults.failed": "No se pudo guardar la elección en ~/.config/mimeapps.list.",
+ "defaults.filesHint": "Archivos abre los documentos con estas apps al hacer doble clic, y las muestra primero en «Abrir con».",
+ "defaults.footer": "Se comparte con las apps Linux (GNOME, KDE, xdg-open) por ~/.config/mimeapps.list.",
+ "defaults.none": "Ninguna app instalada abre estos archivos",
+ "defaults.other": "{id}",
+ "defaults.tag": "{name} (por defecto)",
+ "display.brightness": "Brillo",
+ "display.extend": "Extender",
+ "display.failed": "No se pudo usar ese modo. Sigue el anterior.",
+ "display.hz": "{hz} Hz",
+ "display.inches": "{n} pulgadas",
+ "display.keep": "Mantener",
+ "display.keepBody": {
+ "one": "La pantalla vuelve a la configuración anterior en {count} segundo.",
+ "other": "La pantalla vuelve a la configuración anterior en {count} segundos."
+ },
+ "display.keepTitle": "¿Mantener esta configuración de pantalla?",
+ "display.makeMain": "Usar como principal",
+ "display.mirror": "Duplicar",
+ "display.multiple": "Varias pantallas",
+ "display.multipleHint": "Por ahora LordOS usa una pantalla a la vez: extender el escritorio o duplicarlo en una segunda pantalla todavía no se puede. Podés elegir cuál de las pantallas conectadas usar.",
+ "display.native": "{w} × {h} (nativa)",
+ "display.noBacklight": "Esta pantalla no permite cambiar el brillo (monitores externos y máquinas virtuales).",
+ "display.notInUse": "Sin usar",
+ "display.notOnMonitor": "Esta sesión no está en el monitor ahora (se está mirando desde la red), así que no se pueden cambiar sus pantallas. Night Shift se aplica cuando vuelva.",
+ "display.onlyOne": "Hay una sola pantalla conectada",
+ "display.refresh": "Frecuencia de actualización",
+ "display.resolution": "Resolución",
+ "display.revert": "Volver",
+ "display.rotStandard": "Normal",
+ "display.rotation": "Rotación",
+ "display.rotationHint": "Con la pantalla girada se compone por CPU.",
+ "display.scale": "Escala",
+ "display.scaleHint": "Todavía no está disponible: la interfaz se dibuja al 100 % (ver docs/SETTINGS.md). En pantallas grandes, elegí una resolución menor.",
+ "display.unavailable": "No hay información de las pantallas.",
+ "display.useAs": "Usar como",
+ "night.custom": "Personalizado",
+ "night.customHint": "Night Shift se activa y desactiva a estas horas todos los días.",
+ "night.footer": "Night Shift pasa los colores de la pantalla hacia los tonos más cálidos cuando oscurece.",
+ "night.from": "Desde",
+ "night.lessWarm": "Menos cálido",
+ "night.manualOff": "Desactivado hasta las {time}",
+ "night.manualOn": "Activado hasta las {time}",
+ "night.moreWarm": "Más cálido",
+ "night.noSun": "No se conoce la puesta del sol para esta zona horaria: Night Shift usa de 22:00 a 07:00.",
+ "night.now": "Activar ahora",
+ "night.off": "No",
+ "night.offHint": "Usá el interruptor de abajo para activarlo hasta mañana.",
+ "night.schedule": "Programar",
+ "night.software": "Esta pantalla no tiene tabla de colores (gamma LUT), así que Night Shift tiñe la imagen por software.",
+ "night.sun": "Del atardecer al amanecer",
+ "night.sunHint": "Hoy: de {set} a {rise}, según tu zona horaria. Tu ubicación nunca se busca en la red.",
+ "night.temp": "Temperatura del color",
+ "night.title": "Night Shift",
+ "night.to": "a",
+ "notif.allow": "Permitir avisos",
+ "notif.allowPackage": "Es el mismo que el permiso «Avisos» de Privacidad y seguridad.",
+ "notif.apps": "Avisos de las apps",
+ "notif.appsFooter": "Las apps aparecen acá después de mandar su primer aviso. Las apps Linux (GTK, Qt) avisan por el servicio estándar de freedesktop.",
+ "notif.byApp": "Por app",
+ "notif.dnd": "No molestar",
+ "notif.dndFooter": "Con «No molestar» los avisos se guardan en silencio y no se muestran carteles.",
+ "notif.dndOffHint": "Los avisos se muestran",
+ "notif.dndOnHint": "Activado: los avisos están en silencio",
+ "notif.focus": "Concentración",
+ "notif.from": "Desde",
+ "notif.grouping": "Agrupar avisos",
+ "notif.groupingHint": "Varios carteles de la misma app se muestran como uno.",
+ "notif.lockScreen": "Mostrar en la pantalla bloqueada",
+ "notif.lockScreenHint": "La pantalla bloqueada todavía no muestra avisos.",
+ "notif.noGrouping": "No",
+ "notif.off": "Desactivados",
+ "notif.playSound": "Sonar al recibir avisos",
+ "notif.schedule": "Activar todos los días",
+ "notif.scheduleHint": "De {from} a {to}",
+ "notif.sound": "Sonido",
+ "notif.style.alert": "Alertas",
+ "notif.style.banner": "Carteles",
+ "notif.style.none": "Ninguno",
+ "notif.styleHint.alert": "Las alertas quedan en pantalla hasta que las cerrás.",
+ "notif.styleHint.banner": "Los carteles se van solos después de unos segundos.",
+ "notif.styleHint.none": "Se guardan en silencio, sin cartel.",
+ "notif.styleLabel": "Estilo",
+ "notif.test": "Probar",
+ "notif.testBody": "Así se ven los avisos.",
+ "notif.testButton": "Mandar un aviso de prueba",
+ "notif.testTitle": "Aviso de prueba",
+ "notif.to": "a",
+ "power.act.hibernate": "Hibernar",
+ "power.act.ignore": "No hacer nada",
+ "power.act.poweroff": "Apagar",
+ "power.act.suspend": "Suspender",
+ "power.battery": "Batería",
+ "power.buttons": "Botón de encendido y tapa",
+ "power.buttonsHint": "Lo maneja el sistema (systemd-logind) para todos los usuarios.",
+ "power.charging": "Cargando",
+ "power.chargingLeft": "Cargando — {time} para completar",
+ "power.criticalTitle": "Batería casi agotada",
+ "power.cycles": "{n} ciclos",
+ "power.degraded": "El modo de rendimiento está limitado ahora (el equipo está muy caliente o sobre las piernas).",
+ "power.healthNormal": "Estado de la batería: {pct} % (normal)",
+ "power.healthService": "Estado de la batería: {pct} % (conviene revisarla)",
+ "power.healthUnknown": "Estado de la batería: desconocido",
+ "power.hm": "{h} h {m} min",
+ "power.immediately": "Enseguida",
+ "power.left": "Quedan {time}",
+ "power.lid": "Al cerrar la tapa",
+ "power.lidAC": "Al cerrar la tapa con el cargador",
+ "power.lock": "Pedir contraseña después de apagar la pantalla",
+ "power.lowBattery": "Aviso de batería baja",
+ "power.lowBatteryHint": "Al 20 %, al 10 % y al 5 %.",
+ "power.lowBody": "Queda {pct} %. Conectá el cargador.",
+ "power.lowTitle": "Batería baja",
+ "power.m": "{m} min",
+ "power.menuPercent": "Mostrar el porcentaje en la barra de menú",
+ "power.mode": "Modo de energía",
+ "power.modeGovernor": "Sin power-profiles-daemon: cambia el regulador de frecuencia de la CPU (ahora: {gov}).",
+ "power.modeHint": "Con power-profiles-daemon.",
+ "power.needAdmin": "Solo un administrador puede cambiar esto.",
+ "power.never": "Nunca",
+ "power.noBattery": "Este equipo se alimenta de la red eléctrica (sin batería).",
+ "power.noProfiles": "No disponible: instalá power-profiles-daemon, o esta CPU no permite cambiar su frecuencia.",
+ "power.off": "Apagar la pantalla si está inactiva",
+ "power.offAC": "Apagar la pantalla con el cargador si está inactiva",
+ "power.offBattery": "Apagar la pantalla con batería si está inactiva",
+ "power.onACFull": "Conectado al cargador",
+ "power.onBattery": "Con batería",
+ "power.powerKey": "Al apretar el botón de encendido",
+ "power.profile.balanced": "Equilibrado",
+ "power.profile.performance": "Rendimiento",
+ "power.profile.power-saver": "Ahorro",
+ "power.screenSleep": "Pantalla y reposo",
+ "power.screenSleepHint": "Se cuenta desde la última vez que se usó el teclado, el mouse o el touchpad.",
+ "power.secs": "{s} segundos",
+ "power.sleep": "Suspender si está inactivo",
+ "power.sleepAC": "Suspender con el cargador si está inactivo",
+ "power.sleepBattery": "Suspender con batería si está inactivo",
+ "time.auto": "Ajustar la fecha y la hora automáticamente",
+ "time.byRegion": "Como la región",
+ "time.change": "Cambiar…",
+ "time.dateFull": "Día y fecha",
+ "time.dateNone": "Solo la hora",
+ "time.dateTime": "Fecha y hora",
+ "time.dateWeekday": "Día de la semana",
+ "time.format": "Formato",
+ "time.h12": "12 horas",
+ "time.h24": "24 horas",
+ "time.hour24": "Formato de la hora",
+ "time.hour24Hint": "«Como la región» sigue a Idioma y región.",
+ "time.manual": "A mano",
+ "time.manualHint": "Año-mes-día y horas:minutos.",
+ "time.menuClock": "Reloj de la barra de menú",
+ "time.needAdmin": "Solo un administrador puede cambiar la fecha, la hora y la zona horaria.",
+ "time.noNtp": "No hay un servicio de hora (systemd-timesyncd) instalado.",
+ "time.preview": "Vista previa",
+ "time.searchZone": "Buscar una ciudad",
+ "time.seconds": "Mostrar los segundos",
+ "time.set": "Ajustar",
+ "time.showDate": "Mostrar la fecha",
+ "time.synced": "Sincronizada con los servidores de hora de la red (systemd-timesyncd).",
+ "time.syncing": "Esperando la primera sincronización…",
+ "time.zone": "Zona horaria",
+ "time.zoneFooter": "Se elige a mano: LordOS nunca busca tu ubicación en la red."
+}
diff --git a/assets/locales/es/settings.json b/assets/locales/es/settings.json
index 3f76d4e..47c16ac 100644
--- a/assets/locales/es/settings.json
+++ b/assets/locales/es/settings.json
@@ -224,5 +224,17 @@
"dock.recentsHint": "Las últimas tres apps usadas que no están fijadas, después de una línea.",
"dock.taskbar": "Posición de la barra de tareas",
"dock.taskbarHint": "Tema Clásico. Las ventanas maximizadas no quedan debajo de la barra.",
- "dock.sidesHint": "Izquierda y derecha son lados de la pantalla: no cambian con un idioma de derecha a izquierda."
+ "dock.sidesHint": "Izquierda y derecha son lados de la pantalla: no cambian con un idioma de derecha a izquierda.",
+ "section.displays": "Pantallas",
+ "section.bluetooth": "Bluetooth",
+ "section.power": "Energía",
+ "section.notifications": "Notificaciones",
+ "section.datetime": "Fecha y hora",
+ "section.defaultapps": "Apps por defecto",
+ "keywords.displays": "pantalla monitor resolución frecuencia hz rotación girar brillo night shift noche temperatura color edid",
+ "keywords.bluetooth": "bluetooth vincular emparejar auriculares parlante teclado mouse inalámbrico",
+ "keywords.power": "batería energía perfil ahorro rendimiento suspender reposo tapa botón de encendido apagar pantalla",
+ "keywords.notifications": "notificaciones avisos alertas carteles no molestar concentración sonido",
+ "keywords.datetime": "fecha hora reloj ntp zona horaria 24 horas 12 horas barra de menú segundos",
+ "keywords.defaultapps": "apps por defecto predeterminadas navegador correo música video imágenes pdf editor de texto terminal abrir con"
}
diff --git a/assets/locales/pt/backup.json b/assets/locales/pt/backup.json
index de7e238..30c69b5 100644
--- a/assets/locales/pt/backup.json
+++ b/assets/locales/pt/backup.json
@@ -22,7 +22,7 @@
"bytes": "{done} de {total}",
"cancel": "Cancelar",
"dest": "Destino",
- "destHelp": "Um disco externo (recomendado: ext4) ou uma pasta. As cópias ficam em LordOS-Copias.",
+ "destHelp": "Um disco externo (recomendado: ext4) ou uma pasta. As cópias ficam em LordOS-Backups.",
"volFree": "{free} livres de {total} · {fs}",
"noLinks": "sem links físicos: cada cópia ocupa tudo",
"noDisks": "Nenhum disco externo montado. Conecte um ou escolha uma pasta.",
@@ -104,5 +104,12 @@
"encLock": "Bloquear",
"encWorking": "Verificando a frase…",
"notify.lockedTitle": "As cópias de segurança estão criptografadas",
- "notify.lockedBody": "Digite a frase para que as cópias programadas continuem."
+ "notify.lockedBody": "Digite a frase para que as cópias programadas continuem.",
+ "err.wrong-passphrase": "Frase incorreta",
+ "err.not-encrypted": "Este destino não está criptografado",
+ "err.plain-backups-exist": "Já existem cópias sem criptografia neste destino: escolha outro",
+ "err.setup-failed": "Não foi possível ativar a criptografia",
+ "err.no-destination": "Escolha um destino primeiro",
+ "err.locked": "As cópias estão criptografadas: desbloqueie-as primeiro",
+ "err.interrupted": "Foi interrompida"
}
\ No newline at end of file
diff --git a/assets/locales/pt/editor.json b/assets/locales/pt/editor.json
index b9fdc00..36ef622 100644
--- a/assets/locales/pt/editor.json
+++ b/assets/locales/pt/editor.json
@@ -72,5 +72,10 @@
"status.tabs": "Tabs: {n}",
"tooBig": "é grande demais para o editor ({size}; máx. 8 MB)",
"untitled": "Sem título",
- "cmd.print": "Imprimir…"
+ "cmd.print": "Imprimir…",
+ "find.prev": "Ocorrência anterior",
+ "find.next": "Próxima ocorrência",
+ "find.close": "Fechar a busca",
+ "find.regex": "Expressão regular",
+ "find.case": "Diferenciar maiúsculas e minúsculas"
}
diff --git a/assets/locales/pt/fonts.json b/assets/locales/pt/fonts.json
index 054eba0..54078e3 100644
--- a/assets/locales/pt/fonts.json
+++ b/assets/locales/pt/fonts.json
@@ -85,5 +85,7 @@
"block.ligatures": "Ligaduras",
"block.halfwidth": "Largura total",
"block.mathAlnum": "Letras matemáticas",
- "block.emoji": "Emoji e pictogramas"
+ "block.emoji": "Emoji e pictogramas",
+ "collections": "Coleções",
+ "sizeTip": "Tamanho da amostra"
}
diff --git a/assets/locales/pt/notes.json b/assets/locales/pt/notes.json
index a4ce859..949454d 100644
--- a/assets/locales/pt/notes.json
+++ b/assets/locales/pt/notes.json
@@ -39,7 +39,20 @@
"read": "Ler",
"search": "Buscar nas notas",
"showDesktop": "Na área de trabalho",
- "toc": "ÍNDICE",
+ "toc": "Índice",
"untitled": "Sem título",
- "print": "Imprimir…"
+ "print": "Imprimir…",
+ "insert": "Inserir",
+ "insertEmoji": "Emoji…",
+ "insertImage": "Imagem…",
+ "insertFile": "Anexo…",
+ "more": "Mais",
+ "color": "Cor",
+ "color.yellow": "Amarelo",
+ "color.pink": "Rosa",
+ "color.green": "Verde",
+ "color.blue": "Azul",
+ "color.purple": "Roxo",
+ "color.gray": "Cinza",
+ "noneHint": "Crie uma com o botão ✎ ou com ❖N."
}
diff --git a/assets/locales/pt/passwords.json b/assets/locales/pt/passwords.json
index feeef06..b823923 100644
--- a/assets/locales/pt/passwords.json
+++ b/assets/locales/pt/passwords.json
@@ -427,5 +427,7 @@
"err.fido-denied": "A permissão para usar a chave foi negada.",
"err.unavailable": "O ajudante do cofre não está disponível.",
"err.bad-keyfile": "O arquivo chave do KeePass não é válido.",
- "err.other": "Erro: {code}"
+ "err.other": "Erro: {code}",
+ "autofill.title": "Preencher com o Senhas",
+ "autofill.none": "Nada salvo para isto (ou o Senhas está bloqueado)."
}
diff --git a/assets/locales/pt/pdf.json b/assets/locales/pt/pdf.json
index 4aa2bd2..a6b0d0d 100644
--- a/assets/locales/pt/pdf.json
+++ b/assets/locales/pt/pdf.json
@@ -61,5 +61,12 @@
"zoom.page": "Página inteira",
"go.page": "Ir para a página…",
"go.first": "Primeira página",
- "go.last": "Última página"
+ "go.last": "Última página",
+ "tool.sidebar": "Mostrar ou ocultar a barra lateral",
+ "tool.select": "Selecionar texto",
+ "tool.highlight": "Destacar",
+ "tool.ink": "Desenhar à mão livre",
+ "tool.note": "Adicionar uma nota",
+ "tool.zoomToggle": "Ajustar à largura ou à página",
+ "recent": "PDFs na sua pasta"
}
diff --git a/assets/locales/pt/photos.json b/assets/locales/pt/photos.json
index f64045a..15083a3 100644
--- a/assets/locales/pt/photos.json
+++ b/assets/locales/pt/photos.json
@@ -35,5 +35,13 @@
"month.11": "dezembro",
"menu.file": "Arquivo",
"menu.print": "Imprimir…",
- "menu.slideshow": "Apresentação"
+ "menu.slideshow": "Apresentação",
+ "refresh": "Ler a pasta de novo",
+ "zoomIn": "Aproximar",
+ "zoomOut": "Afastar",
+ "rotateLeft": "Girar para a esquerda",
+ "rotateRight": "Girar para a direita",
+ "fullscreen": "Tela cheia",
+ "emptyTitle": "Não há fotos",
+ "thumbSize": "Tamanho das miniaturas"
}
diff --git a/assets/locales/pt/prefs.json b/assets/locales/pt/prefs.json
new file mode 100644
index 0000000..7b25d58
--- /dev/null
+++ b/assets/locales/pt/prefs.json
@@ -0,0 +1,229 @@
+{
+ "bt.audioHint": "Fones e alto-falantes também aparecem em Som quando estão conectados.",
+ "bt.battery": "Bateria {pct}%",
+ "bt.connect": "Conectar",
+ "bt.connected": "Conectado",
+ "bt.disconnect": "Desconectar",
+ "bt.err.authFailed": "Não foi possível parear: o código não conferiu ou o dispositivo recusou.",
+ "bt.err.blocked": "O Bluetooth está desligado por uma chave de hardware ou de software (rfkill).",
+ "bt.err.canceled": "O pareamento foi cancelado.",
+ "bt.err.failed": "O dispositivo não respondeu. Verifique se está ligado e por perto.",
+ "bt.err.noProfile": "Pareado, mas o dispositivo não oferece nenhum serviço que o LordOS possa conectar (áudio, entrada).",
+ "bt.forget": "Esquecer este dispositivo…",
+ "bt.more": "Mais",
+ "bt.myDevices": "Meus dispositivos",
+ "bt.nearby": "Dispositivos próximos",
+ "bt.nearbyHint": "Coloque o dispositivo em modo de pareamento para vê-lo aqui.",
+ "bt.nearbySearching": "Dispositivos próximos — procurando…",
+ "bt.noAdapter": "Este computador não tem adaptador Bluetooth.",
+ "bt.noAgent": "O LordOS não conseguiu se registrar para parear: dispositivos que pedem um código talvez não pareiem.",
+ "bt.noDevices": "Nenhum dispositivo",
+ "bt.noService": "O serviço de Bluetooth (bluez) não está rodando ou não está instalado.",
+ "bt.noneNearby": "Nenhum dispositivo encontrado",
+ "bt.notConnected": "Não conectado",
+ "bt.offHint": "Ative o Bluetooth para conectar fones, teclados, mouses e outros dispositivos.",
+ "bt.pairing": "Pareando…",
+ "bt.prompt.allow": "Permitir",
+ "bt.prompt.authorize.body": "“{name}” quer parear com este computador.",
+ "bt.prompt.authorize.placeholder": "",
+ "bt.prompt.authorize.title": "Pedido de pareamento Bluetooth",
+ "bt.prompt.cancel": "Cancelar",
+ "bt.prompt.confirm.body": "Confira se este código é o mesmo mostrado em “{name}”.",
+ "bt.prompt.confirm.placeholder": "",
+ "bt.prompt.confirm.title": "Parear com “{name}”?",
+ "bt.prompt.deny": "Recusar",
+ "bt.prompt.display-passkey.body": "Digite este código em “{name}” e pressione Enter nele.",
+ "bt.prompt.display-passkey.placeholder": "",
+ "bt.prompt.display-passkey.title": "Pareando com “{name}”",
+ "bt.prompt.display-pin.body": "Digite este PIN em “{name}”.",
+ "bt.prompt.display-pin.placeholder": "",
+ "bt.prompt.display-pin.title": "Pareando com “{name}”",
+ "bt.prompt.pair": "Parear",
+ "bt.prompt.passkey.body": "Digite o código de 6 dígitos mostrado em “{name}”.",
+ "bt.prompt.passkey.placeholder": "000000",
+ "bt.prompt.passkey.title": "Pareando com “{name}”",
+ "bt.prompt.pin.body": "Digite o PIN de “{name}” (costuma ser 0000 ou 1234; veja o manual).",
+ "bt.prompt.pin.placeholder": "PIN",
+ "bt.prompt.pin.title": "Pareando com “{name}”",
+ "bt.prompt.service.body": "“{name}” quer usar um serviço deste computador.",
+ "bt.prompt.service.placeholder": "",
+ "bt.prompt.service.title": "Permitir “{name}”?",
+ "bt.searching": "Procurando…",
+ "bt.signal": "Sinal {dbm} dBm",
+ "bt.title": "Bluetooth",
+ "bt.unblock": "Ativar",
+ "bt.visibleAs": "Visível como “{name}”.",
+ "bt.working": "Conectando…",
+ "defaults.cat.browser": "Navegador",
+ "defaults.cat.images": "Imagens",
+ "defaults.cat.mail": "E-mail",
+ "defaults.cat.music": "Música",
+ "defaults.cat.pdf": "Documentos PDF",
+ "defaults.cat.terminal": "Terminal",
+ "defaults.cat.text": "Editor de texto",
+ "defaults.cat.video": "Vídeo",
+ "defaults.choose": "Escolher…",
+ "defaults.failed": "Não foi possível salvar a escolha em ~/.config/mimeapps.list.",
+ "defaults.filesHint": "Arquivos abre os documentos com estes apps ao clicar duas vezes, e os mostra primeiro em “Abrir com”.",
+ "defaults.footer": "Compartilhado com os apps Linux (GNOME, KDE, xdg-open) por ~/.config/mimeapps.list.",
+ "defaults.none": "Nenhum app instalado abre estes arquivos",
+ "defaults.other": "{id}",
+ "defaults.tag": "{name} (padrão)",
+ "display.brightness": "Brilho",
+ "display.extend": "Estender",
+ "display.failed": "Não foi possível usar esse modo. O anterior continua.",
+ "display.hz": "{hz} Hz",
+ "display.inches": "{n} polegadas",
+ "display.keep": "Manter",
+ "display.keepBody": {
+ "one": "A tela volta à configuração anterior em {count} segundo.",
+ "other": "A tela volta à configuração anterior em {count} segundos."
+ },
+ "display.keepTitle": "Manter esta configuração de tela?",
+ "display.makeMain": "Usar como principal",
+ "display.mirror": "Espelhar",
+ "display.multiple": "Várias telas",
+ "display.multipleHint": "Por enquanto o LordOS usa uma tela de cada vez: estender a área de trabalho ou espelhá-la numa segunda tela ainda não é possível. Você pode escolher qual das telas conectadas usar.",
+ "display.native": "{w} × {h} (nativa)",
+ "display.noBacklight": "Esta tela não permite mudar o brilho (monitores externos e máquinas virtuais).",
+ "display.notInUse": "Sem uso",
+ "display.notOnMonitor": "Esta sessão não está no monitor agora (está sendo vista pela rede), então suas telas não podem ser alteradas. O Night Shift vale quando ela voltar.",
+ "display.onlyOne": "Só há uma tela conectada",
+ "display.refresh": "Taxa de atualização",
+ "display.resolution": "Resolução",
+ "display.revert": "Reverter",
+ "display.rotStandard": "Padrão",
+ "display.rotation": "Rotação",
+ "display.rotationHint": "Com a tela girada, a composição é feita pela CPU.",
+ "display.scale": "Escala",
+ "display.scaleHint": "Ainda não disponível: a interface é desenhada a 100% (veja docs/SETTINGS.md). Em telas grandes, escolha uma resolução menor.",
+ "display.unavailable": "Não há informação das telas.",
+ "display.useAs": "Usar como",
+ "night.custom": "Personalizado",
+ "night.customHint": "O Night Shift liga e desliga nestes horários todos os dias.",
+ "night.footer": "O Night Shift muda as cores da tela para tons mais quentes quando escurece.",
+ "night.from": "De",
+ "night.lessWarm": "Menos quente",
+ "night.manualOff": "Desligado até {time}",
+ "night.manualOn": "Ligado até {time}",
+ "night.moreWarm": "Mais quente",
+ "night.noSun": "O pôr do sol não é conhecido para este fuso horário: o Night Shift usa das 22:00 às 07:00.",
+ "night.now": "Ligar agora",
+ "night.off": "Desligado",
+ "night.offHint": "Use o interruptor abaixo para ligá-lo até amanhã.",
+ "night.schedule": "Programar",
+ "night.software": "Esta tela não tem tabela de cores (gamma LUT), então o Night Shift tinge a imagem por software.",
+ "night.sun": "Do pôr ao nascer do sol",
+ "night.sunHint": "Hoje: das {set} às {rise}, pelo seu fuso horário. Sua localização nunca é buscada na rede.",
+ "night.temp": "Temperatura da cor",
+ "night.title": "Night Shift",
+ "night.to": "às",
+ "notif.allow": "Permitir notificações",
+ "notif.allowPackage": "É a mesma permissão “Notificações” de Privacidade e segurança.",
+ "notif.apps": "Notificações dos apps",
+ "notif.appsFooter": "Os apps aparecem aqui depois de enviar a primeira notificação. Apps Linux (GTK, Qt) notificam pelo serviço padrão do freedesktop.",
+ "notif.byApp": "Por app",
+ "notif.dnd": "Não perturbe",
+ "notif.dndFooter": "Com “Não perturbe” as notificações são guardadas em silêncio e nenhum aviso aparece.",
+ "notif.dndOffHint": "As notificações aparecem",
+ "notif.dndOnHint": "Ativado: notificações em silêncio",
+ "notif.focus": "Foco",
+ "notif.from": "De",
+ "notif.grouping": "Agrupar notificações",
+ "notif.groupingHint": "Vários avisos do mesmo app aparecem como um só.",
+ "notif.lockScreen": "Mostrar na tela bloqueada",
+ "notif.lockScreenHint": "A tela bloqueada ainda não mostra notificações.",
+ "notif.noGrouping": "Desligado",
+ "notif.off": "Desativadas",
+ "notif.playSound": "Tocar som nas notificações",
+ "notif.schedule": "Ativar todos os dias",
+ "notif.scheduleHint": "Das {from} às {to}",
+ "notif.sound": "Som",
+ "notif.style.alert": "Alertas",
+ "notif.style.banner": "Faixas",
+ "notif.style.none": "Nenhum",
+ "notif.styleHint.alert": "Os alertas ficam na tela até você fechá-los.",
+ "notif.styleHint.banner": "As faixas somem sozinhas depois de alguns segundos.",
+ "notif.styleHint.none": "Guardadas em silêncio, sem aviso na tela.",
+ "notif.styleLabel": "Estilo",
+ "notif.test": "Testar",
+ "notif.testBody": "As notificações ficam assim.",
+ "notif.testButton": "Enviar uma notificação de teste",
+ "notif.testTitle": "Notificação de teste",
+ "notif.to": "às",
+ "power.act.hibernate": "Hibernar",
+ "power.act.ignore": "Não fazer nada",
+ "power.act.poweroff": "Desligar",
+ "power.act.suspend": "Repousar",
+ "power.battery": "Bateria",
+ "power.buttons": "Botão liga/desliga e tampa",
+ "power.buttonsHint": "Controlado pelo sistema (systemd-logind) para todos os usuários.",
+ "power.charging": "Carregando",
+ "power.chargingLeft": "Carregando — {time} para completar",
+ "power.criticalTitle": "Bateria quase no fim",
+ "power.cycles": "{n} ciclos",
+ "power.degraded": "O modo de desempenho está limitado agora (o computador está quente demais ou no colo).",
+ "power.healthNormal": "Saúde da bateria: {pct}% (normal)",
+ "power.healthService": "Saúde da bateria: {pct}% (revisão recomendada)",
+ "power.healthUnknown": "Saúde da bateria: desconhecida",
+ "power.hm": "{h} h {m} min",
+ "power.immediately": "Imediatamente",
+ "power.left": "Restam {time}",
+ "power.lid": "Ao fechar a tampa",
+ "power.lidAC": "Ao fechar a tampa no carregador",
+ "power.lock": "Pedir senha depois que a tela desligar",
+ "power.lowBattery": "Aviso de bateria fraca",
+ "power.lowBatteryHint": "Aos 20%, 10% e 5%.",
+ "power.lowBody": "Resta {pct}%. Conecte o carregador.",
+ "power.lowTitle": "Bateria fraca",
+ "power.m": "{m} min",
+ "power.menuPercent": "Mostrar a porcentagem na barra de menus",
+ "power.mode": "Modo de energia",
+ "power.modeGovernor": "Sem power-profiles-daemon: muda o regulador de frequência da CPU (agora: {gov}).",
+ "power.modeHint": "Pelo power-profiles-daemon.",
+ "power.needAdmin": "Só um administrador pode mudar isto.",
+ "power.never": "Nunca",
+ "power.noBattery": "Este computador funciona na tomada (sem bateria).",
+ "power.noProfiles": "Não disponível: instale o power-profiles-daemon, ou esta CPU não permite mudar a frequência.",
+ "power.off": "Desligar a tela quando inativa",
+ "power.offAC": "Desligar a tela no carregador quando inativa",
+ "power.offBattery": "Desligar a tela na bateria quando inativa",
+ "power.onACFull": "Conectado ao carregador",
+ "power.onBattery": "Na bateria",
+ "power.powerKey": "Ao pressionar o botão liga/desliga",
+ "power.profile.balanced": "Equilibrado",
+ "power.profile.performance": "Desempenho",
+ "power.profile.power-saver": "Economia",
+ "power.screenSleep": "Tela e repouso",
+ "power.screenSleepHint": "Contado a partir do último uso do teclado, do mouse ou do trackpad.",
+ "power.secs": "{s} segundos",
+ "power.sleep": "Repousar quando inativo",
+ "power.sleepAC": "Repousar no carregador quando inativo",
+ "power.sleepBattery": "Repousar na bateria quando inativo",
+ "time.auto": "Ajustar data e hora automaticamente",
+ "time.byRegion": "Como a região",
+ "time.change": "Alterar…",
+ "time.dateFull": "Dia e data",
+ "time.dateNone": "Só a hora",
+ "time.dateTime": "Data e hora",
+ "time.dateWeekday": "Dia da semana",
+ "time.format": "Formato",
+ "time.h12": "12 horas",
+ "time.h24": "24 horas",
+ "time.hour24": "Formato da hora",
+ "time.hour24Hint": "“Como a região” segue Idioma e região.",
+ "time.manual": "Manual",
+ "time.manualHint": "Ano-mês-dia e horas:minutos.",
+ "time.menuClock": "Relógio da barra de menus",
+ "time.needAdmin": "Só um administrador pode mudar a data, a hora e o fuso horário.",
+ "time.noNtp": "Nenhum serviço de hora (systemd-timesyncd) instalado.",
+ "time.preview": "Prévia",
+ "time.searchZone": "Buscar uma cidade",
+ "time.seconds": "Mostrar os segundos",
+ "time.set": "Ajustar",
+ "time.showDate": "Mostrar a data",
+ "time.synced": "Sincronizado com os servidores de hora da rede (systemd-timesyncd).",
+ "time.syncing": "Aguardando a primeira sincronização…",
+ "time.zone": "Fuso horário",
+ "time.zoneFooter": "Escolhido manualmente: o LordOS nunca busca sua localização na rede."
+}
diff --git a/assets/locales/pt/settings.json b/assets/locales/pt/settings.json
index e3946cc..65af66a 100644
--- a/assets/locales/pt/settings.json
+++ b/assets/locales/pt/settings.json
@@ -224,5 +224,17 @@
"dock.recentsHint": "Os três últimos apps usados que não estão fixados, depois de uma linha.",
"dock.taskbar": "Posição da barra de tarefas",
"dock.taskbarHint": "Tema Clássico. As janelas maximizadas não ficam embaixo da barra.",
- "dock.sidesHint": "Esquerda e direita são lados da tela: não mudam com um idioma da direita para a esquerda."
+ "dock.sidesHint": "Esquerda e direita são lados da tela: não mudam com um idioma da direita para a esquerda.",
+ "section.displays": "Telas",
+ "section.bluetooth": "Bluetooth",
+ "section.power": "Energia",
+ "section.notifications": "Notificações",
+ "section.datetime": "Data e hora",
+ "section.defaultapps": "Apps padrão",
+ "keywords.displays": "tela monitor resolução taxa hz rotação brilho night shift noite temperatura cor edid",
+ "keywords.bluetooth": "bluetooth parear fones alto-falante teclado mouse sem fio",
+ "keywords.power": "bateria energia perfil economia desempenho repouso suspender tampa botão liga desliga tela",
+ "keywords.notifications": "notificações avisos alertas faixas não perturbe foco som",
+ "keywords.datetime": "data hora relógio ntp fuso horário 24 horas 12 horas barra de menus segundos",
+ "keywords.defaultapps": "apps padrão navegador e-mail música vídeo imagens pdf editor de texto terminal abrir com"
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 370109a..143e894 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -51,6 +51,12 @@ que React Native pero sobre nuestro servidor gráfico.
| `server/src/media/`, `js_media.c`, `sdk/media.js`, `apps/{photos,player,screenshots,camera,recorder}` | **M9** | Medios: el ayudante encerrado `lord-media` (FFmpeg, libva) y las apps Fotos, Reproductor, Capturas, Cámara y Grabadora; nodo `media`, audio por memoria compartida con el stream de PipeWire en lord-server, ventanas protegidas en capturas, grabación y escritorio remoto (ver `MEDIOS.md`) |
| `server/src/netperm/`, `server/src/fw/`, `js_fw.c` | **M8** | Firewall por app: el servicio root `lord-netperm` aplica las reglas con BPF de cgroup en las sesiones; columna Regla del Monitor y Apps confiables / restringidas en Ajustes (ver `FIREWALL.md`) |
| `server/src/monitor/`, `js_monitor.c`, `apps/monitor/` | **M8** | Monitor: CPU, memoria, red, discos, procesos y conexiones por app con mapa; hilo propio solo con la app abierta, sock_diag y país por IP con una base local (ver `MONITOR.md`) |
+| `server/src/vault/`, `js_vault.c`, `sdk/vault.js`, `apps/passwords` | **M9** | Passwords and the system keyring: the sandboxed helper `lord-vault` (Monocypher: XChaCha20-Poly1305, Argon2id), own `.lvault` format, FIDO2/CTAP2 client, session keyring opened at login, Secret Service on D-Bus with own code (see `PASSWORDS.md`) |
+| `server/src/net/netd.c`, `remote/netsup.c` | **M9** | `lord-netd`: the network belongs to the system. A root service started and supervised by `lord-sessiond` at boot, serving the `net-*` actions for every session (see `RED.md`) |
+| `server/src/disk/`, `js_disk.c`, `sdk/disks.js`, `apps/disks` | **M9** | Disks: listing without root (sysfs, udev database, mountinfo), our own SMART reader (ATA PASS-THROUGH over SG_IO, NVMe health log), closed `disk-*` actions, bootable USB verified with SHA-256 (see `SYSTEM.md`) |
+| `server/src/backup/`, `js_backup.c`, `sdk/backup.js`, `apps/backup` | **M9** | Backups: hard-link snapshots in a lord-server thread (nice 19, idle I/O), hourly/daily/weekly retention, optional encryption with the vendored Monocypher; no root and no `admin.c` actions (see `SYSTEM.md`) |
+| `server/src/logs/`, `js_logs.c`, `sdk/logs.js`, `apps/logs` | **M9** | Logs: our own systemd journal reader (no libsystemd), LordOS logs, system logs for admins through a closed action, live follow with inotify (see `SYSTEM.md`) |
+| `server/src/ui/tzif.c`, `js_help.c`, `sdk/{notify,alarms,statusitems,help}.js`, `apps/{clock,help}` | **M9** | Clock (our own TZif reader, session alarms with the app closed), session notifications, menu-bar status items, Help (markdown articles in es/en/pt, welcome tour, Spotlight source) (see `SYSTEM.md`) |
| `server/src/ui/grab.c`, `cursor.c`, `sdk/windowshell.jsx` | **M8** | Ventanas: mover y agrandar en C (un evento por cuadro, sin JS), capa de la ventana que se mueve, bordes en los 4 lados y esquinas, cursores propios y `cursor-shape-v1` (ver `VENTANAS.md`) |
### Flujo de un frame
@@ -79,6 +85,8 @@ Solo se permite, además del kernel y la libc:
| FFmpeg (`libavcodec`, `libavformat`, `libavutil`, `libswscale`, `libswresample`) y `libva` (+ `libva-drm`) | Decodificar y codificar video, audio e imágenes; VA-API para decodificar por hardware (M9, aprobados por el usuario). **Solo los enlaza `lord-media`**, el ayudante encerrado; el reproductor, la sincronización y la interfaz son propios. Nunca `lord-server` (`MEDIOS.md`) | sistema |
| Poppler (`libpoppler-glib`) y libarchive | PDF y comprimidos (M9, aprobados por el usuario). **Solo los enlaza `lord-doc`**, el ayudante encerrado; con Poppler vienen cairo, FreeType y fontconfig, que `lord-doc` también usa para las muestras de fuentes y para armar PDF. Nunca `lord-server` (`DOCUMENTOS.md`) | sistema |
| `clang` (solo al compilar) | los programas BPF de `lord-netperm` (`np.bpf.c`, `clang -target bpf`); van adentro del binario. Sin clang (`BPF=0`) el servicio corre sin BPF. No se usa libbpf ni bcc | máquina que compila |
+| Monocypher 4.0.2 | XChaCha20-Poly1305, Argon2id/Argon2d, BLAKE2b, ChaCha20 for the Passwords vault and the KeePass importer (approved by the user; CC0/BSD-2, one C file). **Only `lord-vault` links it**; its official test vectors run in `make test` (`PASSWORDS.md`) | vendorizado |
+| EFF word list, 10k common passwords | passphrase generator and the offline "breached" check (CC BY 3.0 US / MIT), embedded in `lord-vault` | `third_party/wordlists` |
| Inter, JetBrains Mono | fuentes de la interfaz y de la terminal (OFL) | `assets/fonts` |
React (`react`, `react-reconciler`) es dependencia **del tema**, no del sistema: se empaqueta
@@ -88,6 +96,9 @@ usa en la máquina de desarrollo.
Desde M8 hay dos programas, y desde M9 dos ayudantes:
+- **`lord-netd`** (M9, root): the system network, started and supervised by `lord-sessiond` at boot;
+ only the `net-*` actions of `admin.c`. libc only. See `RED.md`.
+
- **`lord-sessiond`** (root, `lordos.service`): la pantalla de ingreso, la lista de sesiones, el
monitor y el escritorio remoto. Ver `SESIONES.md` y `REMOTO.md`.
- **`lord-server`**: una sesión por usuario, siempre sin monitor propio (`--headless`); el
@@ -106,6 +117,13 @@ Desde M8 hay dos programas, y desde M9 dos ayudantes:
cuadros vuelven por memoria compartida sellada y el audio va a un anillo cuyo stream de
PipeWire es de `lord-server`. Ver `MEDIOS.md`.
+- **`lord-vault`** (M9): the Passwords and keyring helper. Same rules as `lord-doc`/`lord-media`
+ (fixed path, no arguments, minimal environment, `sandbox_apply_helper`: no network, no new
+ sockets, no exec), but it lives for the whole session: it holds the decrypted vaults in an
+ `mlock`/`MADV_DONTDUMP` arena, receives the vault folder, picked files, the FIDO2 hidraw device
+ and the already-connected session D-Bus socket as fds, and serves the Secret Service. See
+ `PASSWORDS.md`.
+
`lord-server` sigue pudiendo correr solo, con DRM y evdev propios, para el desarrollo.
Datos que vienen con LordOS para el Monitor (`MONITOR.md`): `assets/monitor/geoip-country.mmdb.xz`
@@ -133,6 +151,8 @@ Desde M7, lo que LordOS hace con código propio y lo que delega en un programa d
`/run/cups/cups.sock`; administra la cola y los controladores, ver `IMPRESION.md`).
- **Programas de Debian** (con ruta fija, nunca enlazados, lanzados por el ayudante `admin.c`):
- `dpkg`: desempaquetar y configurar;
+ - `mkfs.vfat`, `mkfs.exfat`, `mkfs.ext4`, `mkfs.ntfs` (optional) and their label tools: formatting
+ and renaming in Disks (M9, `disk-*` actions);
- `wpa_supplicant`: Wi-Fi;
- `openvpn`;
- `resolvectl` y `networkctl`.
diff --git a/docs/DESIGN.md b/docs/DESIGN.md
new file mode 100644
index 0000000..c5a3655
--- /dev/null
+++ b/docs/DESIGN.md
@@ -0,0 +1,101 @@
+# Design guide for LordOS apps
+
+LordOS apps follow the macOS Human Interface Guidelines: generous whitespace, a small type scale,
+consistent control heights and one accent-colored action per view. This guide is the reference
+for every polish pass, so all apps share the same spacing, type and controls. The shared building
+blocks are in `sdk/controls.jsx` and `sdk/components.jsx`, and the tokens below are exported from
+the SDK as `spacing`, `typeScale` and `controlSize`.
+
+The first pass (Calculator, Text Editor, Notes, Photos, PDF Viewer and Fonts) is documented with
+before/after screenshots in [`docs/polish/`](polish/).
+
+## Spacing: an 8 px grid
+
+| Token | px | Use |
+|---|---|---|
+| `xs` | 4 | tight spots: between a glyph and its label, between grouped toolbar buttons |
+| `s` | 8 | between controls in a row, between rows of a list, toolbar gap |
+| `m` | 12 | toolbar side insets, inside a grouped box, between a label and its control |
+| `l` | 16 | padding of panels and dialogs that sit inside a window |
+| `xl` | 20 | **window content inset** (nothing touches the window edge), dialog padding |
+| `xxl` | 24 | between groups and sections |
+
+Rules:
+
+- The content of a window starts 20 px from its edges. Lists in a sidebar start 10 px in, with
+ 8–10 px of padding inside each row.
+- Separate groups by 20–24 px and controls by 8–12 px. Never place two controls touching.
+- Use hairlines (1 px, `separator`) between a sidebar and its content, under a toolbar and above a
+ status bar. Don't use thick borders.
+
+## Type scale
+
+Inter, weights 400 / 500 / 600 only (700 only for very short emphasis).
+
+| Token | px | Weight | Use |
+|---|---|---|---|
+| `caption` | 11 | 400–600 | secondary labels, section captions in sidebars, status bars, counts |
+| `callout` | 12 | 400 | hints, secondary text in rows |
+| `body` | 13 | 400–500 | default text, list rows, buttons, menus |
+| `headline` | 15 | 600 | dialog titles, month headers, empty-state titles |
+| `title` | 17 | 600 | the title of a pane when space is short |
+| `largeTitle` | 22 | 600 | the title of a library or detail view (Photos, Fonts) |
+
+Secondary text uses `textDim`. Avoid uppercase captions: macOS uses sentence case ("Contents",
+not "CONTENTS").
+
+## Controls
+
+| Control | Height | Radius | Notes |
+|---|---|---|---|
+| `Button` | 28 (regular), 22 (`small`) | 7 / 6 | `primary` = the one accent action of the view; `plain` = borderless; `destructive` |
+| `TextInput` | 28 (13 px text) | 7 | grows with `size` |
+| `SearchField` | 28 | 7 | magnifier at the leading edge, clear button at the trailing edge |
+| `Segmented` | 28 (22 `small`) | 8 | `appearance="neutral"` for view switchers (Read/Edit, Sample/Characters/Info); `fill` to share the width |
+| `ToolbarButton` | 28 (22 `small`) | 6 | icon-only items **must** have a `title` (tooltip); `active` = toggled on |
+| `ToolbarGroup` | 32 | 8 | buttons that belong together: zoom −/value/+, markup tools |
+| `Toolbar` | 44 | — | 12 px side insets, 8 px gap, hairline at the bottom |
+| `SidebarItem` | 28 | 6 | source list row; string `icon` is drawn in the accent color; optional `detail` |
+| `MenuButton` | 28 | 8 | "⋯" or "⊕" button that opens a small menu (checked, disabled and destructive items) |
+
+Icons are monochrome Unicode glyphs from the fallback fonts (Inter, DejaVu Sans, Noto Sans
+Symbols 1/2), not color emoji. Verified on the VM:
+`✎ ⧉ ⊕ ⋯ ◫ ⛶ ⤢ ⟲ ⟳ ↻ ⎙ ⌕ ✕ ◐ ▬ ▤ ▦ ▶ ⓘ ☺ ‹ ›`. Color emoji (🗑 📎 🖼 🗨) and some
+symbols (🗀) don't render as icons: draw a small shape instead (see `FolderGlyph` in Photos).
+
+## Layout patterns
+
+- **Sidebar (source list):** 200–240 px, `sidebarBg`, a hairline on its trailing edge,
+ `SectionTitle` captions (11 px, 600, `textDim`) and `SidebarItem` rows. A search field goes at
+ the top of the sidebar when the list is what you search.
+- **Toolbar:** icon-only buttons with tooltips where macOS does that. Show a text label only for
+ the main mode switch or the back button. Push trailing items to the end with `ToolbarSpacer`. In
+ narrow windows, hide items that are also in the app menus (print, invert, rotate), and move
+ secondary actions into a `MenuButton` ("⋯"), so the toolbar never wraps to a second row.
+- **Grouped form ("inset"):** `GroupBox` with `FormRow` children: a rounded box (radius 10) with
+ hairlines between rows. Rows are at least 32–36 px. In a key/value list, put the labels in a
+ right-aligned column (`labelWidth`) and the values leading-aligned.
+- **Empty state:** `EmptyState` with an icon, a short title (15/600) and one hint line (12,
+ `textDim`), centered. At most one primary button.
+- **Dialogs and sheets:** 20 px padding, title 15/600, body 13 with `lineHeight: 1.4`, buttons at
+ the end of the last row with 12 px above them. The default action is `primary`.
+- **Hierarchy:** one primary (accent) action per view. Everything else is plain or neutral.
+
+## Robustness checklist
+
+Check every pass on the VM with:
+
+- **light and dark** mode;
+- **RTL** (Arabic test pack `docs/packs/lordos-lang-ar.json`). The engine mirrors rows. Content
+ that is itself left to right keeps `direction: 'ltr'` (calculator keypad, code, sliders, page
+ geometry), and user text follows its own direction with `textDirection(text)` (a Spanish note in
+ an Arabic UI still reads left to right);
+- the **minimum window size** (`minSize` in the manifest) and a **large/maximized** window;
+- no overlapping or clipped controls, and no toolbar that wraps. Text that can be long uses
+ `whiteSpace: 'nowrap'` and `overflow: 'hidden'` inside a `flex: 1` box.
+
+## Pending (engine)
+
+- The text engine has no ellipsis (`…`) for clipped text: long names are cut at the edge.
+- No per-side borders: hairlines are drawn as 1 px absolute `View`s.
+- No vector icon set: icons are font glyphs (see above).
diff --git a/docs/FIREWALL.md b/docs/FIREWALL.md
index 122fb17..86cb191 100644
--- a/docs/FIREWALL.md
+++ b/docs/FIREWALL.md
@@ -587,14 +587,13 @@ y `/dev/tcp`:
### Límites conocidos
-- **Las scopes son del usuario.** El subárbol de la sesión está delegado a él (`PRIVACIDAD.md`).
- Una app Linux sin caja de arena que corre como el usuario puede mudarse a otra scope, a `server`
- o a una cgroup nueva de la sesión. En una cgroup que no es una scope conocida, no se aplica
- nada. Pasa lo mismo con `firewall.json` y con `permisos.json`. Las `.lpk` no pueden, por
- Landlock.
-
- Para cerrarlo, el próximo paso: que `lord-sessiond` cree las scopes y deje `cgroup.procs` de
- root.
+- **App scopes are root's now** (was: «Las scopes son del usuario»). `lord-sessiond` creates the
+ scopes and places each process; every `cgroup.procs` of the session subtree is root-owned, so a
+ Linux app can no longer move itself to another scope, to `server` or to a new cgroup (tested on
+ VM 122, see `PRIVACIDAD.md`, «Root-owned app scopes»). The remaining hole: `systemd-run --user
+ --scope` asks PID 1 (`AttachProcessesToUnit`), which moves the process as root into
+ `user@<uid>.service`, outside `lordos.service`, where no rule applies. `firewall.json` and
+ `permisos.json` are still writable by an unsandboxed app running as the user.
- **Una scope recién creada** se registra con inotify en microsegundos, antes de que el programa
termine de arrancar (exec + bibliotecas). Si una conexión llegara antes, pasaría con las reglas
por omisión.
diff --git a/docs/ISO.md b/docs/ISO.md
index 7b43a90..a660757 100644
--- a/docs/ISO.md
+++ b/docs/ISO.md
@@ -177,8 +177,8 @@ Qué valida `install-run` del lado root, sin confiar en la interfaz:
- El usuario tiene linger, así su PipeWire arranca con el sistema.
- El usuario de sistema `lordos-greeter`, el de la pantalla de ingreso, se crea al armar el
ISO (lord-sessiond también lo crea si falta).
-- **Red:** el DHCP propio de LordOS, en `lord-netd` desde el arranque (`RED.md`). No trae
- ifupdown, systemd-networkd ni NetworkManager.
+- **Network:** LordOS's own DHCP, in `lord-netd` from boot (`RED.md`). No ifupdown,
+ systemd-networkd or NetworkManager.
- **Sonido:** PipeWire, pipewire-pulse, WirePlumber, alsa-ucm-conf y el firmware SOF (audio de
las notebooks Intel).
- **GPU:** Mesa (radeonsi, iris, nouveau, llvmpipe y RADV/ANV/NVK para Vulkan), `libgbm1`,
@@ -364,11 +364,11 @@ tiene una instalación vieja. Arranca primero del CD.
aunque ifupdown no esté instalado. Convendría que también mire que exista `/sbin/ifup`. El ISO
hoy lo esquiva en `lordos-live-prep`.
- Las herramientas de diagnóstico de audio (`pactl`) no vienen; `wpctl status` sí.
-- ~~**Red antes del primer ingreso**~~ y ~~**carpetas del usuario instalado**~~: resueltos en M9.
- La red es del sistema (`lord-netd`, lanzado por `lord-sessiond` al arrancar; ver `RED.md`) y el
- instalador crea Escritorio, Documentos, Descargas, Música, Imágenes y Videos en el idioma
- elegido, con `~/.config/user-dirs.dirs` (`server/src/users/homedirs.c`, la misma lista que
- Ajustes → Usuarios y `lordos-live-prep`). Falta repetirlo con un ISO nuevo instalado al disco.
+- ~~**Network before the first login**~~ and ~~**folders of the installed user**~~: fixed in M9.
+ The network belongs to the system (`lord-netd`, started by `lord-sessiond` at boot; see `RED.md`)
+ and the installer creates Escritorio, Documentos, Descargas, Música, Imágenes and Videos in the
+ chosen language, with `~/.config/user-dirs.dirs` (`server/src/users/homedirs.c`, the same list as
+ Settings → Users and `lordos-live-prep`). Still to repeat with a new ISO installed to disk.
- **Primer movimiento del mouse después de desbloquear:** en la VM 117, el primer evento
absoluto por QMP después de ❖L/Enter dejó el cursor arriba (y≈8). Los siguientes funcionaron
bien. No se investigó.
diff --git a/docs/PASSWORDS.md b/docs/PASSWORDS.md
new file mode 100644
index 0000000..bc186ff
--- /dev/null
+++ b/docs/PASSWORDS.md
@@ -0,0 +1,393 @@
+# Passwords and the system keyring (M9)
+
+**Contraseñas** ("Passwords" in English, "Senhas" in Portuguese) is the LordOS password manager.
+The same machinery is also the **system keyring**: native apps keep their secrets there through
+`lord.keyring` / the SDK `keyring`, and Linux apps (Chromium, Firefox, `secret-tool`, anything
+using libsecret) through our own implementation of the freedesktop **Secret Service** D-Bus API.
+No gnome-keyring, kwallet, libsecret, libdbus or sd-bus is used by LordOS.
+
+## Screenshots (VM 116, real `lord-sessiond` session, user `pwtest`)
+
+| | |
+|---|---|
+| ![Create the vault](m9-contrasenas-crear.png) | ![Unlock with the master password](m9-contrasenas-desbloquear.png) |
+| Creating the vault: choose how it unlocks (password, FIDO2 key, key file, password + key file) | Locked vault: one tab per unlock method present in the file |
+| ![Internet item with TOTP](m9-contrasenas-internet.png) | ![2FA codes](m9-contrasenas-2fa.png) |
+| An *Internet* item: website, user, hidden password (reveal/copy), live 2FA code with countdown, notes, reminder "change every 90 days" | All 2FA codes with their countdown; the TOTP secret never leaves `lord-vault` |
+| ![Wi-Fi QR](m9-contrasenas-wifi-qr.png) | ![Identity document with photo](m9-contrasenas-identidad.png) |
+| Wi-Fi: the QR code to join from a phone (`WIFI:T:WPA;S:…;P:…;;`) is generated inside `lord-vault` | *Identity and documents*: encrypted photo attachment previewed (decoded and downscaled inside `lord-vault`) |
+| ![Security report](m9-contrasenas-seguridad.png) | ![Generator](m9-contrasenas-generador.png) |
+| Security report: weak, reused, old and breached (offline) passwords | Password generator |
+| ![Passphrase generator](m9-contrasenas-generador-frase.png) | ![Import KeePass](m9-contrasenas-importar.png) |
+| Passphrases from the EFF word list (12.9 bits per word) | Importing a real KeePass KDBX 4 file with our own reader: 4 entries, 3 folders become categories |
+| ![Unlock with a USB key file](m9-contrasenas-desbloquear-usb.png) | ![Unlock with a FIDO2 key](m9-contrasenas-desbloquear-fido.png) |
+| Unlocking with a key file on a USB stick (`/media/pwtest/PENDRIVE`) | Unlocking with a FIDO2 security key (here the software authenticator, see "Testing") |
+| ![Vault settings](m9-contrasenas-ajustes.png) | ![USB permission prompt](m9-contrasenas-fido-permiso.png) |
+| Unlock methods: password, recovery key, FIDO2 key and key file side by side; each wraps the same vault key | Using the security key goes through the system permission prompt (TCC-style `usb` permission); only `lord-server` opens `/dev/hidrawN` |
+| ![Chromium offers to save](m9-contrasenas-chromium-guardar.png) | ![Chromium Safe Storage in the session keyring](m9-contrasenas-llavero-chromium.png) |
+| Chromium (Wayland, `--password-store=gnome-libsecret`) saving a password | …its "Chromium Safe Storage" key lands in our Secret Service, visible in *Session keyring* |
+| ![Chromium autofills after a restart](m9-contrasenas-chromium-autocompletar.png) | ![Protected window in a capture](m9-contrasenas-captura-protegida.png) |
+| After restarting Chromium it decrypts and autofills the saved login: the key came back from our service | The Passwords window comes out black in LordOS screenshots, recordings and the remote desktop |
+
+Main window with categories (tree) and tags: see `m9-contrasenas-categorias.png`.
+
+## Architecture: where the secrets live
+
+```
+ Passwords app (React, apps/passwords) Settings → Network, Mail, … (sdk keyring)
+ │ lord.vault.request(json, files) │
+ ▼ ▼
+ lord-server (src/vault/vclient.c, src/ui/js_vault.c)
+ - spawns lord-vault (fixed path, no args, minimal env), one per session
+ - opens files the user picked (validated like lord.fs) and passes only fds
+ - opens /dev/hidrawN for FIDO2 after the `usb` permission, passes the fd
+ - connects the session D-Bus socket and passes it (Secret Service)
+ - screen lock / user switch → "lock-all"; login → session password (RP_KEYRING)
+ │ SOCK_SEQPACKET, JSON messages, SCM_RIGHTS (src/vault/vwire.c)
+ ▼
+ lord-vault (src/vault/vault.c, keyring.c, …) — sandbox_apply_helper:
+ no network, no new sockets, no exec, threads only, Landlock: only the vault folder (fd)
+ - XChaCha20-Poly1305 + Argon2id (Monocypher), the .lvault format
+ - decrypted vaults in the secret arena (mlock, MADV_DONTDUMP, wiped on lock)
+ - search, security report, TOTP, generator, QR encode/decode, importers, KDBX reader
+ - CTAP2 client over the hidraw fd (thread waits for the touch)
+ - Secret Service on the inherited bus socket (own D-Bus code)
+```
+
+**Why this split.** Everything that touches plaintext vault data, parses untrusted files (KDBX,
+CSV, JSON, images with QR codes) or talks to the security key runs in one small helper that cannot
+open the network, sockets or paths, the same model as `lord-doc` and `lord-media`
+(`docs/PRIVACIDAD.md`, "Ayudantes"). `lord-server` (the compositor) only relays: it never holds
+the vault key and never parses the vault. The UI gets just what it shows:
+
+- the list view gets titles, user names, URLs, tags and flags, **never** a secret;
+- an open item comes with hidden fields as `{"has": true}`; a value travels only when the user
+ clicks reveal, copy or edits it;
+- TOTP secrets never leave `lord-vault`: the UI receives the 6–8 digit code and the seconds left;
+- the Wi-Fi QR is built from the item inside `lord-vault`; the UI receives a bitmap.
+
+**Known limitation: the UI is not a separate sandboxed process yet.** Like every other built-in app
+(Notes, Settings, Files…), the Passwords UI runs inside the session's JavaScript context, so a
+value the user reveals sits for a moment in `lord-server`'s QuickJS heap (garbage collected, not
+wiped). Only `.lpk` packages run as isolated processes today (`lord-server --app <id>`). The
+protocol is ready for it: `vc_attach_app()` gives an isolated app its own channel to `lord-vault`
+(role `app`), so moving the UI to app mode means (1) shipping it as a system package, (2) using the
+powerbox for files and a broker op for the FIDO2 device, and (3) polling the vault channel in
+`appclient.c`. That is the next step; it was not done in this milestone.
+
+## The vault format (`.lvault`, version 1)
+
+One file, portable: copy it, back it up, carry it on a USB stick. The default vault is
+`~/.local/share/lordos/vault/contrasenas.lvault`; the session keyring is `login.lvault` next to
+it. Both folders are on the `lord.fs` deny list (`fsops_protected`): JavaScript cannot overwrite
+or delete them; only `lord-vault` writes there.
+
+```
+header magic "LORDVLT\x1a" | u16 version=1 | u16 minor | u32 header_len | vault_id[16]
+ | u64 created | u64 saved | u32 save_counter | u16 flags | u16 nslots
+ | slots…: u8 type | u8 kdf | u16 len | id[8] | u64 created | label | kdf params | salt[16]
+ | (FIDO2: credential id, hmac salt[32], aaguid[16], pin flag)
+ | nonce[24] | wrapped_vault_key[32] | mac[16]
+body nonce[24] | u64 len | XChaCha20-Poly1305(JSON content) | mac[16] AD = whole header
+attach. u32 count | per item: id[16] | nonce[24] | u64 len | ciphertext | mac[16]
+trailer "LVLTEND\0" | u64 total_len
+```
+
+- **Vault key (VK):** 32 random bytes. It is never derived from the password. Each *slot* wraps VK
+ with XChaCha20-Poly1305 under a key derived from one way of unlocking; the wrap's associated data
+ binds the slot to the vault id and to its own parameters.
+- **Key derivation per slot:**
+
+ | Slot | KEK |
+ |---|---|
+ | password | Argon2id(password, salt, m, t, p=1) |
+ | key file | BLAKE2b(keyed by BLAKE2b(file), "keyfile" ‖ salt) |
+ | password + key file | BLAKE2b(keyed by Argon2id(password), "passkey" ‖ BLAKE2b(file)) |
+ | FIDO2 | BLAKE2b(keyed by hmac-secret output, "fido2" ‖ salt) |
+ | recovery key | BLAKE2b(keyed by the 200-bit recovery code, "recovery" ‖ salt) |
+ | session (keyring) | Argon2id(login password, salt, …) |
+
+- **Body:** subkey `BLAKE2b(VK, "body")`; associated data = the whole header, so changing a slot,
+ a KDF parameter or the counter is detected when the body fails to authenticate.
+- **Attachments** (licence files, document photos, certificates) are sealed separately with
+ `BLAKE2b(VK, "attachment")`, AD = vault id ‖ attachment id; their nonce and MAC are also recorded
+ in the (authenticated) body, so swapping or removing an attachment is detected. Unlocking decrypts
+ only the body; attachments are decrypted on demand and never all at once.
+- **Content (JSON):** `{"v":1,"meta":{…},"cats":[…],"tags":[…],"entries":[{id, cat, title, notes,
+ fav, arch, trash, created, modified, pwch, rotate, tags, f:[{k,t,l,v}], att:[…], hist:[…], x}]}`.
+ Field types: text, hidden, url, date, number, file, totp, email, multiline, pin, bool. The
+ history keeps the last 20 versions of an item's fields (hidden values included, shown only on
+ explicit reveal).
+- **Atomic save with backup:** write `.name.tmp-PID` (O_EXCL) and `fsync`; hard-link the current
+ file to a temporary name and `renameat` it over `name.bak` (so `.bak` is always the previous
+ version, replaced atomically); `renameat` the new file over `name`; `fsync` the folder. At every
+ moment there is a complete vault on disk. This works inside Landlock because everything happens
+ within the one folder `lord-vault` received as an fd.
+- **Argon2id cost** is stored per slot and tuned per machine (`vf_calibrate`): it measures one
+ pass at 64 MiB, then picks memory (19–256 MiB, at most 1/8 of RAM) and passes for ~0.7 s.
+ "Settings → Preferences → Measure" shows what this machine would use; changing the password
+ re-measures.
+- **Recovery key:** 40 Crockford base32 characters (8 groups of 5, 200 bits). It is shown once at
+ creation, can be printed (system print dialog) or saved as a text file, and can be regenerated.
+ Typing is forgiving: case, dashes, O/0 and I/L/1 are normalised.
+
+## Unlocking
+
+1. **Master password** (Argon2id).
+2. **FIDO2 security key** (YubiKey, SoloKey, Nitrokey, …) with the CTAP2 `hmac-secret` extension:
+ own client (`src/vault/ctap2.c`: CTAPHID framing, CBOR, getInfo, clientPIN protocol 1 with our
+ own P-256 ECDH, makeCredential and getAssertion with hmac-secret). Enrolling asks for two
+ touches (create the credential, then derive). If the key has a PIN, the slot remembers that a
+ PIN was used (CTAP 2.1 keys return different secrets with and without user verification).
+3. **Key file**: 64 random bytes written to a path the user picks, typically a USB stick under
+ `/media/$USER`; any existing file of at least 32 bytes also works (hashed with BLAKE2b).
+4. **Password + key file** (two factors). Adding it removes the password-only slot (the UI warns).
+
+Several methods can coexist; at least one besides the recovery key must remain.
+
+**Device access.** `lord.vault.fidoAttach(app)` only works when the app holds the `usb` permission
+(system prompt, stored in `permisos.json`, checked in C). `lord-server` finds FIDO devices by the
+HID report descriptor (usage page 0xF1D0, `src/vault/fidodev.c`), opens `/dev/hidrawN` and passes
+the fd to `lord-vault`. Neither the app nor its JavaScript ever sees the device.
+FIDO hidraw nodes need a udev rule because LordOS sessions are not logind seat sessions
+(`TAG+="uaccess"` does not apply):
+
+```
+# /usr/lib/udev/rules.d/71-lordos-fido.rules
+ACTION=="remove", GOTO="lordos_fido_end"
+SUBSYSTEM=="hidraw", ENV{ID_FIDO_TOKEN}=="1", GROUP="plugdev", MODE="0660"
+LABEL="lordos_fido_end"
+```
+
+(`ID_FIDO_TOKEN` comes from systemd's `60-fido-id.rules`; the user must be in `plugdev`.)
+
+**Auto-lock.** The vault locks after the idle timeout (default 5 min, Settings → Preferences),
+when the screen is locked (❖L, ❖Ctrl+Q: `mirror_session("lock")` → `vc_lock_all`) and when
+switching users. The session keyring stays open until logout, like the macOS login keychain.
+Locking frees the model block by block; every arena block is wiped on free.
+
+## Memory protection (`src/vault/smem.c`)
+
+- Decrypted data lives in our own arena: anonymous `mmap` regions with `mlock` (as far as
+ `RLIMIT_MEMLOCK` allows: 8 MiB by default on Debian), `MADV_DONTDUMP` and `MADV_WIPEONFORK`.
+ Small blocks come from size classes (O(1)), large ones get their own mapping.
+- `sm_free` wipes before releasing; locking a vault frees its whole model.
+- The process is not dumpable (`PR_SET_DUMPABLE 0`, which also blocks ptrace from the same user)
+ and `RLIMIT_CORE` is 0.
+- The request JSON is received straight into the arena (`vw_feed` with the arena allocator) and
+ the in-arena JSON reader (`vjson.c`) tokenises in place; stb_image (for QR images and photo
+ previews) and the KDBX gzip inflate also allocate from the arena (`vstb.c`).
+- Argon2's work area (64–256 MiB) cannot be locked under the default limit; it is `DONTDUMP`
+ and wiped after each derivation. The test VM has no swap.
+
+## Clipboard
+
+- Copying a password, PIN, card number or 2FA code calls `clipboard.set(value, { secure: true })`:
+ it never enters LordOS' clipboard history (Spotlight / ❖V panel).
+- Wayland clients now see the extra MIME type `x-kde-passwordManagerHint` (value `secret`) on a
+ sensitive LordOS clipboard, the KDE/GNOME convention clipboard managers honour
+ (`src/wl/wl.c`). The bytes handed to Wayland clients are wiped after sending.
+- The app clears the clipboard after 30 s (configurable: 15/30/60/120 s) if it still holds the
+ same value.
+
+## The session keyring (`login.lvault`)
+
+A separate vault, like the macOS *login* keychain:
+
+1. `lord-sessiond` (root) verifies the password typed at the login screen (`crypt_r` against
+ `/etc/shadow`, unchanged).
+2. Right after, the login worker sends it once over the session socket as `RP_KEYRING` (accepted
+ only from a root peer, `src/remote/mirror.c`) and wipes its copy.
+3. `lord-server` forwards it to `lord-vault` (`session-password` on the control channel) and wipes
+ its buffers; `lord-vault` opens `login.lvault` (a `session` slot, Argon2id tuned to ~0.4 s) or
+ creates it on first login.
+4. If the account password was changed outside LordOS, the slot no longer opens: `lord-vault` emits
+ `keyring-mismatch` (the UI can ask for the old password; re-wrapping is a `password-change` on
+ `v:"login"`).
+
+When the session starts without a password (autologin, remote desktop for now), the keyring stays
+locked; the first app that needs it triggers a system prompt (`<KeyringPrompt />`, mounted by
+`startShell`) asking for the login password.
+
+### `lord.keyring` / SDK `keyring` (native apps)
+
+```js
+import { keyring, AutofillButton } from '@lordos/sdk';
+await keyring.set('mail', { service: 'imap.example.com', account: 'ana', secret: 'xxxx', label: 'Mail' });
+const item = await keyring.get('mail', { service: 'imap.example.com', account: 'ana' }); // { secret, … } | null
+await keyring.remove('mail', { service, account });
+await keyring.list('mail'); // without secrets
+```
+
+- Items are entries of `login.lvault` with `x.kr = {owner, service, account, shared}`.
+- An app sees only its own items. Asking for another app's item returns `not-shared` plus the item
+ id, so the system can ask the user; `keyring.share(id, app)` records the user's decision
+ (`shared`). Sharing is an admin operation (the Passwords app or a system prompt), never the
+ asking app itself.
+- **Trust boundary:** built-in apps run in the shell's JavaScript context, so for them the owner
+ string is passed by trusted system code, not enforced by a process boundary. For isolated `.lpk`
+ apps the owner must be set by `lord-server` from the broker (the app id it already verifies);
+ wiring that broker op is part of moving to app mode (see above).
+- **Settings → Network** now stores Wi-Fi passwords (`wifi:<ssid>`) and VPN credentials
+ (`vpn:<name>`) in the keyring when you join or save, and offers them back with the 🔑 button.
+ The root-owned copy that `wpa_supplicant`/the VPN daemons need to connect at boot is still
+ written by the closed `admin.c` actions (as NetworkManager does with system connections).
+
+### Autofill in native apps
+
+`<AutofillButton app service|url|ssid onFill />` is a small 🔑 button next to a login field. It
+lists what the app saved in the keyring for that service plus matching Passwords items (by host,
+or by SSID for Wi-Fi) while the vault is unlocked; the secret leaves `lord-vault` only when the
+user picks one. Used in Settings → Network (Wi-Fi password, VPN credentials).
+
+### Secret Service (`org.freedesktop.secrets`)
+
+Our own minimal D-Bus code (`src/vault/dbus.c`, `secretsvc.c`). Before writing it we checked: no
+LordOS binary links libdbus or libsystemd (sd-bus), so adding either would have been a new
+dependency; the protocol subset needed (SASL EXTERNAL, Hello, RequestName, method calls and
+returns, signals, properties) is small. `lord-server` connects the session bus socket
+(`DBUS_SESSION_BUS_ADDRESS` or `$XDG_RUNTIME_DIR/bus`) and passes it already connected; the
+sandboxed `lord-vault` authenticates and serves on it.
+
+- Objects: `/org/freedesktop/secrets` (Service), `/org/freedesktop/secrets/collection/login`
+ (alias `default`), items below it, sessions and prompts.
+- Session algorithms: `plain` and `dh-ietf1024-sha256-aes128-cbc-pkcs7` (1024-bit MODP group 2,
+ HKDF-SHA256, AES-128-CBC). `secret-tool` (libsecret 0.21.7) negotiates the DH one.
+- Items are entries of `login.lvault` with `x.ss = {attrs, ctype}`; non-UTF-8 secrets are stored
+ base64.
+- If another service already owns the name (gnome-keyring, kwallet), LordOS does not take it.
+- **Access control is the freedesktop one:** like gnome-keyring, any app of the session that can
+ reach the bus can read the unlocked collection. Isolated `.lpk` apps cannot open the bus socket.
+- **Chromium:** current Chromium releases keep their saved logins in their own database and store
+ only the encryption key ("Chromium Safe Storage", schema `chrome_libsecret_os_crypt_password_v2`)
+ in the Secret Service. We verified the whole round trip: save a login, restart Chromium, it
+ fetches the key from our service and autofills. LordOS does not set `XDG_CURRENT_DESKTOP` to
+ GNOME, so Chromium needs `--password-store=gnome-libsecret` to pick libsecret; without it, it
+ uses its "basic" store.
+- Not implemented: delete prompts, more than one collection (`CreateCollection` returns `login`),
+ per-app ACLs, searching a *locked* collection (returns nothing instead of the locked list).
+
+## Import and export (`src/vault/vimport.c`, `kdbx.c`, `csvp.c`, `xmlmini.c`)
+
+All parsers run inside `lord-vault` on bytes read from an fd, allocate from the arena and were
+fuzzed (truncation at every offset and random byte flips under ASan/UBSan).
+
+| Format | How |
+|---|---|
+| KeePass / KeePassXC **KDBX 4.0/4.1** | own reader: Argon2d/Argon2id (Monocypher), AES-KDF, AES-256-CBC or ChaCha20, header SHA-256 + HMAC, HMAC-SHA256 block stream, gzip, inner header and binaries, ChaCha20 protected values, KeePass XML (groups → category tree, tags, times, custom and protected fields, attachments, TOTP in `otp`/legacy keys) |
+| KeePass **KDBX 3.1** | same reader (Salsa20 inner stream, hashed blocks); AES-KDF uses AES-NI when present |
+| KeePassXC CSV | supported as a fallback; it loses tags, custom fields and attachments |
+| Bitwarden JSON / CSV | logins, notes, cards, identities, custom fields, folders; encrypted exports are refused with a clear message |
+| Chrome/Chromium, Firefox, Apple CSV | yes |
+| Passwords CSV / copy (`.lvault`) | export and import; a `.lvault` copy opens with its own unlock methods and is merged |
+
+Twofish KDBX files and Argon2 version 0x10 are not supported. Export to CSV shows a red warning
+and needs an explicit confirmation; export to `.lvault` writes an encrypted copy with the same
+slots.
+
+## Templates and categories
+
+Built-in categories, each with a field template (`apps/passwords/templates.js`): General,
+Internet, Email, Finance, Cards, Network, Wi-Fi (with QR), Servers/SSH, Databases, Apps,
+Licenses (attachments), API and tokens, Identity and documents (photo attachments), Crypto (extra
+warning), VPN (link to Settings → Network), Secure notes (markdown + attachments). Users create
+categories with a name, icon, colour, parent (any depth: KeePassX-style tree) and their own field
+definitions; imported KeePass/Bitwarden folders become user categories. Items have one category,
+many tags (with colours), favourite, archived, trash, history, attachments and an optional
+"change every N days" reminder.
+
+## Security report and generator
+
+- **Weak:** strength below "fair" or in the bundled list of the 10,000 most common passwords
+ (SecLists, MIT), also catching case, trailing digits/symbols and leetspeak variants.
+- **Reused:** grouped by a keyed BLAKE2b of the password (computed in `lord-vault`).
+- **Old:** past their reminder, or unchanged for a year.
+- **Breached, offline only:** the common-password list, and optionally a local Have I Been Pwned
+ "pwned-passwords-sha1-ordered-by-hash" file chosen by the user (binary search with `pread`).
+ Nothing is ever looked up online; `lord-vault` has no network at all.
+- **Generator:** passwords (length 8–64, classes, no look-alikes) and passphrases from the EFF large
+ word list (7,776 words, CC BY 3.0 US), with separator, capitals and a digit. Random bytes from
+ `getrandom` with rejection sampling.
+
+## TOTP and QR codes
+
+- RFC 6238 TOTP and RFC 4226 HOTP with SHA-1/256/512, 6–10 digits, any period; `otpauth://` URIs
+ and bare base32 secrets.
+- Adding 2FA from a QR image: `qr-scan` decodes the PNG/JPEG inside `lord-vault` with our own QR
+ decoder (`src/vault/qr.c`: finder patterns, affine sampling with the alignment pattern, format
+ and version info, Reed-Solomon correction).
+
+## Measurements (VM 116: Xeon Silver 4108 @ 1.8 GHz, 4 vCPU, no GPU)
+
+| What | Result |
+|---|---|
+| Argon2id calibrated for this VM | 128 MiB, 5 passes |
+| Unlock with the master password | 435–660 ms (target 0.5–1 s) |
+| Session keyring at login | ~0.4 s, created on first login |
+| Search 10,001 items (model) | 0.44–1.60 ms |
+| Search 10,004 items (inside lord-vault, measured there) | worst 1.53 ms (< 10 ms) |
+| List of 10,004 items to the UI | 1.7 MB in 43 ms round trip |
+| Open a vault with 10,004 items (recovery key, no Argon2) | 169 ms |
+| Import a 10,000-row Chrome CSV | 223 ms total (parse 14 ms) |
+| KDBX 4 Argon2d 64 MiB × 10, 300 entries | 579 ms |
+| KDBX 3.1 from keepassxc-cli (33.7 M AES-KDF rounds) | 958 ms with AES-NI |
+| FIDO2 hmac-secret with the software key | ~307 ms (three simulated 100 ms touches) |
+| Wi-Fi QR encode / decode a 1000×1000 screenshot | 0.53 ms / 11.4 ms |
+| Secret Service DH modexp (1024 bit) | 5.3 ms |
+| lord-vault memory with the demo vault open | 28 KB in use, 256 KB mlocked, all regions locked |
+
+## Testing
+
+`make -C server test` builds and runs, among the rest:
+
+| Test | What |
+|---|---|
+| `build/monocypher-test` | Monocypher's official test vectors (`tests/test.c` + `vectors.h` of 4.0.2) |
+| `build/vcrypto-test` (27) | AES (FIPS-197, SP 800-38A CBC), SHA-1, HMAC (RFC 2202/4231), HKDF (RFC 5869), the arena |
+| `build/vault-test` (74) | vault round trip, every unlock method, wrong password, **every byte flipped** (1165/1165 detected), **truncated at every length**, unknown version, atomic save + `.bak`, model upsert/keep/history, 10k-item search < 10 ms, RFC 6238/4226 vectors, otpauth parsing, generator and strength, JSON, chunked messages with fds, Argon2 timing |
+| `build/ctap-test` (135) | CBOR (RFC 8949 Appendix A), 200,000 random mutations, P-256 vectors from python-cryptography, PIN protocol math, CTAPHID reassembly |
+| `build/dbus-test` (103) | D-Bus marshalling, 316,000 mutated messages, DH vectors, an end-to-end Secret Service over a fake bus |
+| `build/import-test` (150) | all formats, 5 real KDBX files, key files, tampering, truncation, fuzzing under ASan/UBSan |
+| `build/qr-test` (36) | known-answer QR matrices, 360 round trips, error correction, real PNGs, fuzzing |
+
+Not part of `make test` because they need the real helper or root:
+
+- `build/vault-e2e` (47/47): drives the real sandboxed `lord-vault` through `vclient.c` (create,
+ unlock, wrong password, items, search, report, TOTP, QR, attachments, key file on a "USB",
+ recovery key, password + key file, import/export, keyring ownership and sharing, screen lock
+ closing Passwords but not the keyring, `NoNewPrivs`/`Seccomp` set).
+- `tests/fido-soft/run-pw-116.sh` (32/32): `softfido`, a software CTAP2 authenticator on
+ `/dev/uhid` (CTAPHID, getInfo, clientPIN, makeCredential, getAssertion with hmac-secret), and the
+ client against it: same salt → same secret, other salt or credential → different, wrong key →
+ `no-credential`, PIN required/invalid/blocked paths, timeout and cancel.
+- `tests/secretsvc/run-pw-116.sh` (15/15): a demo backend on the real session bus with
+ `secret-tool`.
+
+**Untested: real security keys.** No YubiKey, SoloKey or Nitrokey was available; the FIDO2 path was
+exercised only against our software authenticator over uhid (in the tests and in the real session
+for the screenshots) and against recorded/synthesised frames. CTAP 2.1 PIN protocol 2 and keys
+whose only verification is built in (fingerprint) are not implemented/tested.
+
+## Files
+
+| Path | What |
+|---|---|
+| `third_party/monocypher/` | Monocypher 4.0.2 (CC0/BSD-2), official tests and vectors |
+| `third_party/wordlists/` | EFF large word list (CC BY 3.0 US), 10k common passwords (SecLists, MIT) |
+| `server/src/vault/vault.c`, `vault_int.h` | `lord-vault`: process, sandbox, channels, requests |
+| `server/src/vault/keyring.c` | session keyring, `kr-*` requests, Secret Service backend |
+| `server/src/vault/vfile.c` | the `.lvault` format, slots, KDF, atomic save |
+| `server/src/vault/vmodel.c` | decrypted content: items, search, list, history |
+| `server/src/vault/smem.c` | the secret arena |
+| `server/src/vault/vjson.c`, `vwire.c` | in-arena JSON, the message protocol |
+| `server/src/vault/vgen.c`, `totp.c`, `qr.c`, `vstb.c` | generator/strength/HIBP, TOTP, QR, stb with the arena |
+| `server/src/vault/vcrypto.c` | AES, SHA-1, HMAC, HKDF |
+| `server/src/vault/ctap2.c`, `cbor.c`, `p256.c`, `fidodev.c` | FIDO2 client, CBOR, P-256, device discovery |
+| `server/src/vault/dbus.c`, `secretsvc.c` | own D-Bus and the Secret Service |
+| `server/src/vault/vimport.c`, `kdbx.c`, `csvp.c`, `xmlmini.c` | importers |
+| `server/src/vault/vclient.c`, `server/src/ui/js_vault.c` | lord-server side, `lord.vault` |
+| `server/mk/vault*.mk` | build and test rules |
+| `sdk/vault.js` | `vaultRequest`, `keyring`, `autofill`, `<AutofillButton>`, `<KeyringPrompt>` |
+| `apps/passwords/` | the app |
+| `assets/locales/{en,es,pt}/passwords.json` | texts |
+| `tests/fido-soft/` | software FIDO2 authenticator |
diff --git a/docs/PRIVACIDAD.md b/docs/PRIVACIDAD.md
index afcd79b..ea9ae32 100644
--- a/docs/PRIVACIDAD.md
+++ b/docs/PRIVACIDAD.md
@@ -17,14 +17,15 @@ primera vez y el usuario decide. Ver también [FIRMA.md](FIRMA.md) (paquetes fir
| Permisos por app, estilo TCC, guardados donde la app no escribe (`server/src/sec/perms.c`) | **hecho** |
| Avisos dibujados por el sistema (también los que pide una app aislada por el broker), Ajustes → Privacidad, puntos verde/naranja | **hecho** |
| cgroup por app (`app-lordos-lpk-<id>.scope`, `app-lordos-<id>.scope`) con límites, en el subárbol delegado de la sesión | **hecho**, probado con `lord-sessiond` y `Delegate=yes` |
+| **Root-owned app scopes**: an app can't move itself to another cgroup (`lord-sessiond` places each process, see [Root-owned app scopes](#root-owned-app-scopes)) | **done**, tested on VM 122 (the `systemd-run --user --scope` path stays open, see there) |
| Firma de paquetes y niveles de confianza | **hecho**, ver [FIRMA.md](FIRMA.md) |
| Tokens del tema, idioma y dirección (RTL) **en vivo** dentro del proceso de la app | **hecho** (claro/oscuro, acento, idioma; probado con árabe) |
| Revocación en vivo: al denegar un permiso, la app suelta la cámara/el micrófono al instante | **hecho** |
| Powerbox: diálogo de abrir/guardar **dibujado por lord-server** que entrega solo el fd del archivo elegido | **hecho** (`fs.openFile`/`fs.saveFile`) |
| Menús de la app en la barra de menú del sistema | **hecho** (por el broker) |
| **Micrófono** como datos (audio) por un anillo de solo lectura, tras consentimiento | **hecho** (lord-server abre el flujo de PipeWire; la app lee el nivel por su cursor; revocar lo cierra) |
-| Cámara como frames decodificados por un anillo (vía lord-media), tras consentimiento | **pendiente** (consentimiento, indicador y revocación listos; falta el anillo MM_RING de lord-media y un `/dev/video` para probar — la VM 122 no tiene) |
-| Varias ventanas por app aislada | **pendiente** — ver nota abajo |
+| Cámara como frames decodificados por un anillo (vía lord-media), tras consentimiento | **done**, tested on VM 122 with v4l2loopback (see [Camera for isolated apps](#camera-for-isolated-apps)) |
+| Varias ventanas por app aislada | **done**, tested on VM 122 (see [Several windows per isolated app](#several-windows-per-isolated-app)) |
## El proceso por app
@@ -259,11 +260,12 @@ delegado**. Lo prepara `lord-sessiond` (ver [SESIONES.md](SESIONES.md)):
2. Al arrancar, `lord-sessiond` se mueve a la hoja `supervisor` (`cgroup_service_init`): la raíz
del servicio queda sin procesos y puede habilitar `cpu memory pids` para sus hijos (regla «sin
procesos internos» de cgroup v2).
-3. Por cada sesión, `cgroup_delegate_session(uid, gid)` crea `lordos-session-<uid>/server`, mete
- ahí al `lord-server` del usuario y le **cede** el subárbol (`chown`).
-4. `lord-server` crea las scopes de sus apps como hermanas de `server`, sin root:
- `app-lordos-lpk-<id>.scope` (apps `.lpk`, desde `sandbox.c`) y `app-lordos-<id>.scope` (apps
- Linux, una línea en el lanzador de `apps.c`: `app_scope_enter(id)`).
+3. Por cada sesión, `cgroup_delegate_session(uid, gid)` crea `lordos-session-<uid>/server` y mete
+ ahí al `lord-server` del usuario. **Update:** the subtree is no longer chowned to the user; it
+ stays root's.
+4. **Update:** the app scopes (`app-lordos-lpk-<id>.scope`, `app-lordos-<id>.scope`,
+ `app-lordos-media.scope`…) are created by `lord-sessiond` on request and are root-owned, so an
+ app can't leave its scope. See [Root-owned app scopes](#root-owned-app-scopes).
Medido en la VM 122 (dos usuarios, `lord` en el monitor y `bob` desde el navegador):
@@ -367,18 +369,169 @@ micrófono (temas `default` y `classic`); al tocarlo muestra qué app lo usa. Fu
| `server/src/sec/perms.c` | permisos por app (TCC), `permisos.json` |
| `server/src/ui/js_sec.c` | `lord.perms`, `lord.sign` y `lord.broker.resolve` |
| `sdk/privacy.js` | avisos, indicadores, `registerPrivacySection`, `requestPermission` |
+| `server/src/remote/cgsup.c` | the root placement service on `/run/lordos/cgroup.sock` (child of `lord-sessiond`) |
+| `server/src/sec/brokercam.c`, `broker_int.h` | the camera of isolated apps, server side (ring, ACK validation, powerbox saves, revoke) |
+| `server/src/ui/js_brokercam.c` | `lord.media` (camera) inside the app process |
+| `tests/lpk-legit` | also: camera, photo/video through the powerbox, «New window» |
| `apps/settings/Privacy.jsx` | Ajustes → Privacidad |
| `tests/lpk-evil`, `tests/lpk-legit` | apps de prueba (maliciosa y legítima) |
| `server/tests/sandbox_test.c` | pruebas de la caja de arena (app, red, ayudante) |
-### Varias ventanas por app aislada (pendiente)
-
-Hoy cada app `.lpk` aislada tiene **una** ventana: `server/src/app/appclient.c` guarda la superficie,
-el `xdg_surface` y el `xdg_toplevel` en variables globales (una sola de cada una), y todo el dibujo
-(buffers, callbacks de cuadro) y la entrada se arman alrededor de esa única superficie. Soportar
-varias ventanas es un cambio transversal, no aditivo: hay que pasar esos globales a una estructura
-por ventana, que el «app host» (`runtime/app-host.js`) monte varios *roots* (uno por superficie) y
-que la app pueda pedir una ventana nueva, y que el compositor (`sdk/wayland.js`) mapee cada
-superficie como su propia ventana `linux#…` con el mismo `appId` (menús, tema e idioma a la correcta).
-Queda para una próxima iteración; el resto de M8 (proceso por app, broker, powerbox, micrófono,
-menús, revocación) no lo necesita.
+## Root-owned app scopes
+
+The session's cgroup subtree used to be delegated to the user (`chown`), so a Linux app without a
+sandbox, running as the user, could write its pid into another cgroup's `cgroup.procs` (another
+app's scope, `server`, or a new cgroup it created) and leave its per-app firewall rules and its
+accounting behind. `.lpk` apps never could (Landlock hides `/sys`).
+
+Now the subtree stays **root-owned** and the scopes are created by root:
+
+- `cgroup_delegate_session()` (`server/src/sec/cgroup.c`) creates `lordos-session-<uid>/server`
+ and moves the session's `lord-server` there, but no longer chowns anything to the user
+ (`cgroup_harden_session`). At startup, `cgroup_service_init()` hardens the subtrees left by an
+ older `lord-sessiond` (sessions survive a restart).
+- `lord-sessiond` forks a small root child (`server/src/remote/cgsup.c`) that listens on
+ `/run/lordos/cgroup.sock` (`SOCK_SEQPACKET`, mode 0666; `SO_PEERCRED` decides). It serves one
+ request: `enter <scope> <memory.high MB> <memory.max MB> <cpu %>`. It dies with its parent
+ (`PR_SET_PDEATHSIG`) and is restarted if it ends.
+- `cgroup_enter()` (used by the Linux app launcher, `sandbox_apply` and `sandbox_apply_helper`)
+ asks that socket to place **the calling process itself**, right before `execve` (or before the
+ sandbox). Without `lord-sessiond` (development) it falls back to the old self-migration.
+- `cgroup_place_serve()` (root) only places a peer that:
+ - is in its own session's `server` leaf (`/proc/<pid>/cgroup`): `lord-server` or a child it
+ forked right before exec. A process already in an app scope can never ask;
+ - runs a binary from `lord-server`'s directory (root-owned, not writable by others;
+ `insecure_dev` relaxes it on development VMs). A binary replaced while running
+ (`(deleted)`) is still accepted;
+ - asks for a valid name: `app-lordos-<id>.scope` or `lordos-<helper>.scope`, never
+ `lordos-session-…`.
+
+ It creates the scope (root-owned, its control files too), writes the limits, and writes the
+ peer's pid into `cgroup.procs`. The peer is blocked waiting for the reply, so its pid can't be
+ reused meanwhile.
+
+Result: in the session subtree every `cgroup.procs` (the session's, `server`'s and each scope's)
+and every directory is root's. Moving a process between two cgroups needs write access to the
+`cgroup.procs` of their common ancestor, so a user process can't leave its scope, enter another
+one or create a cgroup.
+
+Tested on VM 122, from inside a Linux app (`foot` in `app-lordos-aisla.scope`, with the firewall
+restriction «no internet»):
+
+```
+$ echo $$ > server/cgroup.procs Permission denied
+$ echo $$ > ./cgroup.procs (session) Permission denied
+$ mkdir lordos-session-1000/escape Permission denied
+$ mkdir <own scope>/sub Permission denied
+== my cgroup now: lordos-session-1000/app-lordos-aisla.scope
+== net after: curl: (7) Failed to connect to example.com port 443 (the rule still applies)
+```
+
+![The scope escape attempts fail](m8-aislamiento-scope.png)
+
+Also tested: the `.lpk` app, `lord-media` (`app-lordos-media.scope`) and Linux apps are placed
+by `lord-sessiond`; `systemctl restart lordos` twice with the session alive (the new
+`lord-sessiond` hardens the old subtree, starts a new placement service, and an app launched
+afterwards still lands in its scope); `DelegateSubgroup=supervisor` in the unit.
+
+**Known gap: `systemd-run --user --scope`.** The same screenshot shows it: a process can still ask
+the user's systemd manager for a new scope. The user manager can't migrate it itself, so it asks
+PID 1 (`AttachProcessesToUnit`), which runs as root and only checks that the process and the
+target unit belong to the same UID; it does not look at the source cgroup. The process then runs
+in `user@<uid>.service/app.slice/run-….scope`, outside `lordos.service`, where `lord-netperm`'s
+programs aren't attached. Closing it needs either `lord-netperm` hooks on the users' `user@`
+subtrees (treating a LordOS session user's transient scopes as an unknown app) or a systemd-side
+policy; neither is done. `.lpk` apps can't do it (no D-Bus, no new sockets).
+
+Not tested this round: a second user over fast user switching and the remote desktop (no test
+password at hand). Their code path is the same `cgroup_delegate_session()` per uid.
+
+## Camera for isolated apps
+
+Consent, the green dot and revocation already existed. The frames now reach the app without the
+app ever touching the device:
+
+```
+/dev/video10 ──open (after consent)──▶ lord-server ──fd──▶ lord-media (MK_CAMERA, sandbox_apply_helper)
+ │ decodes into MM_RING (3 BGRA slots,
+ │ sealed memfd), MM_FRAME per frame
+lord-server (sec/brokercam.c) ◀──────────────────────────────┘
+ │ read-only reopen of the ring (/proc/self/fd/N, O_RDONLY) + "frame <sid> <id>" events
+ ▼
+lord-server --app (ui/js_brokercam.c) — maps it PROT_READ, draws it with <MediaView> (media/mview.c),
+ answers "ack <sid> <id>"; lord-server validates it and only then sends MM_ACK to lord-media
+```
+
+- **Broker op `BOP_CAMERA`** (`sec/broker.h`): `list`, `open dev w h`, `ring sid` (→ the read-only
+ fd), `ack sid id` and `size sid w h` (no reply), `photo sid mirror name`,
+ `record sid mirror mic name`, `recstop sid`, `close sid`. Each one checks the `camera`
+ permission again in `lord-server`.
+- **The device:** `lord-server` validates `/dev/videoN`, opens it and passes it only to
+ `lord-media`. The app process never sees it (Landlock hides `/dev` anyway).
+- **The ring:** `lord-server` checks the memfd from `lord-media` (sealed against shrinking, big
+ enough) and keeps it. The app gets a new **read-only** open file description, so it can only map
+ it `PROT_READ` (verified: the mapping is `r--s` in `/proc/<pid>/maps`) and can't write a frame
+ that another reader would see.
+- **ACK validation** (`brokercam.c`): an ACK is forwarded to `lord-media` only if its generation
+ is the current ring's, its slot exists and holds a frame `lord-server` forwarded and nobody
+ acknowledged yet, and the app has tokens left (120 ACKs/s, burst 30). Anything else is dropped
+ and counted. `lord-media` frees slots only on a valid ACK, so an app that never acknowledges, or
+ acknowledges garbage, only stops its own preview. If the app's socket is full, `lord-server`
+ acknowledges the frame itself so the ring never jams. After a resize the app may acknowledge a
+ frame of the previous generation once: that's logged as `invalid camera ACK ignored (1)`.
+- **Photo and video:** the app asks `photo`/`record` with a suggested name. `lord-server` opens
+ the **system's save dialog** (the powerbox, reqids with the high bit set), opens the chosen
+ file itself (`O_NOFOLLOW`, regular file only) and gives that fd to `lord-media` (`MM_PHOTO`,
+ `MM_RECORD`). The app only gets the file's name back (event `photo`/`video`). Recording with
+ sound also needs the `microphone` permission; the PipeWire stream is `lord-server`'s.
+- **Revoke:** Settings → Privacy → Camera → Deny calls `brokersrv_revoke`, which sends `revoke`
+ to the app, kills its `lord-media` (`SIGKILL`) and closes the source: the stream stops at once
+ and the green dot goes off. The app gets `closed` (`revoked: true`) and blanks its view.
+- **Same SDK:** an isolated app uses `media.cameras()`, `media.camera()`, `<MediaView>`,
+ `media.photo()` and `media.cameraRecord()` as in the session; in the app process `lord.media`
+ is the camera subset above (`js_brokercam.c`).
+
+Tested on VM 122 with `v4l2loopback` (`/dev/video10`) fed by `ffmpeg` (`testsrc2` 1280×720 YUYV,
+service `lordos-test-camfeed`) and `tests/lpk-legit`: live preview, `foto.jpg` (1280×720 JPEG)
+and `video.mp4` (H.264, 4.5 s) saved through the powerbox, and revocation (the `lord-media`
+process is gone within 0.5 s). While previewing, the app process uses ~1–2 % CPU and
+`lord-media` ~9 %.
+
+| | |
+|---|---|
+| ![camera preview inside the isolated app](m8-aislamiento-camara.png) | ![camera revoked](m8-aislamiento-camara-revocada.png) |
+| The preview in `tests/lpk-legit` (its own process), with the green dot | After «Deny» in Settings: the stream stopped, the dot is gone |
+
+Not tested: a hostile app sending forged or flooded ACKs (the JS API only acknowledges frames it
+received; it would take native code inside the sandbox). The validation is in
+`brokercam_handle` (`"ack"`).
+
+## Several windows per isolated app
+
+`server/src/app/appclient.c` keeps one `AppWin` per toplevel (surface, `xdg_surface`,
+`xdg_toplevel`, decoration, its two `wl_shm` buffers, size, frame callback and the root node it
+draws). The app host (`runtime/app-host.js`) registers the app in the SDK's window store of its
+own process, so the app opens and closes windows with the usual SDK:
+
+- `wm.open(appId, { new: true })` opens another window; `wm.close(id)`, `wm.setTitle(id, t)` and
+ `useAppWindow()` work per window. The app host renders every window as a child of the React root
+ and binds it to its surface with `lord.appWindows` (`open`, `attach`, `close`, `setTitle`).
+- Each window is laid out and painted on its own surface from its root node (`layout_root`,
+ `paint_root`), and the pointer is hit-tested in the window it is over (`wl_pointer.enter`).
+ Keyboard focus follows `wl_keyboard.enter`; the app host raises that window (`wm.focus`).
+- The frame's close button sends `xdg_toplevel.close` for that surface; the app host runs
+ `wm.close(id)` (close guards still apply). Closing the last window ends the process.
+- In the session, every surface is its own `linux#<surface>` window with the theme frame
+ (`sdk/wayland.js`); the Dock groups all of them under the app's entry (`launcherIdOf`), the app's
+ menus go to every window of the app, and «New window» in the Dock reaches the running process
+ through the broker (`window` event) instead of launching a second process.
+
+![two windows of one isolated app, the Dock menu lists both](m8-aislamiento-ventanas.png)
+
+Tested on VM 122 with `tests/lpk-legit`: «New window» from the app and from the Dock menu, the Dock
+menu listing every window, closing a window, focus and input in each one.
+
+Also fixed while testing: the app's event loop now drains broker events that arrived during a
+synchronous RPC (`js_broker_pending`), events are NUL-terminated before `JS_ParseJSON` (a
+`revoke` could be dropped), and an isolated app no longer inherits `lord-server`'s blocked
+`SIGTERM`/`SIGINT`.
diff --git a/docs/RED.md b/docs/RED.md
index d2acadb..2e26d7f 100644
--- a/docs/RED.md
+++ b/docs/RED.md
@@ -5,102 +5,102 @@ La red de LordOS es propia y corre directo sobre el kernel. No usa NetworkManage
| Lado | Qué hace | Archivos |
|---|---|---|
| lord-server (sin root) | Lee el estado con rtnetlink (interfaces, direcciones, rutas, contadores) y escucha los cambios. El DNS sale de `/run/systemd/resolve/resolv.conf` o de `/etc/resolv.conf`. Lo expone a JS como `lord.net`. | `state.c`, `ui/js_net.c` |
-| `lord-netd` (root, la red del sistema) | Atiende las acciones `net-*` de la lista cerrada de `admin.c` y es dueño de los procesos residentes (DHCP, wpa_supplicant, VPN). Lo lanza y vigila `lord-sessiond` al arrancar el equipo (ver «La red es del sistema»). Sin `lord-sessiond`, las atiende el ayudante de la sesión, como antes. | `actions.c`, `dhcp.c`, `wifi.c`, `wg.c`, `ovpn.c`, `ipsec.c` + `vici.c`, `vpnproc.c` (PPTP, OpenConnect, Fortinet), `vpn.c` (lo común), `sys.c` |
+| `lord-netd` (root, the system network) | Serves the `net-*` actions of `admin.c`'s closed list and owns the resident processes (DHCP, wpa_supplicant, VPN). `lord-sessiond` starts and supervises it at boot (see "The network belongs to the system"). Without `lord-sessiond`, the session's helper serves them, as before. | `actions.c`, `dhcp.c`, `wifi.c`, `wg.c`, `ovpn.c`, `ipsec.c` + `vici.c`, `vpnproc.c` (PPTP, OpenConnect, Fortinet), `vpn.c` (lo común), `sys.c` |
| compartido | netlink propio, criptografía mínima (X25519, SHA-1/PBKDF2, base64), utilidades | `nl.c`, `crypto.c`, `netpriv.h` |
-## La red es del sistema: `lord-netd` (M9)
+## The network belongs to the system: `lord-netd` (M9)
-Hasta M8 la red la levantaba el ayudante root de la **primera sesión** que entraba
-(`/run/lordos/net-owner`). Eso tenía tres problemas en un sistema instalado:
+Up to M8 the network was brought up by the root helper of the **first session** that logged in
+(`/run/lordos/net-owner`). On an installed system that had three problems:
-- antes del primer ingreso no había red: la pantalla de ingreso mostraba el nombre del equipo en
- lugar de la IP y el escritorio remoto no se alcanzaba;
-- si esa sesión cerraba, sus DHCP y wpa_supplicant terminaban con ella y las otras sesiones no la
- volvían a levantar;
-- la red dependía de quién entraba primero.
+- there was no network before the first login, so the greeter showed the hostname instead of the
+ IP and the remote desktop was unreachable;
+- if that session logged out, its DHCP client and wpa_supplicant exited with it, and the other
+ sessions didn't bring the network back;
+- the network depended on who logged in first.
-Ahora la red es del sistema, como NetworkManager o systemd-networkd:
+Now the network belongs to the system, like NetworkManager or systemd-networkd:
```
lordos.service
└── lord-sessiond
- └── lord-netd la red: DHCP, Wi-Fi guardadas, configs, DNS, VPN
- ├── if:<if> cliente DHCP (código propio)
+ └── lord-netd the network: DHCP, saved Wi-Fi, configs, DNS, VPN
+ ├── if:<if> DHCP client (our own code)
├── wpa:<if> wpa_supplicant
- └── vpn:<nombre> openvpn, charon, pppd…
-lord-server --user lord ── lord-admin ──┐ /run/lordos/netd.sock (0600, solo root)
-lord-server --user ana ── lord-admin ──┘ las acciones net-* se pasan tal cual
+ └── vpn:<name> openvpn, charon, pppd…
+lord-server --user lord ── lord-admin ──┐ /run/lordos/netd.sock (0600, root only)
+lord-server --user ana ── lord-admin ──┘ net-* actions are forwarded as they are
```
-- **Qué es.** `lord-netd` es el mismo `admin.c` compilado con `LORD_NETD` (`server/src/net/netd.c`
- solo tiene `main`): su tabla tiene **solo** las acciones `net-*`, con las mismas validaciones, y no
- ejecuta nada que esas acciones no ejecutaran ya. Solo libc.
-- **Cuándo arranca.** `lord-sessiond` lo lanza al arrancar, antes que la pantalla de ingreso
+- **What it is.** `lord-netd` is `admin.c` built with `LORD_NETD` (`server/src/net/netd.c` only has
+ `main`). Its table has **only** the `net-*` actions, with the same validation, and it runs
+ nothing those actions didn't already run. libc only.
+- **When it starts.** `lord-sessiond` starts it at boot, before the greeter
(`server/src/remote/netsup.c`):
- - ruta fija `<carpeta de lord-sessiond>/lord-netd`, de root y no escribible por otros (salvo
- `insecure_dev`);
- - sin argumentos y con un entorno mínimo;
- - en su propia sesión (`setsid`).
-
- `lord-netd` corre `net-restore` él solo: configs de `/etc/lordos/net/if`, DHCP en las placas
- físicas libres, Wi-Fi con las redes guardadas y DNS. Por eso hay IP antes de que alguien entre.
-- **Las sesiones** no levantan nada. El ayudante de cada sesión se conecta a `/run/lordos/netd.sock`
- (`SO_PEERCRED`: solo uid 0), se presenta con `HELLO <usuario>` y le pasa tal cual cada acción
- `net-*`. `lord-netd` vuelve a calcular si ese usuario es administrador (grupo sudo) y aplica
- `A_ANYONE` igual que antes. Las respuestas vuelven al ayudante que pidió; los avisos (`net dhcp…`,
- `net wifi…`, `net vpn…`), a todas las sesiones. Ajustes → Red no cambió.
-- **`net-restore` de una sesión** responde `OK 0 interfaz(es): la red es del sistema (lord-netd)`.
-- **Contraseñas de Wi-Fi y VPN:** siguen en `/etc/lordos/net/wifi` y `/etc/lordos/net/vpn` (root,
- 0600). Viajan por el socket entre dos procesos root y nunca vuelven a una sesión.
-- **Si `lord-netd` termina,** `lord-sessiond` lo vuelve a lanzar: espera 1, 2, 4… hasta 30 s, y
- vuelve a 1 s si había durado más de un minuto.
- - Su cliente DHCP recibe `SIGUSR1` (`PR_SET_PDEATHSIG`): se va **sin soltar la dirección** y deja
- la concesión en `/run/lordos/dhcp/<if>.lease` (0600). El cliente nuevo la confirma
- (INIT-REBOOT) y las conexiones no se cortan.
- - Las VPN que estaban prendidas se vuelven a conectar (`/run/lordos/netd-vpns`).
- - wpa_supplicant sí se reinicia: el Wi-Fi se vuelve a asociar en unos segundos.
-- **Si se reinicia `lord-sessiond`** (`KillMode=process`), `lord-netd` sigue vivo y el
- `lord-sessiond` nuevo lo **adopta**: lee `/run/lordos/netd.pid`, verifica que sea un proceso
- root llamado `lord-netd` y lo vigila con un `pidfd` en su `poll`, sin sondear. El lock
- `/run/lordos/netd.lock` (`flock`) impide que corran dos.
-- **Reconexión de las sesiones:** si `lord-netd` se reinicia, el ayudante de cada sesión lo ve
- aparecer de nuevo con inotify sobre `/run/lordos` (el socket se crea con otro nombre y se renombra
- cuando ya escucha) y se vuelve a conectar. Una acción que estaba en curso responde «la red del
- sistema se reinició: probá de nuevo».
-- **Sin `lord-sessiond`** (un `lord-server` suelto, en desarrollo) no existe
- `/run/lordos/netd.enabled` y el ayudante de la sesión corre la red él mismo, como antes (con
- `net-owner`). Con esa marca, una sesión nunca levanta la red por su cuenta.
-- **Los procesos residentes ya no viven en los hijos del ayudante** (`admin_daemon_fork` y las
- acciones `A_FORK` solo se quedan con su pipe): un DHCP que sobrevive no retiene el lock ni el
- socket de `lord-netd`.
-
-### Prueba (VM 119, 17 de octubre)
-
-La VM 119 corre `lord-sessiond` instalado como el `.deb` (no se instaló desde el ISO; ver
-`VM-SETUP.md`, paso 20). `eth0` la maneja systemd-networkd (netplan) y LordOS no la toca, así que la
-prueba usa una placa de LordOS: el veth `lnt0`, con su par en el netns `lnt` y un `dnsmasq` ahí
-(`lordos-test-netns.service`, arranca antes que `lordos.service`) y `/etc/lordos/net/if/lnt0.conf`
-con `method=dhcp`.
-
-| Prueba | Resultado |
+ - fixed path `<lord-sessiond's directory>/lord-netd`, root-owned and not writable by others
+ (unless `insecure_dev`);
+ - no arguments and a minimal environment;
+ - in its own session (`setsid`).
+
+ `lord-netd` runs `net-restore` by itself: the configs in `/etc/lordos/net/if`, DHCP on free
+ physical NICs, Wi-Fi with the saved networks, and DNS. That is why there is an IP before anyone
+ logs in.
+- **Sessions** bring nothing up. Each session's helper connects to `/run/lordos/netd.sock`
+ (`SO_PEERCRED`: uid 0 only), introduces itself with `HELLO <user>` and forwards every `net-*`
+ action as it is. `lord-netd` works out again whether that user is an administrator (group sudo)
+ and applies `A_ANYONE` as before. Replies go back to the helper that asked; events
+ (`net dhcp…`, `net wifi…`, `net vpn…`) go to every session. Settings → Network didn't change.
+- **A session's `net-restore`** answers `OK 0 interfaz(es): la red es del sistema (lord-netd)`.
+- **Wi-Fi and VPN passwords** stay in `/etc/lordos/net/wifi` and `/etc/lordos/net/vpn` (root, 0600).
+ They travel over the socket between two root processes and never go back to a session.
+- **If `lord-netd` exits,** `lord-sessiond` starts it again: it waits 1, 2, 4… up to 30 s, and goes
+ back to 1 s if it had run for more than a minute.
+ - Its DHCP client gets `SIGUSR1` (`PR_SET_PDEATHSIG`): it exits **without releasing the address**
+ and leaves the lease in `/run/lordos/dhcp/<if>.lease` (0600). The new client confirms it
+ (INIT-REBOOT) and connections are not dropped.
+ - VPNs that were up are reconnected (`/run/lordos/netd-vpns`).
+ - wpa_supplicant does restart: Wi-Fi reassociates within a few seconds.
+- **If `lord-sessiond` restarts** (`KillMode=process`), `lord-netd` keeps running and the new
+ `lord-sessiond` **adopts** it: it reads `/run/lordos/netd.pid`, checks that it is a root process
+ named `lord-netd` and watches it with a `pidfd` in its `poll`, without polling. The lock
+ `/run/lordos/netd.lock` (`flock`) prevents two from running.
+- **Sessions reconnect:** when `lord-netd` restarts, each session's helper sees it come back with
+ inotify on `/run/lordos` (the socket is created under another name and renamed once it listens)
+ and reconnects. An action in progress answers "la red del sistema se reinició: probá de nuevo".
+- **Without `lord-sessiond`** (a standalone `lord-server`, in development) there is no
+ `/run/lordos/netd.enabled`, and the session's helper runs the network itself, as before (with
+ `net-owner`). With that mark, a session never brings the network up on its own.
+- **Resident processes no longer inherit the helper's descriptors** (`admin_daemon_fork` and
+ `A_FORK` actions keep only their pipe): a DHCP client that outlives `lord-netd` doesn't hold its
+ lock or socket.
+
+### Test (VM 119, October 17)
+
+VM 119 runs `lord-sessiond` installed like the `.deb`; it was not installed from the ISO (see
+`VM-SETUP.md`, step 20). `eth0` is managed by systemd-networkd (netplan) and LordOS leaves it
+alone, so the test uses a LordOS-managed NIC: the veth `lnt0`, whose peer is in the netns `lnt`
+with a `dnsmasq` there (`lordos-test-netns.service`, which starts before `lordos.service`), and
+`/etc/lordos/net/if/lnt0.conf` with `method=dhcp`.
+
+| Test | Result |
|---|---|
-| Arranque, sin nadie adentro | `lord-netd` lanzado a la vez que la pantalla de ingreso; `lnt0` con `10.77.0.96/24` a los **3 s** |
-| Escritorio remoto antes de ingresar | `curl https://10.77.0.96:5673/` desde el netns: **200** |
-| `lord` entra por el monitor, `ana` (creada en Ajustes → Usuarios) por la red | dos ayudantes conectados a `netd.sock`; Ajustes → Red muestra `lnt0` «por DHCP» |
-| `lord` cierra la sesión (era la «primera») | `lnt0` sigue con su IP |
-| `ana` también cierra: no queda ninguna sesión | `lnt0` sigue con su IP y el remoto responde 200 |
-| `kill -9` a `lord-netd` | relanzado en 1 s, `resume` de la concesión: la dirección **no se cayó ni un instante** (muestreo cada 0,5 s) |
-| `systemctl restart lordos` | `lord-netd sigue corriendo (pid …): la red no se cortó`; matarlo después: relanzado y retomado igual |
+| Boot, nobody logged in | `lord-netd` started together with the greeter; `lnt0` had `10.77.0.96/24` after **3 s** |
+| Remote desktop before login | `curl https://10.77.0.96:5673/` from the netns: **200** |
+| `lord` logs in on the monitor, `ana` (created in Settings → Users) over the network | two helpers connected to `netd.sock`; Settings → Network shows `lnt0` "por DHCP" |
+| `lord` logs out (it was the "first" session) | `lnt0` keeps its IP |
+| `ana` logs out too: no session left | `lnt0` keeps its IP and the remote desktop answers 200 |
+| `kill -9` on `lord-netd` | restarted in 1 s, lease `resume`: the address **never dropped** (sampled every 0.5 s) |
+| `systemctl restart lordos` | `lord-netd still running (pid …): the network was not interrupted`; killing it afterwards: restarted and resumed the same way |
| | |
|---|---|
-| ![pantalla de ingreso](m9-sistema-red-greeter.png) | ![Ajustes → Red](m9-sistema-red-sesion.png) |
-| Pantalla de ingreso recién arrancada, nadie adentro: abajo la IP. En esta VM es la de `eth0` (netplan); la de `lnt0` (lord-netd) ya estaba, como muestra el registro | Ya adentro: `lnt0` «por DHCP», la levantó `lord-netd` |
+| ![greeter](m9-sistema-red-greeter.png) | ![Settings → Network](m9-sistema-red-sesion.png) |
+| Greeter right after boot, nobody logged in: the IP at the bottom. On this VM it is `eth0`'s (netplan); `lnt0`'s (lord-netd) was already up, as the log shows | Logged in: `lnt0` "por DHCP", brought up by `lord-netd` |
-Arreglo que salió de la prueba: `systemctl restart lordos` fallaba con «Failed to spawn executor:
-Device or resource busy» cuando quedaban procesos vivos (pantalla de ingreso, sesiones y ahora
-`lord-netd`): systemd quiere poner al principal nuevo en la raíz del cgroup del servicio, que tiene
-controladores habilitados. `lordos.service` lleva ahora `DelegateSubgroup=supervisor`.
+A fix that came out of the test: `systemctl restart lordos` failed with "Failed to spawn executor:
+Device or resource busy" while processes were still alive (greeter, sessions and now `lord-netd`):
+systemd tries to put the new main process in the service cgroup's root, which has controllers
+enabled. `lordos.service` now has `DelegateSubgroup=supervisor`.
## Qué hay (probado en la VM)
@@ -164,7 +164,7 @@ El argumento puede tener varias líneas (`\n`). "Cualquiera" quiere decir que no
| Acción | Argumento | Quién | Respuesta |
|---|---|---|---|
-| `net-restore` | — | cualquiera | Con `lord-netd` la corre él solo al arrancar el equipo; la que manda cada sesión responde `OK 0 … la red es del sistema`. Sin `lord-netd` (desarrollo) la aplica la primera sesión, anotada en `/run/lordos/net-owner` mientras viva. Aplica las configs de `/etc/lordos/net/if`, y las interfaces físicas libres sin config van por DHCP (con Wi-Fi: wpa_supplicant más las redes guardadas). `OK <n>` |
+| `net-restore` | — | cualquiera | With `lord-netd`, it runs it by itself at boot; the one each session sends answers `OK 0 … la red es del sistema`. Without `lord-netd` (development) the first session applies it, noted in `/run/lordos/net-owner` while alive. Aplica las configs de `/etc/lordos/net/if`, y las interfaces físicas libres sin config van por DHCP (con Wi-Fi: wpa_supplicant más las redes guardadas). `OK <n>` |
| `net-up` / `net-down` | `if` | admin | `net-down` además para su DHCP/wpa |
| `net-config` | `if\nmethod=dhcp\|static\|off\naddress=ip/n\n…gateway=ip\ndns=ip…` | admin | Guarda y aplica. Rechaza las interfaces del sistema. |
| `net-manage` / `net-unmanage` | `if` | admin | Escribe y borra `/etc/systemd/network/00-lordos-<if>.network` (`Unmanaged=yes`) y hace `networkctl reload`. |
@@ -283,7 +283,7 @@ daemon <proceso> exit <código> (fin de "if:<if>", "wpa:<if>", "vpn:<nombre>")
## Procesos residentes
-Son hijos de `lord-netd` (o, sin él, del ayudante de la sesión), que los lanza con `admin_daemon_*`:
+They are children of `lord-netd` (or, without it, of the session's helper), which starts them with `admin_daemon_*`:
| Proceso | Qué es |
|---|---|
@@ -291,7 +291,7 @@ Son hijos de `lord-netd` (o, sin él, del ayudante de la sesión), que los lanza
| `wpa:<if>` | wpa_supplicant. Deja un pidfile en `/run/lordos/wpa/<if>.pid` para matar uno que haya quedado de una sesión anterior. |
| `vpn:<nombre>` | Maneja openvpn, charon, pppd, openconnect u openfortivpn. El programa muere con él (`PDEATHSIG`). |
-Si `lord-netd` se reinicia, vuelve a levantar todo y retoma las concesiones DHCP y las VPN que estaban prendidas. Después de apagar el equipo, las VPN no se conectan solas.
+If `lord-netd` restarts, it brings everything back up and resumes the DHCP leases and the VPNs that were up. After a shutdown, VPNs don't reconnect by themselves.
## Cómo se reproduce la prueba
@@ -419,6 +419,6 @@ Ya estaban: `openssl` (PKI de prueba), systemd-networkd, systemd-resolved y los
- **VPN, más:** varias IPsec a la vez, que hoy no se puede por el pidfile único de charon. IPv6 por dentro de los túneles de PPTP, OpenConnect y Fortinet (hoy solo IPv4).
- **Wi-Fi:** probar WPA3/SAE con un hostapd SAE; WPA-Enterprise (802.1X); redes ocultas desde la UI; elegir entre varios BSSID.
- **IPv6:** DHCPv6 (hoy el kernel hace SLAAC solo) y DNS por RA (RDNSS).
-- **VPN al arrancar el equipo:** una opción «conectar sola» por VPN. Hoy se restauran interfaces, Wi-Fi y las VPN prendidas antes de un reinicio de `lord-netd`, pero no las de antes de apagar.
-- **Probar `lord-netd` con una placa física y Wi-Fi reales** en un sistema instalado desde el ISO (en la VM 119 se probó con un veth y `lord-sessiond` instalado como el `.deb`).
+- **VPN at boot:** a per-VPN "connect automatically" option. Today interfaces, Wi-Fi and the VPNs that were up before a `lord-netd` restart are restored, but not those from before a shutdown.
+- **Test `lord-netd` with a real physical NIC and Wi-Fi** on a system installed from the ISO (on VM 119 it was tested with a veth and `lord-sessiond` installed like the `.deb`).
- **ifupdown:** las interfaces de `/etc/network/interfaces` se ven como del sistema, pero `net-manage` todavía no sabe sacarlas de ahí.
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index afa4aaf..a399d27 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -215,8 +215,10 @@ instalador propio, y red, VPN, sonido y portapapeles con interfaz propia.
example.com", solo LAN, sin entrantes, sin red, apagado;
- [x] Monitor: interruptor Regla por app y contadores de permitidas/denegadas; Ajustes →
Privacidad: modo, Apps confiables y Apps restringidas;
- - [ ] modo "preguntar" (diseñado), interruptores por destino, scopes con `cgroup.procs` de root
- para que una app Linux no pueda mudarse de scope.
+ - [x] root-owned scopes: `lord-sessiond` places every app process and a Linux app can't move
+ itself to another cgroup (VM 122). Still open: `systemd-run --user --scope` (PID 1 moves it
+ into `user@<uid>.service`).
+ - [ ] modo "preguntar" (diseñado), interruptores por destino.
- [x] App **Monitor**, fase 1 (`MONITOR.md`), probada en la VM 123:
- [x] pestañas Resumen, CPU, Memoria, Red, Discos y Procesos con el aspecto del Monitor de
TangoOS;
@@ -349,6 +351,71 @@ Detalle en `MEDIOS.md`. Probado en la VM 119 con capturas (`m9-media-*.png`).
- grabar un área y el audio del sistema;
- guardar en WebP.
+## M9 — System apps and system network ✅ (2026-10-18)
+
+Details in `SYSTEM.md` (apps), `RED.md` (network) and `SESIONES.md` (user folders). Tested on VM 119
+with screenshots (`m9-sistema-*.png`).
+
+- [x] **The network belongs to the system (`lord-netd`):** a small root service started and
+ supervised by `lord-sessiond` at boot. DHCP, saved Wi-Fi, saved configs and DNS come up before
+ anyone logs in (IP on the greeter, remote desktop reachable); sessions forward their `net-*`
+ actions over `/run/lordos/netd.sock`. It survives two users logging in and out, its own crash
+ (the DHCP lease is resumed without dropping the address) and a `lord-sessiond` restart (adopted
+ through a pidfd).
+- [x] **User folders:** the installer and Settings → Users create Escritorio, Documentos,
+ Descargas, Música, Imágenes and Videos in the user's language plus `user-dirs.dirs`
+ (`users/homedirs.c`, with `build/homedirs-test`).
+- [x] **Disks** (`apps/disks`): disks and partitions with usage, our own SMART reader (ATA over
+ `SG_IO`, NVMe health log; `build/smart-test`), mount/unmount/eject, format FAT32/exFAT/ext4/NTFS,
+ rename, erase, bootable USB from an ISO/IMG verified with SHA-256; closed `disk-*` actions that
+ never touch the system disk.
+- [x] **Backups** (`apps/backup`): scheduled hard-link snapshots of the home, hourly/daily/weekly
+ retention, browse by date and restore, exclusions, optional encryption with Monocypher; a
+ lord-server thread at nice 19 and idle I/O, paused on battery (`build/backup-test`).
+- [x] **Logs** (`apps/logs`): our own systemd journal reader, the user's own journal and LordOS
+ logs, system logs for admins through a closed action, filters, search, live follow and export
+ (`build/journal-test`).
+- [x] **Clock** (`apps/clock`): world clock with our own TZif reader (`build/tzif-test`), alarms that
+ fire with the app closed, timer and stopwatch, a menu-bar status item.
+- [x] **Help** (`apps/help`): searchable markdown articles in es/en/pt, a skippable welcome tour on
+ first login, links to Settings pages, indexed by Spotlight.
+- [x] **Session notifications** (`sdk/notify.js`) and **menu-bar status items**
+ (`sdk/statusitems.js`) for any theme.
+- [ ] **Pending:**
+ - install a new ISO to disk and repeat the network-before-login and user-folder checks there;
+ - test `lord-netd` with real NICs and Wi-Fi; a per-VPN "connect at boot" option;
+ - Disks: GPT for disks over 2 TiB, manual partitioning, LUKS/LVM, real NVMe;
+ - Backups: test pausing on a real laptop battery, store the passphrase in the Passwords keyring;
+ - Logs: zstd-compressed journal fields;
+ - RTL screenshots of the five apps.
+
+## M9 — Passwords and the system keyring ✅ (2026-10-18)
+
+Details in `PASSWORDS.md`. Tested on VM 116 with a real `lord-sessiond` session
+(`m9-contrasenas-*.png`).
+
+- [x] **`lord-vault`**, sandboxed helper (no network, no sockets, no exec, fd-only files); the only
+ binary with Monocypher; decrypted data in an mlock/MADV_DONTDUMP arena, wiped on lock.
+- [x] **Own `.lvault` format:** XChaCha20-Poly1305, vault key wrapped per unlock method (Argon2id
+ tuned per machine, BLAKE2b), attachments sealed separately, atomic save with `.bak`; every flipped
+ byte and every truncation detected (`vault-test`, 74/74).
+- [x] **Unlock:** master password, FIDO2 `hmac-secret` key (own CTAP2 client), key file on a USB
+ stick, password + key file, printable recovery key. Auto-lock on idle, ❖L and user switch.
+- [x] **App:** Apple-Passwords-style sidebar (All, Favorites, Archived, 2FA codes, Wi-Fi, Secure
+ notes, Cards, Security), KeePassX-style category tree with 16 built-in templates and user
+ categories with their own fields, tags, history, trash, attachments, rotation reminders, Wi-Fi QR,
+ TOTP with countdown (also from a QR image), generator, security report (offline breach check),
+ import (own KDBX 4/3.1 reader, Bitwarden, Chrome, Firefox, Apple) and export. Protected window.
+- [x] **Clipboard:** secrets marked sensitive (out of the history, `x-kde-passwordManagerHint` for
+ Wayland clients), cleared after 30 s.
+- [x] **Session keyring** (`login.lvault`) opened with the login password via `lord-sessiond`;
+ `keyring` API per app with sharing; Settings → Network stores Wi-Fi/VPN secrets there;
+ `<AutofillButton>`.
+- [x] **Secret Service** with our own D-Bus code (plain + DH sessions): `secret-tool` and Chromium
+ work without gnome-keyring.
+- [ ] Run the Passwords UI as an isolated process (app mode); today only `lord-vault` is sandboxed.
+- [ ] Test with real FIDO2 keys (only the uhid software authenticator was available).
+
## Pendiente antes del ISO final
- [ ] **Mail, Calendario, Contactos y Recordatorios** (estilo Outlook; cuentas IMAP/SMTP, CalDAV y
@@ -356,7 +423,10 @@ Detalle en `MEDIOS.md`. Probado en la VM 119 con capturas (`m9-media-*.png`).
- [ ] **Secciones de Ajustes que faltan:** Pantallas, Bluetooth, Energía, Notificaciones, Fecha y
hora, Apps por defecto.
- [ ] **Chromium y Firefox** preinstalados (apps Linux, no nativas).
-- [ ] **Cámara en apps aisladas** (`.lpk`) y **varias ventanas por app aislada**.
+- [x] **Cámara en apps aisladas** (`.lpk`) y **varias ventanas por app aislada** (VM 122,
+ `PRIVACIDAD.md`): read-only frame ring from `lord-media` with validated ACKs, photo/video through
+ the powerbox, instant revoke; one Wayland toplevel per window, grouped in the Dock, «New
+ window» from the app and the Dock.
- [ ] **Pulido visual estilo Apple, app por app** (antes del ISO): revisar todas las apps nativas
(Ajustes, Archivos, Terminal, Store, Editor, Notas, Calculadora, Monitor, PDF, Tipografías,
Emojis, Escáner, Fotos, Reproductor, Capturas, Cámara, Grabadora, Contraseñas, Discos, Copias,
diff --git a/docs/SESIONES.md b/docs/SESIONES.md
index 14396a7..68e97eb 100644
--- a/docs/SESIONES.md
+++ b/docs/SESIONES.md
@@ -16,7 +16,7 @@ LordOS tiene su propio administrador de sesiones, `lord-sessiond`. Hace lo mismo
```
lordos.service (root)
└── lord-sessiond principal: config, lista de sesiones, contraseñas, monitor
- ├── lord-netd (netsup.c) la red del sistema, desde el arranque (RED.md); lo relanza si termina
+ ├── lord-netd (netsup.c) the system network, from boot (RED.md); restarted if it exits
├── conexiones web (conn.c) un hijo por navegador; pasa a ser el usuario (REMOTO.md)
└── trabajadores hijos cortos: verificar contraseña, crear la sesión
lord-server --greeter --user lordos-greeter pantalla de ingreso (tema themes/greeter)
@@ -166,10 +166,9 @@ primeros no esperan; después la espera es de 1, 2, 4… segundos, hasta 5 minut
- **Reinicio de `lord-sessiond`:**
- las sesiones siguen vivas (`KillMode=process`), y al volver se entra de nuevo por la
pantalla de ingreso;
- - `lord-netd` también sigue vivo y el `lord-sessiond` nuevo lo adopta: la red no se corta;
- - `lordos.service` lleva `DelegateSubgroup=supervisor`: sin eso, systemd no podía arrancar el
- principal nuevo mientras quedaban procesos vivos en el árbol delegado («Device or resource
- busy»);
+ - `lord-netd` keeps running too and the new `lord-sessiond` adopts it: the network is not cut;
+ - `lordos.service` has `DelegateSubgroup=supervisor`: without it, systemd couldn't start the new
+ main process while live processes remained in the delegated tree ("Device or resource busy");
- el inicio automático se aplica una sola vez por arranque del equipo
(`/run/lordos/autologin-done`), así que un reinicio del servicio no desbloquea una sesión
bloqueada.
@@ -191,6 +190,11 @@ corre sin root, así que `lord-sessiond` le **delega** un subárbol:
`lordos-session-<uid>/server`, se mete ahí y le cede el subárbol al usuario (`chown`).
- `lord-server` crea las scopes de sus apps como hermanas de `server`, sin root:
`app-lordos-lpk-<id>.scope` (apps `.lpk` aisladas) y `app-lordos-<id>.scope` (apps Linux).
+- **Update (root-owned scopes):** the subtree is no longer chowned to the user. The scopes are
+ created by `lord-sessiond` (a root child on `/run/lordos/cgroup.sock`, `remote/cgsup.c`) when
+ `lord-server`, or a child it forked right before exec, asks to be placed; all of them, and
+ every `cgroup.procs`, are root's. After a restart the new `lord-sessiond` hardens the subtrees
+ of the sessions that survived. See `PRIVACIDAD.md`, «Root-owned app scopes».
- La pantalla de ingreso y las conexiones web quedan en `supervisor`.
```
@@ -256,11 +260,11 @@ root:
- **Avatares:** quedan en `/var/lib/lordos/users/<u>.json` (el color) y `<u>.png` (la imagen).
La pantalla de ingreso los puede leer; la casa de cada usuario, no.
- **Usuario nuevo:**
- - se crea con las carpetas comunes en el idioma del sistema (Escritorio, Documentos, Descargas,
- Música, Imágenes y Videos; en inglés o portugués si ese es el idioma), su
- `~/.config/user-dirs.dirs` y `user-dirs.locale` (xdg-user-dirs), más `settings.json` y
- `locale.conf`. La lista está en un solo lugar, `server/src/users/homedirs.c`, y la usa también
- el instalador; es la misma de `lordos-live-prep`. Prueba: `build/homedirs-test`;
+ - it is created with the common folders in the system language (Escritorio, Documentos,
+ Descargas, Música, Imágenes and Videos; in English or Portuguese if that is the language), its
+ `~/.config/user-dirs.dirs` and `user-dirs.locale` (xdg-user-dirs), plus `settings.json` and
+ `locale.conf`. The list lives in one place, `server/src/users/homedirs.c`, which the installer
+ uses too; it matches `lordos-live-prep`. Test: `build/homedirs-test`;
- el nombre de usuario se sugiere a partir del nombre completo.
## Seguridad
@@ -268,7 +272,7 @@ root:
| Proceso | Corre como | Qué puede |
|-----------------------------------|-----------------|------------------------------------------------------------------|
| `lord-sessiond` (principal) | root | lee shadow, abre y presta la placa y la entrada, crea sesiones, reinicia; no lee píxeles |
-| `lord-netd` | root | solo las acciones `net-*` de `admin.c` (RED.md); habla solo con los ayudantes root de las sesiones (`netd.sock` 0600) |
+| `lord-netd` | root | only the `net-*` actions of `admin.c` (RED.md); talks only to the sessions' root helpers (`netd.sock` 0600) |
| pantalla de ingreso | `lordos-greeter` | dibujar y pedir; sin ayudante de administración ni acceso a casas |
| sesión | el usuario | lo de siempre (el ayudante `admin.c` con su lista cerrada); la placa y la entrada solo mientras está en el monitor |
| conexión web | root → usuario | suelta root apenas sabe de quién es la sesión (REMOTO.md) |
@@ -292,9 +296,9 @@ root:
| `server/src/remote/mirror.c` | lado de la sesión: visores, monitor prestado, tamaño, pedidos |
| `server/src/remote/proto.h` | el protocolo local |
| `server/src/users/users_admin.c` | acciones `user-*` |
-| `server/src/users/homedirs.c` | carpetas comunes y `user-dirs.dirs` (Usuarios y el instalador) |
-| `server/src/remote/netsup.c` | lanza, vigila y adopta a `lord-netd` (RED.md) |
-| `/run/lordos/netd.sock`, `netd.pid`, `netd.enabled` | la red del sistema (RED.md) |
+| `server/src/users/homedirs.c` | common folders and `user-dirs.dirs` (Users and the installer) |
+| `server/src/remote/netsup.c` | starts, supervises and adopts `lord-netd` (RED.md) |
+| `/run/lordos/netd.sock`, `netd.pid`, `netd.enabled` | the system network (RED.md) |
| `server/src/sec/cgroup.c` | subárbol de cgroup por sesión y scopes por app (`Delegate=yes`) |
| `themes/greeter/` | la pantalla de ingreso |
| `apps/settings/Users.jsx` | Ajustes → Usuarios |
diff --git a/docs/SISTEMA.md b/docs/SISTEMA.md
deleted file mode 100644
index 0122c22..0000000
--- a/docs/SISTEMA.md
+++ /dev/null
@@ -1,606 +0,0 @@
-# Apps del sistema (M9)
-
-Las apps nativas del sistema que vienen preinstaladas con LordOS: **Discos**, **Copias de
-seguridad**, **Registros**, **Reloj** y **Ayuda**. Todas usan `t()` con es/en/pt, funcionan de
-derecha a izquierda y tienen su propio ícono. Lo que necesita root pasa por acciones cerradas de
-`admin.c`, con argumentos validados del lado root y programas de ruta fija.
-
-## Discos (`apps/disks`)
-
-La utilidad de discos de LordOS, como Utilidad de Discos de macOS o GNOME Discos.
-
-- **A la izquierda:** los discos agrupados en Internos, Externos (USB y tarjetas) e Imágenes
- (dispositivos `loop` con un archivo detrás), cada uno con sus particiones. Un punto marca las
- que están montadas.
-- **A la derecha:**
- - una barra de uso: las particiones del disco a escala, o lo usado y lo libre de una partición
- montada;
- - las acciones;
- - los datos: dispositivo, modelo, número de serie, capacidad, conexión, tipo, tabla de
- particiones, sistema de archivos, etiqueta, UUID, punto de montaje;
- - la tarjeta **Salud del disco (SMART)**.
-- **Actualización sin sondeos:** la lista se renueva sola al montar, desmontar, enchufar o
- formatear.
-
-| | |
-|---|---|
-| ![discos](m9-sistema-discos.png) | ![salud](m9-sistema-discos-smart.png) |
-| Un pendrive (USB) con su partición exFAT montada | Salud del disco SATA: SMART propio por SG_IO, con los atributos |
-| ![formatear](m9-sistema-discos-formatear.png) | ![borrar](m9-sistema-discos-confirmar.png) |
-| Formatear: FAT32, exFAT, ext4 o NTFS (si está `mkfs.ntfs`), con la etiqueta | La confirmación dice qué se borra y pide escribir el nombre del disco |
-| ![usb de arranque](m9-sistema-discos-usb-arranque.png) | ![verificado](m9-sistema-discos-usb-verificado.png) |
-| Crear un USB de arranque: copiando, con «Cancelar» | Copiado y verificado (SHA-256 releyendo el disco); la partición de la imagen aparece sola |
-
-### Cómo está hecho
-
-| Pieza | Qué hace |
-|---|---|
-| `server/src/disk/disk.c` | Lista sin root, desde tres fuentes. **`/sys/block`:** tamaño, extraíble, solo lectura, rotacional, modelo. **La base de udev** (`/run/udev/data/b<mayor>:<menor>`): sistema de archivos, etiqueta, UUID, tabla de particiones y bus; ya lo probó udev, así que no se abre el dispositivo. **`/proc/self/mountinfo`:** dónde está montado cada uno. También reconoce el disco del sistema y escucha los cambios. |
-| `server/src/disk/smart.c` | Analizadores de SMART de ATA y del registro de salud de NVMe: funciones puras, sin E/S |
-| `server/src/disk/disk_admin.c` | Las acciones `disk-*` del ayudante (root) |
-| `server/src/ui/js_disk.c`, `sdk/disks.js` | `lord.disks.list()`, `tools()`, `watch(on)`; en el SDK, `useDisks()` y `disks` |
-| `apps/disks/` | La app: `index.jsx`, `health.jsx` (SMART), `dialogs.jsx` (formatear, renombrar, borrar, USB de arranque), `icons.jsx` |
-
-**Avisos sin sondeo.** Mientras la app está abierta (`useDisks`), `lord.disks.watch(true)` abre un
-epoll con dos cosas. Ese único fd va al bucle principal de `lord-server` (`main.c`), y JS recibe
-`__lordDisks('change')`, juntado en uno cada 150 ms. Al cerrar la app se cierra todo.
-
-- `/proc/self/mountinfo`, que avisa con `POLLPRI` cuando cambian los montajes.
-- Un socket `NETLINK_KOBJECT_UEVENT` en el grupo de udev (2). Cuando llega el aviso, udev ya
- terminó de actualizar su base.
-
-`mountinfo` tiene una trampa: su aviso se gasta al consultarlo, y el `poll` del bucle sobre el
-epoll ya lo consume, así que `epoll_wait` después no lo informa. Por eso, con cada aviso se compara
-una huella del contenido de mountinfo (unos KB) con la anterior.
-
-### Acciones (`admin.run('disk-…', arg)`)
-
-Todas están en la tabla cerrada de `admin.c` (macro `DISK_ADMIN_ACTIONS` en `disk/disk.h`).
-
-| Acción | Argumento | Qué hace |
-|---|---|---|
-| `disk-smart` | `disco` | Lee la salud. `LOG smart {…}` (resumen), un `LOG attr {…}` por atributo ATA y `OK <ms>` |
-| `disk-mount` | `dispositivo` | Monta en `/media/<usuario>/<etiqueta>` con `mount(2)`: `nosuid,nodev`, y en FAT, exFAT y NTFS (`ntfs3`) con `uid=`/`gid=` del usuario. ISO 9660 y UDF van de solo lectura. `OK <carpeta>` |
-| `disk-unmount` | `dispositivo` o `disco` | Desmonta lo que está en `/media` o `/run/media` (`umount2`) y borra la carpeta vacía |
-| `disk-eject` | `disco` | Desmonta todo, vacía cachés (`BLKFLSBUF`) y manda `START STOP UNIT` (expulsar). Por USB además apaga el dispositivo (`/sys/block/<d>/device/delete`), como «Apagar» de GNOME Discos |
-| `disk-format` | `dispositivo\nfat32\|exfat\|ext4\|ntfs\netiqueta` | **Disco entero:** borra las firmas (el primer y el último MiB) y escribe una tabla MBR propia con una partición desde 1 MiB. Una imagen `loop` sin `partscan` lo recibe. Después corre el `mkfs` de ruta fija. En ext4 la raíz queda del usuario (`-E root_owner=uid:gid`) |
-| `disk-label` | `partición\netiqueta` | `fatlabel`, `exfatlabel`, `e2label` o `ntfslabel`. FAT, exFAT y NTFS tienen que estar desmontados |
-| `disk-erase` | `dispositivo\nquick\|zero` | `quick`: borra las firmas (primer y último MiB) y relee la tabla. `zero`: escribe ceros en todo, con progreso y cancelable |
-| `disk-write-image` | `disco\nruta` | Copia una imagen ISO/IMG al disco entero y la verifica |
-| `disk-cancel` | `disco` | Corta un `zero` o una copia en curso. Solo quien la empezó, o un administrador |
-
-Las acciones largas mandan `LOG progress phase=<table|mkfs|erase|write|verify> done=<n> total=<n>`,
-y la app lo muestra como barra.
-
-### Seguridad
-
-- **Las mismas reglas para todas, del lado root (`target()` en `disk_admin.c`):**
- - el nombre tiene que ser un dispositivo de bloque real (`sd*`, `vd*`, `hd*`, `xvd*`, `nvme*`,
- `mmcblk*`, `loop*`, solo minúsculas y dígitos);
- - `/dev/<nombre>` se comprueba con `lstat`: de bloque y con el mismo número mayor:menor que
- sysfs;
- - una acción para «disco entero» rechaza particiones, y al revés.
-- **El disco del sistema nunca se toca** (`disk_is_system`). Es el disco de cualquier partición que
- aloje `/`, `/usr`, `/var`, `/home`, `/boot`, `/boot/efi`, `/efi`, el medio del live
- (`/run/live/medium`…) o una swap activa. Si es un dm/md (LVM, LUKS, RAID), se baja por `slaves/`
- hasta los discos de verdad. Solo `disk-smart` lo acepta, porque solo lee.
-- **Quién puede:**
- - los discos internos, solo un administrador (grupo `sudo`);
- - los extraíbles (USB, `removable=1`, tarjetas `mmc`), cualquier usuario de la sesión, como
- udisks con las sesiones activas;
- - leer SMART, cualquiera.
-- **Solo se desmonta lo de `/media` y `/run/media`.** Si algo está montado en otro lado, la acción se
- niega. Formatear, borrar y copiar abren el dispositivo con `O_EXCL`: si sigue en uso (montado o
- abierto por otro programa), el kernel responde `EBUSY` y no se hace nada. `disk-eject` tampoco
- expulsa con un borrado o una copia en curso.
-- **Programas de ruta fija, sin shell:**
- - `/usr/sbin/mkfs.fat`, `/usr/sbin/mkfs.exfat`, `/usr/sbin/mkfs.ext4` y `/usr/sbin/mkfs.ntfs`;
- - `/usr/sbin/fatlabel`, `/usr/sbin/exfatlabel`, `/usr/sbin/e2label` y `/usr/sbin/ntfslabel`;
- - `/usr/bin/udevadm settle`.
-
- Las etiquetas se validan por formato y no pueden empezar con `-`:
- - FAT32: hasta 11 caracteres, `A-Z 0-9 espacio _ -`, en mayúsculas;
- - exFAT: hasta 15;
- - ext4: hasta 16 bytes;
- - NTFS: hasta 32;
- - en todos, sin caracteres de control ni `/ \ : * ? " < > |`.
-
- Montar, desmontar, particionar, borrar, copiar y expulsar son llamadas al sistema: no se lanza
- ningún programa.
-- **La imagen se lee con los permisos del usuario.**
- - El ayudante hace `setfsuid`/`setfsgid` al usuario antes de `realpath` y `open`
- (`O_NOFOLLOW`). Root no lee nada que el usuario no pudiera leer.
- - Solo acepta archivos regulares de la carpeta personal, de `/media/<usuario>` o de
- `/run/media/<usuario>`. Un enlace a `/etc/shadow` o un `..` se rechazan (probado).
- - Tampoco acepta una imagen que esté en el mismo disco que se va a escribir.
-- **Verificación.**
- - Se calcula el SHA-256 (`pkg/crypto.c`) mientras se copia, con `O_DIRECT`, y se hace `fsync`.
- - Después se vacía la caché (`BLKFLSBUF`), se relee el disco con `O_DIRECT` y se compara.
- - El resultado trae el hash, para compararlo con el que publica la distribución.
-- **Para que el escritorio no se trabe:** borrar con ceros y copiar una imagen bajan su prioridad
- (`nice 10` e `ioprio` best-effort 7). La copia usa `O_DIRECT`, para no llenar la caché de páginas
- sucias. El borrado hace `fdatasync` cada medio segundo.
-- **Cancelar.** El trabajo deja `/run/lordos/disk-<disco>.job` con su pid y su uid. `disk-cancel`
- verifica que ese pid sea un `lord-admin` (y no un pid reciclado) y que lo pida el mismo usuario o
- un administrador.
-- **La confirmación de la app:** todo lo que borra (formatear, borrar, USB de arranque) termina en
- el mismo paso.
- - Dice exactamente qué se pierde: disco, modelo y tamaño, y cada partición con su nombre,
- etiqueta, sistema de archivos, tamaño, dónde está montada y cuántos datos tiene.
- - Para el disco entero hay que escribir su nombre (`sdc`).
- - El botón rojo no responde hasta que coincide.
- - De todas formas, la validación de verdad es la del lado root.
-
-### SMART: lectura propia por ioctl (y no smartctl)
-
-Se eligió leerlo con código propio:
-
-- **Sin dependencias ni programas externos.** La política de dependencias pide no agregar
- programas si se puede evitar, y `smartmontools` (`smartctl`) traería otro binario de root con
- su base de discos.
-- **Lo necesario es poco:** tres comandos y dos formatos de 512 bytes, bien definidos.
-- **El análisis queda en funciones puras con prueba propia:** los datos que manda el disco son
- datos de afuera.
-
-| Disco | Cómo se lee (en el ayudante, root) |
-|---|---|
-| SATA / ATA (`sd*`, `hd*`) | `SG_IO` con **ATA PASS-THROUGH (16)** (`0x85`). Tres comandos: **SMART READ DATA** (`B0h/D0h`, PIO de entrada, 1 sector); **READ THRESHOLDS** (`D1h`); **RETURN STATUS** (`DAh`, sin datos, con `ck_cond`). Este último se lee del descriptor «ATA Status Return» (`09h`) del sense: LBA mid/high `4Fh/C2h` = bien, `F4h/2Ch` = umbral superado |
-| NVMe (`nvme*`) | `NVME_IOCTL_ADMIN_CMD`: Get Log Page `02h` (SMART / Health Information), 512 bytes |
-
-El análisis (`smart.c`, probado en `tests/smart_test.c`):
-
-- **ATA:**
- - los 30 atributos de 12 bytes, con su crudo de 48 bits y su umbral;
- - la suma de comprobación;
- - temperatura (194, o 190 si no está), horas (9), encendidos (12), reasignados (5), pendientes
- (197) e incorregibles (198).
-- **Salud ATA:**
- - **falla** si RETURN STATUS dice umbral superado, o si un atributo *pre-falla* está en su umbral
- o debajo;
- - **advertencia** si hay sectores reasignados, pendientes o incorregibles, o si la suma no da;
- - si no, **bien**.
-
- Un atributo «de edad» (no pre-falla) bajo el umbral se muestra en rojo, pero no hace fallar.
-- **NVMe:**
- - lee advertencia crítica, temperatura (kelvin → °C), repuesto y su umbral, % de vida usada,
- datos leídos y escritos (unidades de 512 000 bytes), ciclos, horas, apagados inseguros y
- errores de medio;
- - los contadores son de 128 bits: si no entran en 64, se saturan;
- - **falla** con los bits de repuesto, confiabilidad o solo lectura;
- - **advertencia** con la temperatura, más del 100 % de vida usada, repuesto bajo el umbral o
- errores de medio.
-
-**Solo cuando se pide.** El botón «Comprobar salud» lee una vez y el resultado queda en memoria
-mientras la app está abierta. Nunca se lee en segundo plano: no se despierta un disco dormido ni se
-traba nada.
-
-Por USB, muchos adaptadores no dejan pasar ATA PASS-THROUGH, y la app lo explica. Los discos
-virtuales (virtio, loop) no tienen SMART.
-
-### Medido en la VM 119
-
-| | |
-|---|---|
-| Leer SMART (SATA de QEMU, ATA PASS-THROUGH: 3 comandos) | **0,4–0,6 ms** en el ayudante (`OK <ms>`); con el viaje de ida y vuelta por el ayudante, menos de un cuadro |
-| `lord.disks.list()` (4 discos, 5 particiones) | ~3 ms (100 listas en 0,58 s con el arranque del proceso de prueba incluido; el arranque solo, 1,3 ms) |
-| Avisos de cambios con la app cerrada | ningún fd ni timer |
-| Imagen de 300 MB a un pendrive USB emulado (`dummy_hcd` + `g_mass_storage`) | 4,8–5,6 s escribiendo (56–65 MB/s, con el SHA-256 al vuelo), más la verificación; 10,3 s en total |
-| SHA-256 propio | ~150 MB/s (4,1 s de CPU para 2 × 300 MB) |
-
-### Cómo se prueba
-
-```sh
-make -C server build/smart-test && ./server/build/smart-test # también lo corre `make -C server test`
-make -C server build/disk-cli
-./server/build/disk-cli list # lo mismo que lord.disks.list()
-sudo ./server/build/disk-cli -u lord -n disk-format 'sdc\nexfat\nPendrive' # -n: como no-administrador
-```
-
-`disk-cli` corre las acciones con un `admin_say` que imprime. Sirve para probar a mano: necesita
-root y dispositivos de verdad, así que no está en `make test`.
-
-En la VM 119 se probaron:
-
-- **Un pendrive USB de verdad para el kernel**, armado con `modprobe dummy_hcd` y
- `modprobe g_mass_storage file=/var/tmp/usb-disk-sistema-119.img removable=1`
- (`sdc`, `TRAN usb`, `RM 1`), como usuario no administrador:
- - formatear el disco entero en FAT32, exFAT (etiqueta con espacio y ñ), ext4 (la raíz queda del
- usuario) y NTFS;
- - montar y escribir en los cuatro;
- - montar dos veces (rechazado);
- - renombrar montado (rechazado en FAT) y desmontado;
- - borrar rápido, y con ceros con cancelación (que se niega a otro usuario);
- - expulsar con un borrado en curso (rechazado) y sin él (el dispositivo desaparece);
- - crear el USB de arranque desde `~/Descargas`: el SHA-256 coincide con `sha256sum` de la imagen
- y del disco, y la tabla de la imagen aparece;
- - las imágenes rechazadas: `/etc/shadow`, `../../etc/passwd`, un enlace a `/etc/shadow`, una
- imagen dentro del mismo pendrive, una partición como destino y el disco del sistema.
-- **El disco SATA de prueba** (`sdb`, de 8 GB, agregado como `sata1` en Proxmox; QEMU con AHCI
- responde SMART de ATA):
- - SMART: 7 atributos y RETURN STATUS «bien»;
- - como no administrador, formatear y borrar se rechazan.
-- **El disco del sistema** (`sda`, virtio-scsi):
- - formatear, borrar o desmontar se rechazan, también como administrador;
- - SMART responde «este disco no informa SMART», porque `scsi-hd` de QEMU no hace ATA
- PASS-THROUGH.
-
-### Paquetes
-
-| Paquete | Para qué | En el ISO |
-|---|---|---|
-| `dosfstools` | FAT32 (`mkfs.fat`, `fatlabel`) | ya está (el instalador usa `mkfs.vfat` para la partición EFI) |
-| `exfatprogs` | exFAT (`mkfs.exfat`, `exfatlabel`) | se agrega a la lista del ISO |
-| `e2fsprogs` | ext4 (`mkfs.ext4`, `e2label`) | ya viene en Debian base |
-| `ntfs-3g` | NTFS (`mkfs.ntfs`, `ntfslabel`) | opcional: sin él, la app no ofrece NTFS |
-
-Para montar no hace falta ningún paquete: `vfat`, `exfat`, `ntfs3`, `ext4` e `iso9660` son módulos
-del kernel de Debian.
-
-### Pendiente
-
-- **Discos de más de 2 TiB:** la tabla propia es MBR. Hace falta escribir GPT (con su CRC32 y la
- copia al final).
-- **Particionar a mano:** crear, borrar y cambiar el tamaño de particiones. Hoy se formatea el disco
- entero con una partición, o una partición existente sin tocar su tipo en la tabla.
-- **LUKS, LVM y RAID:**
- - se ven sus discos, y si están debajo del sistema se protegen;
- - no se desbloquean ni se arman desde la app.
-- **Probar NVMe con un disco de verdad.** El análisis tiene prueba, pero en la VM no hay NVMe: Proxmox
- no lo ofrece sin `args`. Tampoco se probó SMART de USB con un adaptador que lo deje pasar (SAT).
-- **Autotest de SMART** (corto/largo) y el historial de la salud.
-- **Elegir la imagen con el selector de archivos del sistema:** hoy hay una lista de las `.iso`/`.img`
- de la carpeta personal y un campo para la ruta.
-
-## Copias de seguridad (`apps/backup`)
-
-Copias programadas de la carpeta personal en un disco externo o una carpeta, como Time Machine.
-El motor es código propio (no usa rsync) y corre **como el usuario**, adentro de `lord-server`: para
-copiar la carpeta personal no hace falta root, así que no hay ninguna acción nueva en `admin.c`.
-
-| | |
-|---|---|
-| ![ajustes](m9-sistema-copias-ajustes.png) | ![progreso](m9-sistema-copias-progreso.png) |
-| Ajustes: destino (discos montados del usuario o una carpeta), frecuencia, batería y exclusiones | «Copiar ahora»: progreso por archivos y bytes, con Pausar y Detener |
-| ![explorar](m9-sistema-copias-explorar.png) | ![restaurado](m9-sistema-copias-restaurado.png) |
-| Las copias por fecha y el árbol de cada una | Restaurar un archivo borrado: aviso de la sesión al terminar |
-| ![cifrado](m9-sistema-copias-cifrado.png) | ![bloqueadas](m9-sistema-copias-bloqueadas.png) |
-| Activar el cifrado en un destino nuevo | Destino cifrado y bloqueado: la frase incorrecta se rechaza |
-
-### Cómo se guarda
-
-```
-<destino>/LordOS-Copias/<equipo>-<usuario>/
-├── 2026-10-17-235656/ una instantánea: la carpeta personal entera, tal cual
-├── 2026-10-18-001432/ lo que no cambió es un enlace duro a la anterior
-├── .inprogress-<sello>/ la copia en curso (se renombra al terminar)
-└── cifrado.json solo si el destino está cifrado: sal y verificador
-```
-
-- **Instantáneas con enlaces duros** (`server/src/backup/engine.c`): un archivo con el mismo
- tamaño, fecha de modificación y permisos que en la instantánea anterior se enlaza (`link`); si no,
- se copia (`copy_file_range`, o `read`/`write` entre sistemas de archivos). Cada instantánea se ve
- completa —se puede abrir en Archivos— pero ocupa solo lo que cambió. En FAT/exFAT (sin enlaces
- duros) cada copia ocupa todo: la app lo avisa al lado del disco.
-- **Atómica:** se escribe en `.inprogress-<sello>` y se renombra al final, después de `syncfs`.
- Cada archivo va primero a `<nombre>.bkpart~` y se renombra: un nombre final siempre es un archivo
- completo.
-- **Copias cortadas** (se apaga el equipo, se desenchufa el disco, «Detener»): la próxima copia
- toma el `.inprogress` que quedó como otra fuente de enlaces —no vuelve a copiar lo que ya estaba—
- y después lo borra. Si un archivo cambia mientras se copia, se vuelve a copiar (hasta 3 veces).
-- **Enlaces simbólicos:** se guardan como enlaces (el texto), nunca se siguen. El recorrido usa
- `lstat` y abre con `O_NOFOLLOW`; no cruza a otros sistemas de archivos (un disco montado adentro
- de la carpeta personal) y saltea fifos, sockets y dispositivos.
-- **Exclusiones:** siempre `.cache`, `.local/share/Trash`, `.local/share/lordos/apps`,
- `.local/share/lordos/trash` y `.thumbnails`, la propia carpeta `LordOS-Copias` si el destino está
- adentro de la carpeta personal (por dispositivo e inodo), y las carpetas que agrega el usuario
- (rutas relativas validadas: sin `..`, `/` inicial ni caracteres de control).
-
-### Retención
-
-`bk_retention` es una función pura (probada con fechas inventadas):
-
-- todas las instantáneas de las últimas 24 horas;
-- la última de cada día hasta 30 días;
-- la última de cada semana (de lunes a domingo, hora local) después;
-- la más nueva siempre queda.
-
-Si falta lugar (menos de 512 MiB libres antes de empezar, o `ENOSPC` durante la copia), se borran las
-más viejas, nunca la última, y se reintenta. Borrar una instantánea primero la renombra a
-`.deleting-<id>` (sale de la lista enseguida) y después la borra; solo adentro de la carpeta del
-equipo y con nombres validados (`AAAA-MM-DD-HHMMSS`).
-
-### Restaurar
-
-En la pestaña **Copias**: las instantáneas por día, el árbol de cada una (con los tamaños reales) y
-**Restaurar «archivo»**, **Restaurar esta carpeta** o **Restaurar todo** (con confirmación).
-
-- **No se pisa nada sin querer:** si el archivo actual es distinto, el de la copia se guarda al
- lado como «nombre (restaurado).ext» (y «… 2», «… 3»). Con «Reemplazar si existe», se reemplaza
- (escribiendo a un temporal y renombrando). Si es igual, no se hace nada.
-- **Las mismas reglas que `lord.fs`:** solo se escribe en la carpeta personal y los discos del
- usuario (`fsops_allowed`, con la carpeta ya resuelta), y nunca en lo protegido
- (`fsops_protected`: `~/.local/share/applications`, `~/.config/autostart`,
- `~/.local/share/lordos/apps`, `settings.json`, `permisos.json`, `backup.json`). Un `.desktop`
- plantado en una copia no se restaura; tampoco a través de un enlace de la carpeta personal que
- apunte a una carpeta protegida.
-- **Sin escapes por la copia:** la ruta pedida se valida (`bk_rel_valid`) y su carpeta resuelta
- tiene que seguir adentro de la instantánea.
-- **Restaurar todo** recupera la carpeta personal como estaba ese día; lo que cambió desde
- entonces queda al lado (o se reemplaza). Los archivos más nuevos no se borran.
-- «Abrir en Archivos» muestra la instantánea en Archivos (es una carpeta común, de solo lectura en
- la práctica).
-
-### Programación, prioridad y batería (`server/src/backup/backup.c`)
-
-- **Un hilo de `lord-server`**, no un proceso aparte: así no se agrega ninguna forma de ejecutar
- programas. El hilo se pone **nice 19** (`setpriority` sobre su propio tid) y **E/S «idle»**
- (`ioprio_set`, clase 3) y bloquea todas las señales. Lo copiado se suelta de la caché de páginas
- (`posix_fadvise(DONTNEED)`), así no desplaza lo que usa el escritorio.
-- **Sin sondeos:** el hilo duerme en `pthread_cond_timedwait` hasta la próxima copia (la de la
- instantánea más nueva + la frecuencia). La primera copia programada espera 5 minutos después de
- iniciar la sesión; después de un error, 15; si el disco no está, se vuelve a mirar cada 5 minutos.
-- **Batería:** con «Pausar con la batería» (viene prendido), si hay una batería descargándose y
- ninguna fuente de corriente conectada (`/sys/class/power_supply`), la copia no empieza o se
- pausa entre archivos, y vuelve a mirar cada 60 s. Mientras copia, la batería se lee cada 2 s.
-- **El estado llega solo a JS:** un `eventfd` en el bucle principal (`backup_fd`/`backup_dispatch`)
- llama a `__lordBackup(estado)` cuando cambia algo (a lo sumo dos veces por segundo con el
- progreso). La app no consulta.
-- **Avisos** (`sdk/notify.js`), aunque la app esté cerrada: si una copia falla; si termina bien una
- que se pidió con «Copiar ahora»; al terminar de restaurar; y una vez por sesión si las copias
- están cifradas y bloqueadas.
-- **Configuración:** `~/.config/lordos/backup.json` (`dest`, `interval`: `hourly|daily|weekly|manual`,
- `pauseOnBattery`, `encrypt`, `exclude`). Solo la escribe `lord.backup.configure`, que valida el
- destino (ruta real, en las raíces de `lord.fs`, escribible). Está en la lista de `fsops_protected`:
- decide a dónde van los datos, así que una app no la puede cambiar con `lord.fs.write`.
-
-### Cifrado (opcional)
-
-Con Monocypher 4.0.2 (vendorizado en `third_party/monocypher`, el mismo que usa Contraseñas; ver
-`server/src/backup/crypt.c`):
-
-- **Por archivo:** `LBK1` + nonce de 24 bytes + trozos de 64 KiB con XChaCha20-Poly1305. El nonce de
- cada trozo lleva su número y los datos asociados dicen si es el último: no se pueden cambiar,
- reordenar, quitar ni cortar trozos sin que falle la verificación. Restaurar escribe a un temporal
- y lo descarta si algo no verifica.
-- **La clave** sale de la frase con Argon2id (64 MiB, 3 pasadas, sal de 16 bytes por destino). En
- `cifrado.json` quedan la sal y un verificador (BLAKE2b con la clave), nunca la clave.
-- **Solo en memoria:** la clave vive en el proceso de la sesión (`mlock`), nunca en el disco. Al
- iniciar sesión las copias cifradas quedan **bloqueadas**: hay que escribir la frase en Ajustes
- (un aviso lo recuerda). Argon2 corre en el hilo de las copias, nunca en el compositor.
-- **Los enlaces duros siguen funcionando:** el tamaño de un archivo cifrado se calcula del
- original, así que lo que no cambió se enlaza igual.
-- **Qué no se cifra:** los nombres de archivos y carpetas, los textos de los enlaces simbólicos,
- los tamaños aproximados y las fechas.
-- Se activa solo en un destino sin copias (no se mezclan cifradas y sin cifrar). Si se pierde la
- frase, no hay forma de recuperar las copias.
-- **Pendiente:** guardar la frase en el llavero de la sesión (Contraseñas) para que las copias
- programadas no esperen a que el usuario la escriba.
-
-### API (`lord.backup`, `server/src/ui/js_backup.c`; en el SDK, `backup` y `useBackup()`)
-
-| Llamada | |
-|---|---|
-| `status()` / `useBackup()` | `{ state: idle\|running\|paused\|nodest\|restoring\|deleting\|locked\|unlocking, battery, userPause, dest, destAvailable, destFree, next, lastOk, progress: { files, totalFiles, bytes, totalBytes, file }, last: { ok, files, copied, linked, bytes, errors, secs, error }, restore: {…}, encrypted, destEncrypted, locked, unlock: {…} }` |
-| `config()` / `configure(obj)` | leer y guardar la configuración (valida en C) |
-| `runNow()`, `pause(on)`, `cancel()` | |
-| `list()` | `[{ id, time }]` |
-| `ls(id, rel)` | `[{ name, dir, link, size, mtime }]` (tamaños ya descifrados) |
-| `restore(id, rel, { replace, suffix, to })` | `rel` vacío: todo |
-| `remove(id)`, `path(id)` | borrar una instantánea; su ruta real para Archivos |
-| `unlock(frase, crear)`, `lock()` | cifrado |
-
-### Pruebas y medidas
-
-`make -C server test` → `build/backup-test` (`server/tests/backup_test.c`), **220 comprobaciones**:
-instantánea, exclusiones, fifo, enlaces simbólicos guardados como enlaces, el destino adentro de la
-carpeta personal, enlaces duros (mismo inodo), copia cortada a mitad de un archivo de 40 MB y
-retomada (lo ya copiado se enlaza, sin restos), restaurar (mantener los dos, numerar, reemplazar,
-crear carpetas, `.desktop` plantado, `settings.json`, escape por un enlace de la copia y de la
-carpeta personal, `..`, destino fuera de las raíces), poda por falta de lugar, retención con 90 días
-de copias por hora, y el cifrado (tamaños, ida y vuelta de 0 B a 1 MiB, byte alterado, trozos de
-menos, clave equivocada, frase incorrecta, instantánea cifrada con enlaces duros y restauración que
-descarta una copia alterada).
-
-Medido en la VM 119 (4 vCPU Xeon Silver 4108, disco virtio en SSD), copiando la carpeta personal
-(3,8 GB, 13 436 archivos) a una imagen ext4 en loop:
-
-| | |
-|---|---|
-| Primera copia completa | 24 s; el hilo usó 0,3 s de CPU de usuario y 8 s de sistema (≈34 % de un núcleo) |
-| Copia siguiente sin cambios | 1,0 s (13 403 enlazados, 29 copiados) |
-| Después de cambiar 1,8 GB | 12,8 s (42 copiados, 14 372 enlazados) |
-| Primera copia cifrada (1,8 GB, 10 704 archivos) | 18,3 s |
-| Latencia de despertar de un hilo cada 10 ms durante la copia | p50 0,1 ms, p99 0,2–2 ms (sin copia: p99 0,26 ms) |
-| Lectura de 64 KiB en frío durante la copia, con `mq-deadline` | p95 59–75 ms con prioridad idle, 121 ms sin ella |
-| Ídem con el planificador `none` (el de la VM) | p95 44–70 ms con idle, 61–74 ms sin ella: `none` no aplica prioridades |
-
-`ioprio` solo tiene efecto con un planificador que lo respete (`mq-deadline`, BFQ); con `none`
-(NVMe y la VM, por defecto) lo que protege al escritorio es nice 19, soltar la caché de páginas y
-que el hilo no compite con el compositor por CPU (despertar con p99 de 2 ms como mucho). Con
-`LORD_BACKUP_NOPRIO=1` en el entorno de la sesión se apagan nice e ioprio, solo para medir.
-
-### Pendiente
-
-- Probar «Pausar con la batería» en una notebook (en la VM no hay batería).
-- Avisar al conectar el disco de las copias (hoy se vuelve a mirar cada 5 minutos).
-- Guardar la frase del cifrado en el llavero de la sesión.
-- Versiones de un archivo (todas las copias de ese archivo, como «Entrar en Time Machine»).
-- El estado de RTL se revisó en el código (filas que el motor espeja, textos con `start`/`end`, la
- barra de progreso en `ltr`); no hay captura en árabe.
-
-<!-- SECCION:REGISTROS -->
-
-## Reloj (`apps/clock`)
-
-Reloj mundial, alarmas, temporizador y cronómetro, como el Reloj de macOS o GNOME Reloj.
-
-| Pestaña | Qué hace |
-|---|---|
-| Reloj mundial | La hora local y la de las ciudades que se agregan (buscador sobre `zone1970.tab` de tzdata), con una esfera analógica, «hoy/mañana/ayer», la diferencia en horas y la abreviatura de la zona (CEST, AEDT…) |
-| Alarmas | Hora, días en que se repite (o una sola vez), nombre, prender/apagar, editar y borrar. Muestra cuánto falta para la próxima |
-| Temporizador | Horas, minutos y segundos o atajos (1–30 min), pausar y seguir, barra de progreso |
-| Cronómetro | Vueltas con el parcial y el total; la más rápida en verde y la más lenta en rojo |
-
-### La hora de otra ciudad: un lector TZif propio
-
-Para la hora de otra ciudad no se toca la zona del proceso: `setenv("TZ")` cambiaría el `Date` de
-todo el tema (la barra, las otras apps). En su lugar:
-
-- `server/src/ui/tzif.c` lee los archivos TZif de `/usr/share/zoneinfo` (RFC 8536, versiones 1 a
- 4: el bloque de 64 bits, la búsqueda binaria de la transición y el pie con la regla POSIX TZ para
- las fechas después de la última transición) y evalúa reglas POSIX (`CET-1CEST,M3.5.0,M10.5.0/3`,
- `Jn`, `n`, `Mm.w.d`, horas negativas o de más de 24 h, nombres `<+0545>`).
-- **Validado:** el nombre de zona solo admite `[A-Za-z0-9/_+-]`, sin `..` ni `/` inicial; la ruta
- real (tzdata usa enlaces) tiene que quedar dentro de `/usr/share/zoneinfo/`; archivos regulares de
- hasta 1 MB; todos los conteos e índices del archivo se controlan antes de leer.
-- **JS:** `lord.time.zoneOffset(zona, segundosUnix)` → `{ offset, abbr, dst }` o `null`
- (`server/src/ui/js_help.c`, que lo agrega al `lord.time` de `js_sys.c`).
-- **Prueba** (`make -C server test` → `build/tzif-test`, `tests/tzif_test.c`): reglas POSIX con
- instantes conocidos (Europa, Australia, EE. UU., Nepal, zonas sin verano), un TZif v2 armado en
- la prueba con **todos sus prefijos truncados** (tienen que fallar sin leer de más) y un índice de
- tipo inválido, y la comparación con glibc (`localtime_r` con `TZ`) en 24 zonas difíciles
- (Lord Howe, Chatham, Casablanca, Gaza, Santiago, Kathmandu, St Johns…) cada ~3 días de 1970 a
- 2045: **216 168 instantes, 0 diferencias** en la VM 119.
-
-### Alarmas con la app cerrada (`sdk/alarms.js`)
-
-Las alarmas, el temporizador y el cronómetro viven en el SDK, no en la ventana: `startShell` llama
-a `startAlarms()` una vez por sesión. Así suenan con el Reloj cerrado y también con la sesión en
-segundo plano (cambio rápido de usuario o vista solo desde el navegador): la sesión de
-`lord-server` sigue corriendo y su JS también.
-
-- **Dónde se guardan:** `settings.clock = { alarms: [{ id, h, m, days, label, on, snooze, fired }],
- cities: [...] }` en `~/.config/lordos/settings.json`. `fired` es el instante de la última vez que
- sonó, para no repetirla al reiniciar la sesión.
-- **Sin sondeos:** un solo `setTimeout` hasta lo próximo que tiene que sonar (alarma, posposición o
- fin del temporizador). Se vuelve a programar cuando cambian las alarmas (suscripción a los ajustes).
-- **Cambios de hora y suspensión:** los timers de `lord-server` usan `CLOCK_MONOTONIC`, que no
- avanza suspendido. Por eso la espera se corta en tramos —1 minuto si algo suena dentro de la hora,
- 10 minutos si no— y en cada despertar se recalcula con la hora real. Lo que debió sonar hace menos
- de 10 minutos suena igual; lo más viejo se da por perdido (no suena una alarma de ayer al volver
- de una suspensión larga). Sin alarmas ni temporizador no hay ningún timer.
-- **Al sonar:** un [aviso](#avisos-de-la-sesión-sdknotifyjs) fijo con «Detener» y «Posponer 9 min»
- y el sonido `notify` de `lord.sound.play` cada 2,5 s durante un minuto o hasta que se toca el
- aviso. Las de una sola vez se apagan solas. El temporizador avisa igual, con «Repetir».
-- **Barra de menú:** `registerStatusItem('clock', …)` muestra ⏱ con lo que falta del temporizador
- (se redibuja cada segundo solo mientras corre) o ⏰ con la hora de la próxima alarma si suena en
- las próximas 24 h. Un clic abre el Reloj en esa pestaña.
-
-### Íconos de estado de la barra (`sdk/statusitems.js`)
-
-`registerStatusItem(id, Componente, orden)` y `<StatusItems color />`: un registro opcional para
-que las apps del sistema muestren algo en la barra del tema, como los "menu extras" de macOS. Los
-temas `default` (junto a los indicadores de privacidad) y `classic` (en la barra de tareas) lo
-dibujan; un tema que no lo dibuja simplemente no los muestra.
-
-### Avisos de la sesión (`sdk/notify.js`)
-
-LordOS no tenía avisos (solo el aviso corto del portapapeles). Ahora hay uno común para todas las
-apps, montado por `startShell`, así que se ve con cualquier tema:
-
-```js
-import { notify, dismissNotification, notifyHistory } from '@lordos/sdk';
-const id = notify({
- app: 'backup', // su ícono y su nombre (appName) en el aviso
- title: t('backup.notify.doneTitle'), // los textos llegan ya traducidos
- body: '1234 archivos',
- actions: [{ id: 'open', label: t('backup.notify.open'), primary: true, run: () => wm.open('backup') }],
- sound: true, // el sonido «notify» (lord.sound.play)
- sticky: false, timeout: 6000, // sticky: queda hasta que se toca una acción o la ×
- onClose: (motivo) => {}, // 'closed', 'action' o el id de la acción
-});
-dismissNotification(id);
-```
-
-- Arriba, del lado del final de la línea (a la derecha; a la izquierda en árabe o hebreo), debajo
- del `workArea` del tema; hasta cuatro a la vez, el más nuevo arriba.
-- Un clic en el aviso corre la primera acción; la × lo cierra.
-- `notifyHistory`: los últimos 50 de la sesión, solo en memoria.
-- Hasta tres acciones por aviso. La API queda estable: la usan el Reloj y las Copias de seguridad.
-
-### Capturas
-
-| | |
-|---|---|
-| ![reloj mundial](m9-sistema-reloj-mundial.png) | ![alarma](m9-sistema-reloj-alarma.png) |
-| Reloj mundial con varias ciudades | La alarma suena con el Reloj cerrado: aviso con Detener y Posponer, ⏰ en la barra |
-
-## Ayuda (`apps/help`)
-
-Ayuda y consejos de LordOS, como la app Consejos y el visor de ayuda de macOS.
-
-- **Artículos:** uno por cada app y por cada función (escritorio, ventanas, Spotlight,
- portapapeles, teclado y métodos de entrada, apps Linux, touchpad, red, VPN, usuarios y sesiones,
- escritorio remoto, privacidad, impresión, sonido, actualizaciones, ajustes, apariencia, idioma, y
- las apps del sistema). 44 artículos en `assets/help/{es,en,pt}/<id>.md`, escritos a partir de los
- documentos de `docs/`.
-- **Barra lateral** por secciones (Primeros pasos, El escritorio, Apps, Sistema, Ajustes), con el
- ícono de cada app, y **búsqueda** en títulos, palabras clave y texto, con un fragmento del
- resultado.
-- **Se dibuja con el `<Markdown>` del SDK** (el mismo de Notas): títulos, listas, tablas, código.
-- **Enlaces propios** dentro del texto: `[Ajustes → Red](settings:network)` abre esa sección de
- Ajustes (`wm.open('settings', { args: { section } })`, que Ajustes ya aceptaba);
- `[Archivos](app:files)` abre una app; `[VPN](help:vpn)` otro artículo. En el artículo de una app,
- un botón «Abrir <app>».
-- **Menú Ayuda** del tema `default`: «Ayuda de LordOS» y «Bienvenido a LordOS».
-
-### Formato de un artículo
-
-```markdown
----
-title: Reloj
-app: clock # la app que explica (botón «Abrir» e ícono)
-section: apps # start | desktop | apps | system | settings
-order: 41
-keywords: alarma, temporizador, cronómetro
----
-# Reloj
-
-Texto en markdown…
-```
-
-Si el idioma de la interfaz no tiene artículos, se usan los de inglés. Para agregar un idioma
-alcanza con copiar la carpeta y traducir.
-
-### Lectura: `lord.help` (`server/src/ui/js_help.c`)
-
-| Llamada | Devuelve |
-|---|---|
-| `lord.help.list(idioma)` | `[{ id, title, app, section, order, keywords }]` (el encabezado de cada `.md`) |
-| `lord.help.read(idioma, id)` | el texto del artículo o `null` |
-
-Solo lectura, igual que `lord.locale.catalog`: el idioma y el id solo admiten `[a-z0-9-]` (sin
-puntos ni barras), así que no se sale de `<assets>/help/`; `O_NOFOLLOW`, archivos regulares de
-hasta 256 KB. En el SDK, `help` (`sdk/help.js`): `list`, `read`, `search`, `open(id)`,
-`startTour()` y `link(url)`.
-
-### Spotlight
-
-`sdk/spotlight.js` tiene ahora un registro de fuentes, `registerSpotlightSource(id, fn)`. La Ayuda
-registra la suya: los artículos aparecen en la sección «Ayuda» con un fragmento en la vista previa,
-y Enter abre el artículo. El título de la sección sale de `shell.spotlight.section.<id>`.
-
-### «Bienvenido a LordOS»
-
-Un recorrido de seis pasos (bienvenida, el escritorio, Spotlight, Ajustes con botones a Apariencia,
-Red y Usuarios, las apps del sistema y dónde está la ayuda), con «Omitir», «Atrás» y «Siguiente».
-
-- Se abre solo **la primera vez** que se entra a la sesión: `startShell` llama a `maybeStartTour()`,
- que anota `welcomeShown: true` en los ajustes antes de abrirlo (aunque se cierre la ventana, no
- vuelve). En el sistema en vivo no aparece: ahí se abre el instalador.
-- Se vuelve a ver desde la barra lateral de Ayuda o desde el menú Ayuda.
-- Los textos están en `assets/locales/<idioma>/help.json` (`help.tour.<n>.title|body`).
-
-### Capturas
-
-| | |
-|---|---|
-| ![bienvenida](m9-sistema-ayuda-bienvenida.png) | ![artículo](m9-sistema-ayuda-articulo.png) |
-| «Bienvenido a LordOS» en el primer ingreso | Un artículo abierto desde Spotlight, con enlaces a otros artículos |
-| ![spotlight](m9-sistema-ayuda-spotlight.png) | |
-| Spotlight encuentra artículos de la Ayuda | |
-
-### Pendiente
-
-- Imágenes dentro de los artículos (el `<Markdown>` ya las dibuja; faltan capturas por idioma).
-- Un índice dentro de los artículos largos (`markdownHeadings` ya existe).
diff --git a/docs/SYSTEM.md b/docs/SYSTEM.md
new file mode 100644
index 0000000..5cb9d6b
--- /dev/null
+++ b/docs/SYSTEM.md
@@ -0,0 +1,611 @@
+# System apps (M9)
+
+The native system apps that ship preinstalled with LordOS: **Disks** (Discos), **Backups** (Copias
+de seguridad), **Logs** (Registros), **Clock** (Reloj) and **Help** (Ayuda). All of them use `t()`
+with es/en/pt, work right to left and have their own icon. Anything that needs root goes through
+closed `admin.c` actions, with arguments validated on the root side and programs at fixed paths.
+
+## Disks (`apps/disks`)
+
+The LordOS disk utility, like macOS Disk Utility or GNOME Disks.
+
+- **On the left:** disks grouped into Internal, External (USB and cards) and Images (`loop`
+ devices backed by a file), each with its partitions. A dot marks the mounted ones.
+- **On the right:**
+ - a usage bar: the disk's partitions to scale, or used and free space of a mounted partition;
+ - the actions;
+ - the details: device, model, serial number, capacity, connection, type, partition table, file
+ system, label, UUID, mount point;
+ - the **Disk health (SMART)** card.
+- **Refresh without polling:** the list updates by itself on mount, unmount, plug-in or format.
+
+| | |
+|---|---|
+| ![disks](m9-sistema-discos.png) | ![health](m9-sistema-discos-smart.png) |
+| A USB stick with its exFAT partition mounted | Health of the SATA disk: our own SMART over SG_IO, with the attributes |
+| ![format](m9-sistema-discos-formatear.png) | ![erase](m9-sistema-discos-confirmar.png) |
+| Format: FAT32, exFAT, ext4 or NTFS (if `mkfs.ntfs` is present), with the label | The confirmation says what gets erased and asks to type the disk name |
+| ![bootable usb](m9-sistema-discos-usb-arranque.png) | ![verified](m9-sistema-discos-usb-verificado.png) |
+| Create a bootable USB: copying, with "Cancel" | Copied and verified (SHA-256 by reading the disk back); the image's partition shows up on its own |
+
+### How it is built
+
+| Piece | What it does |
+|---|---|
+| `server/src/disk/disk.c` | The list, without root, from three sources. **`/sys/block`:** size, removable, read-only, rotational, model. **The udev database** (`/run/udev/data/b<major>:<minor>`): file system, label, UUID, partition table and bus; udev already probed them, so the device is never opened. **`/proc/self/mountinfo`:** where each one is mounted. It also recognizes the system disk and watches for changes. |
+| `server/src/disk/smart.c` | ATA SMART and NVMe health log parsers: pure functions, no I/O |
+| `server/src/disk/disk_admin.c` | The helper's `disk-*` actions (root) |
+| `server/src/ui/js_disk.c`, `sdk/disks.js` | `lord.disks.list()`, `tools()`, `watch(on)`; in the SDK, `useDisks()` and `disks` |
+| `apps/disks/` | The app: `index.jsx`, `health.jsx` (SMART), `dialogs.jsx` (format, rename, erase, bootable USB), `icons.jsx` |
+
+**Notifications without polling.** While the app is open (`useDisks`), `lord.disks.watch(true)`
+opens an epoll with two things. That single fd goes into the `lord-server` main loop (`main.c`),
+and JS gets `__lordDisks('change')`, coalesced into one every 150 ms. Closing the app closes
+everything.
+
+- `/proc/self/mountinfo`, which signals `POLLPRI` when mounts change.
+- A `NETLINK_KOBJECT_UEVENT` socket on the udev group (2). When the event arrives, udev has
+ already finished updating its database.
+
+`mountinfo` has a catch: its event is consumed by polling it, and the main loop's `poll` on the
+epoll already consumes it, so `epoll_wait` afterwards does not report it. So on every event a
+fingerprint of the mountinfo content (a few KB) is compared with the previous one.
+
+### Actions (`admin.run('disk-…', arg)`)
+
+All are in the closed table of `admin.c` (macro `DISK_ADMIN_ACTIONS` in `disk/disk.h`).
+
+| Action | Argument | What it does |
+|---|---|---|
+| `disk-smart` | `disk` | Reads health. `LOG smart {…}` (summary), one `LOG attr {…}` per ATA attribute and `OK <ms>` |
+| `disk-mount` | `device` | Mounts at `/media/<user>/<label>` with `mount(2)`: `nosuid,nodev`, and on FAT, exFAT and NTFS (`ntfs3`) with the user's `uid=`/`gid=`. ISO 9660 and UDF are read-only. `OK <folder>` |
+| `disk-unmount` | `device` or `disk` | Unmounts whatever is under `/media` or `/run/media` (`umount2`) and removes the empty folder |
+| `disk-eject` | `disk` | Unmounts everything, flushes caches (`BLKFLSBUF`) and sends `START STOP UNIT` (eject). Over USB it also powers the device off (`/sys/block/<d>/device/delete`), like "Power Off" in GNOME Disks |
+| `disk-format` | `device\nfat32\|exfat\|ext4\|ntfs\nlabel` | **Whole disk:** wipes the signatures (first and last MiB) and writes our own MBR table with one partition from 1 MiB. A `loop` image without `partscan` gets it turned on. Then the fixed-path `mkfs` runs. On ext4 the root belongs to the user (`-E root_owner=uid:gid`) |
+| `disk-label` | `partition\nlabel` | `fatlabel`, `exfatlabel`, `e2label` or `ntfslabel`. FAT, exFAT and NTFS must be unmounted |
+| `disk-erase` | `device\nquick\|zero` | `quick`: wipes the signatures (first and last MiB) and rereads the table. `zero`: writes zeros everywhere, with progress, cancellable |
+| `disk-write-image` | `disk\npath` | Copies an ISO/IMG image to the whole disk and verifies it |
+| `disk-cancel` | `disk` | Stops a `zero` erase or a copy in progress. Only whoever started it, or an administrator |
+
+Long actions send `LOG progress phase=<table|mkfs|erase|write|verify> done=<n> total=<n>`, which
+the app shows as a bar.
+
+### Security
+
+- **The same rules for all of them, on the root side (`target()` in `disk_admin.c`):**
+ - the name must be a real block device (`sd*`, `vd*`, `hd*`, `xvd*`, `nvme*`, `mmcblk*`,
+ `loop*`, lowercase letters and digits only);
+ - `/dev/<name>` is checked with `lstat`: a block device with the same major:minor as sysfs;
+ - a "whole disk" action refuses partitions, and vice versa.
+- **The system disk is never touched** (`disk_is_system`). It is the disk of any partition that
+ holds `/`, `/usr`, `/var`, `/home`, `/boot`, `/boot/efi`, `/efi`, the live medium
+ (`/run/live/medium`…) or an active swap. For a dm/md (LVM, LUKS, RAID), `slaves/` is followed
+ down to the real disks. Only `disk-smart` accepts it, because it only reads.
+- **Who can:**
+ - internal disks, only an administrator (group `sudo`);
+ - removable ones (USB, `removable=1`, `mmc` cards), any session user, like udisks with active
+ sessions;
+ - reading SMART, anyone.
+- **Only `/media` and `/run/media` are unmounted.** If something is mounted elsewhere, the action
+ refuses. Format, erase and the image copy open the device with `O_EXCL`: if it is still in use
+ (mounted or opened by another program), the kernel answers `EBUSY` and nothing is done.
+ `disk-eject` does not eject with an erase or a copy in progress either.
+- **Fixed-path programs, no shell:**
+ - `/usr/sbin/mkfs.fat`, `/usr/sbin/mkfs.exfat`, `/usr/sbin/mkfs.ext4` and `/usr/sbin/mkfs.ntfs`;
+ - `/usr/sbin/fatlabel`, `/usr/sbin/exfatlabel`, `/usr/sbin/e2label` and `/usr/sbin/ntfslabel`;
+ - `/usr/bin/udevadm settle`.
+
+ Labels are validated per format and cannot start with `-`:
+ - FAT32: up to 11 characters, `A-Z 0-9 space _ -`, uppercased;
+ - exFAT: up to 15;
+ - ext4: up to 16 bytes;
+ - NTFS: up to 32;
+ - in all of them, no control characters and none of `/ \ : * ? " < > |`.
+
+ Mount, unmount, partition, erase, copy and eject are system calls: no program is launched.
+- **The image is read with the user's permissions.**
+ - The helper does `setfsuid`/`setfsgid` to the user before `realpath` and `open`
+ (`O_NOFOLLOW`). Root reads nothing the user could not read.
+ - It only accepts regular files from the home folder, `/media/<user>` or `/run/media/<user>`. A
+ link to `/etc/shadow` or a `..` is refused (tested).
+ - It also refuses an image stored on the disk that is about to be written.
+- **Verification.**
+ - The SHA-256 (`pkg/crypto.c`) is computed while copying, with `O_DIRECT`, followed by `fsync`.
+ - Then the cache is dropped (`BLKFLSBUF`), the disk is read back with `O_DIRECT` and compared.
+ - The result includes the hash, to compare with the one the distribution publishes.
+- **Keeping the desktop smooth:** zero erase and image copy lower their priority (`nice 10` and
+ best-effort `ioprio` 7). The copy uses `O_DIRECT` so it does not fill the page cache with dirty
+ pages. The erase calls `fdatasync` every half second.
+- **Cancelling.** The job leaves `/run/lordos/disk-<disk>.job` with its pid and uid.
+ `disk-cancel` checks that the pid is a `lord-admin` (not a recycled pid) and that the request
+ comes from the same user or an administrator.
+- **The app's confirmation:** everything that erases (format, erase, bootable USB) ends in the same
+ step.
+ - It says exactly what is lost: disk, model and size, and each partition with its name, label,
+ file system, size, mount point and how much data it holds.
+ - For a whole disk you have to type its name (`sdc`).
+ - The red button does nothing until it matches.
+ - Either way, the real validation is the one on the root side.
+
+### SMART: our own reader over ioctl (not smartctl)
+
+We chose to read it with our own code:
+
+- **No dependencies or external programs.** The dependency policy asks not to add programs when
+ avoidable, and `smartmontools` (`smartctl`) would bring another root binary with its drive
+ database.
+- **What is needed is small:** three commands and two well-defined 512-byte formats.
+- **The parsing stays in pure functions with their own test:** the data the disk sends is
+ outside data.
+
+| Disk | How it is read (in the helper, root) |
+|---|---|
+| SATA / ATA (`sd*`, `hd*`) | `SG_IO` with **ATA PASS-THROUGH (16)** (`0x85`). Three commands: **SMART READ DATA** (`B0h/D0h`, PIO data-in, 1 sector); **READ THRESHOLDS** (`D1h`); **RETURN STATUS** (`DAh`, non-data, with `ck_cond`). The last one is read from the "ATA Status Return" descriptor (`09h`) of the sense data: LBA mid/high `4Fh/C2h` = good, `F4h/2Ch` = threshold exceeded |
+| NVMe (`nvme*`) | `NVME_IOCTL_ADMIN_CMD`: Get Log Page `02h` (SMART / Health Information), 512 bytes |
+
+The parsing (`smart.c`, tested in `tests/smart_test.c`):
+
+- **ATA:**
+ - the 30 attributes of 12 bytes, with their 48-bit raw value and their threshold;
+ - the checksum;
+ - temperature (194, or 190 if missing), hours (9), power cycles (12), reallocated (5), pending
+ (197) and uncorrectable (198).
+- **ATA health:**
+ - **failing** if RETURN STATUS says threshold exceeded, or if a *pre-fail* attribute is at or
+ below its threshold;
+ - **warning** if there are reallocated, pending or uncorrectable sectors, or if the checksum
+ does not add up;
+ - otherwise **good**.
+
+ An "old-age" (non-pre-fail) attribute below its threshold is shown in red but does not make it
+ fail.
+- **NVMe:**
+ - reads critical warning, temperature (kelvin → °C), spare and its threshold, % life used, data
+ read and written (units of 512 000 bytes), cycles, hours, unsafe shutdowns and media errors;
+ - counters are 128-bit: if they don't fit in 64, they saturate;
+ - **failing** with the spare, reliability or read-only bits;
+ - **warning** with the temperature bit, more than 100 % life used, spare below its threshold or
+ media errors.
+
+**Only on request.** The "Check health" button reads once and the result stays in memory while
+the app is open. It is never read in the background: a sleeping disk is not woken up and nothing
+stalls.
+
+Over USB, many adapters don't pass ATA PASS-THROUGH, and the app explains that. Virtual disks
+(virtio, loop) have no SMART.
+
+### Measured on VM 119
+
+| | |
+|---|---|
+| Reading SMART (QEMU SATA, ATA PASS-THROUGH: 3 commands) | **0.4–0.6 ms** in the helper (`OK <ms>`); with the round trip through the helper, less than a frame |
+| `lord.disks.list()` (4 disks, 5 partitions) | ~3 ms (100 lists in 0.58 s including the test process start; the start alone, 1.3 ms) |
+| Change notifications with the app closed | no fd and no timer |
+| 300 MB image to an emulated USB stick (`dummy_hcd` + `g_mass_storage`) | 4.8–5.6 s writing (56–65 MB/s, with SHA-256 on the fly), plus the verification; 10.3 s in total |
+| Our own SHA-256 | ~150 MB/s (4.1 s of CPU for 2 × 300 MB) |
+
+### How to test it
+
+```sh
+make -C server build/smart-test && ./server/build/smart-test # `make -C server test` runs it too
+make -C server build/disk-cli
+./server/build/disk-cli list # the same as lord.disks.list()
+sudo ./server/build/disk-cli -u lord -n disk-format 'sdc\nexfat\nPendrive' # -n: as a non-administrator
+```
+
+`disk-cli` runs the actions with an `admin_say` that prints. It is for manual testing: it needs
+root and real devices, so it is not in `make test`.
+
+Tested on VM 119:
+
+- **A USB stick that is real for the kernel**, built with `modprobe dummy_hcd` and
+ `modprobe g_mass_storage file=/var/tmp/usb-disk-sistema-119.img removable=1`
+ (`sdc`, `TRAN usb`, `RM 1`), as a non-administrator user:
+ - format the whole disk as FAT32, exFAT (label with a space and ñ), ext4 (the root belongs to
+ the user) and NTFS;
+ - mount and write on all four;
+ - mounting twice (refused);
+ - renaming while mounted (refused on FAT) and unmounted;
+ - quick erase, and zero erase with cancellation (refused for another user);
+ - eject with an erase in progress (refused) and without one (the device disappears);
+ - create the bootable USB from `~/Descargas`: the SHA-256 matches `sha256sum` of the image and
+ of the disk, and the image's partition table shows up;
+ - the refused images: `/etc/shadow`, `../../etc/passwd`, a link to `/etc/shadow`, an image
+ inside the same stick, a partition as target and the system disk.
+- **The SATA test disk** (`sdb`, 8 GB, added as `sata1` in Proxmox; QEMU with AHCI answers ATA
+ SMART):
+ - SMART: 7 attributes and RETURN STATUS "good";
+ - as a non-administrator, format and erase are refused.
+- **The system disk** (`sda`, virtio-scsi):
+ - format, erase or unmount are refused, also as administrator;
+ - SMART answers "this disk does not report SMART", because QEMU's `scsi-hd` does not do ATA
+ PASS-THROUGH.
+
+### Packages
+
+| Package | For | In the ISO |
+|---|---|---|
+| `dosfstools` | FAT32 (`mkfs.fat`, `fatlabel`) | already there (the installer uses `mkfs.vfat` for the EFI partition) |
+| `exfatprogs` | exFAT (`mkfs.exfat`, `exfatlabel`) | added to the ISO list |
+| `e2fsprogs` | ext4 (`mkfs.ext4`, `e2label`) | already in Debian base |
+| `ntfs-3g` | NTFS (`mkfs.ntfs`, `ntfslabel`) | optional: without it, the app does not offer NTFS |
+
+Mounting needs no package: `vfat`, `exfat`, `ntfs3`, `ext4` and `iso9660` are Debian kernel
+modules.
+
+### Pending
+
+- **Disks over 2 TiB:** our table is MBR. GPT has to be written (with its CRC32 and the backup
+ at the end).
+- **Manual partitioning:** create, delete and resize partitions. Today the whole disk is
+ formatted with one partition, or an existing partition without changing its type in the table.
+- **LUKS, LVM and RAID:**
+ - their disks are shown, and protected if the system sits on them;
+ - they are not unlocked or assembled from the app.
+- **Test NVMe with a real disk.** The parser has a test, but the VM has no NVMe: Proxmox does not
+ offer it without `args`. SMART over a USB adapter that passes it through (SAT) was not tested
+ either.
+- **SMART self-test** (short/long) and health history.
+- **Pick the image with the system file picker:** today there is a list of the `.iso`/`.img` files
+ in the home folder and a field for the path.
+
+## Backups (`apps/backup`)
+
+Scheduled backups of the home folder to an external disk or a folder, like Time Machine. The
+engine is our own code (no rsync) and runs **as the user**, inside `lord-server`: backing up the
+home folder needs no root, so no new action was added to `admin.c`.
+
+| | |
+|---|---|
+| ![settings](m9-sistema-copias-ajustes.png) | ![progress](m9-sistema-copias-progreso.png) |
+| Settings: destination (the user's mounted disks or a folder), schedule, battery and exclusions | "Back Up Now": progress by files and bytes, with Pause and Stop |
+| ![browse](m9-sistema-copias-explorar.png) | ![restored](m9-sistema-copias-restaurado.png) |
+| Backups by date and the tree of each one | Restoring a deleted file: session notification when done |
+| ![encryption](m9-sistema-copias-cifrado.png) | ![locked](m9-sistema-copias-bloqueadas.png) |
+| Turning on encryption for a new destination | Encrypted and locked destination: a wrong passphrase is rejected |
+
+The screenshots were taken before the backup folder was renamed from `LordOS-Copias` to
+`LordOS-Backups`.
+
+### On-disk layout
+
+```
+<destination>/LordOS-Backups/<host>-<user>/
+├── 2026-10-17-235656/ a snapshot: the whole home folder, as it was
+├── 2026-10-18-001432/ what did not change is a hard link to the previous one
+├── .inprogress-<stamp>/ the run in progress (renamed when it finishes)
+└── encryption.json only if the destination is encrypted: salt and key check
+```
+
+- **Hard-linked snapshots** (`server/src/backup/engine.c`): a file with the same size,
+ modification time and mode as in the previous snapshot is hard-linked (`link`); otherwise it is
+ copied (`copy_file_range`, or `read`/`write` across filesystems). Every snapshot looks complete
+ (it can be opened in Files) but only takes the space of what changed. On FAT/exFAT (no hard
+ links) every backup takes full space; the app warns about it next to the disk.
+- **Atomic:** a run writes to `.inprogress-<stamp>` and renames it at the end, after `syncfs`.
+ Each file is first written to `<name>.bkpart~` and renamed, so a final name is always a complete
+ file.
+- **Interrupted runs** (power off, unplugged disk, "Stop"): the next run uses the leftover
+ `.inprogress` as another link source (what was already copied is not copied again) and then
+ deletes it. A file that changes while being copied is copied again (up to 3 times).
+- **Symbolic links** are stored as links (their text) and never followed. The walk uses `lstat`
+ and opens with `O_NOFOLLOW`; it does not cross into other filesystems (a disk mounted inside the
+ home folder) and skips fifos, sockets and devices.
+- **Exclusions:** always `.cache`, `.local/share/Trash`, `.local/share/lordos/apps`,
+ `.local/share/lordos/trash` and `.thumbnails`; the `LordOS-Backups` folder itself when the
+ destination is inside the home folder (by device and inode); and the folders the user adds
+ (validated relative paths: no `..`, leading `/` or control characters).
+
+### Retention
+
+`bk_retention` is a pure function (tested with made-up dates):
+
+- every snapshot from the last 24 hours;
+- the newest of each day up to 30 days;
+- the newest of each week (Monday to Sunday, local time) after that;
+- the newest snapshot always stays.
+
+When space runs low (less than 512 MiB free before starting, or `ENOSPC` while copying), the
+oldest snapshots are deleted, never the newest, and the copy is retried. Deleting a snapshot first
+renames it to `.deleting-<id>` (it leaves the list at once) and then removes it; only inside the
+machine folder and with validated names (`YYYY-MM-DD-HHMMSS`).
+
+### Restore
+
+In the **Backups** tab: snapshots by day, the tree of each one (with real sizes), and
+**Restore "file"**, **Restore This Folder** or **Restore All** (with confirmation).
+
+- **Nothing is overwritten by accident:** if the current file differs, the backed-up one is saved
+ next to it as "name (restored).ext" (then "… 2", "… 3"; the suffix is translated). With
+ "Replace if it exists" it is replaced (written to a temporary file and renamed). If it is
+ identical, nothing happens.
+- **The same rules as `lord.fs`:** it only writes in the home folder and the user's disks
+ (`fsops_allowed`, on the resolved folder), never in protected places (`fsops_protected`:
+ `~/.local/share/applications`, `~/.config/autostart`, `~/.local/share/lordos/apps`,
+ `settings.json`, `permisos.json`, `backup.json`). A `.desktop` file planted in a backup is not
+ restored, not even through a link in the home folder that points to a protected folder.
+- **No escapes through the backup:** the requested path is validated (`bk_rel_valid`) and its
+ resolved folder must stay inside the snapshot.
+- **Restore All** brings the home folder back as it was that day; whatever changed since then is
+ kept alongside (or replaced). Newer files are not deleted.
+- "Open in Files" shows the snapshot in Files (it is a regular folder).
+
+### Scheduling, priority and battery (`server/src/backup/backup.c`)
+
+- **A `lord-server` thread**, not a separate process, so no new way to run programs is added. The
+ thread sets **nice 19** (`setpriority` on its own tid) and **idle I/O** (`ioprio_set`, class 3)
+ and blocks all signals. What it copies is dropped from the page cache
+ (`posix_fadvise(DONTNEED)`), so it does not evict what the desktop uses.
+- **No polling:** the thread sleeps in `pthread_cond_timedwait` until the next backup (newest
+ snapshot + interval). The first scheduled backup waits 5 minutes after the session starts;
+ after an error, 15; if the disk is missing, it checks again every 5 minutes.
+- **Battery:** with "Pause on battery" (on by default), if a battery is discharging and no power
+ source is connected (`/sys/class/power_supply`), the backup does not start, or pauses between
+ files, and checks again every 60 s. While copying, the battery is read every 2 s.
+- **The status is pushed to JS:** an `eventfd` in the main loop (`backup_fd`/`backup_dispatch`)
+ calls `__lordBackup(status)` when something changes (at most twice a second with progress). The
+ app never polls.
+- **Notifications** (`sdk/notify.js`), even with the app closed: when a backup fails; when a "Back
+ Up Now" run succeeds; when a restore finishes; and once per session when backups are encrypted
+ and locked.
+- **Configuration:** `~/.config/lordos/backup.json` (`dest`, `interval`:
+ `hourly|daily|weekly|manual`, `pauseOnBattery`, `encrypt`, `exclude`). Only
+ `lord.backup.configure` writes it, and it validates the destination (real path, inside the
+ `lord.fs` roots, writable). It is on the `fsops_protected` list: it decides where the data goes,
+ so an app cannot change it with `lord.fs.write`.
+- Errors that reach the UI as codes (`wrong-passphrase`, `not-encrypted`, `plain-backups-exist`,
+ `setup-failed`, `no-destination`, `locked`, `interrupted`) are translated by the app
+ (`backup.err.*`); other engine messages are in English.
+
+### Encryption (optional)
+
+With Monocypher 4.0.2 (vendored in `third_party/monocypher`, the same copy Passwords uses; see
+`server/src/backup/crypt.c`):
+
+- **Per file:** `LBK1` + a 24-byte nonce + 64 KiB chunks of XChaCha20-Poly1305. Each chunk's nonce
+ carries its number and the associated data says whether it is the last one: chunks cannot be
+ changed, reordered, removed or truncated without failing verification. Restore writes to a
+ temporary file and discards it if anything fails to verify.
+- **The key** is derived from the passphrase with Argon2id (64 MiB, 3 passes, a 16-byte salt per
+ destination). `encryption.json` stores the salt and a key check (BLAKE2b keyed with the key),
+ never the key.
+- **Memory only:** the key lives in the session process (`mlock`) and never on disk. At login,
+ encrypted backups are **locked**: the passphrase has to be entered in Settings (a notification
+ reminds the user). Argon2 runs in the backup thread, never in the compositor.
+- **Hard links still work:** an encrypted file's size is computed from the original's, so
+ unchanged files are still linked.
+- **Not encrypted:** file and folder names, symlink targets, approximate sizes and dates.
+- It can only be turned on for a destination without backups (encrypted and unencrypted backups
+ are never mixed). If the passphrase is lost, the backups cannot be recovered.
+- **Pending:** storing the passphrase in the session keyring (Passwords) so scheduled backups do
+ not wait for the user to type it.
+
+### API (`lord.backup`, `server/src/ui/js_backup.c`; in the SDK, `backup` and `useBackup()`)
+
+| Call | |
+|---|---|
+| `status()` / `useBackup()` | `{ state: idle\|running\|paused\|nodest\|restoring\|deleting\|locked\|unlocking, battery, userPause, dest, destAvailable, destFree, next, lastOk, progress: { files, totalFiles, bytes, totalBytes, file }, last: { ok, files, copied, linked, bytes, errors, secs, error }, restore: {…}, encrypted, destEncrypted, locked, unlock: {…} }` |
+| `config()` / `configure(obj)` | read and save the configuration (validated in C) |
+| `runNow()`, `pause(on)`, `cancel()` | |
+| `list()` | `[{ id, time }]` |
+| `ls(id, rel)` | `[{ name, dir, link, size, mtime }]` (sizes already decrypted) |
+| `restore(id, rel, { replace, suffix, to })` | empty `rel`: everything |
+| `remove(id)`, `path(id)` | delete a snapshot; its real path for Files |
+| `unlock(passphrase, create)`, `lock()` | encryption |
+
+### Tests and measurements
+
+`make -C server test` → `build/backup-test` (`server/tests/backup_test.c`), **220 checks**:
+snapshot, exclusions, fifo, symlinks stored as links, the destination inside the home folder, hard
+links (same inode), a run interrupted in the middle of a 40 MB file and resumed (already copied
+files are linked, no leftovers), restore (keep both, numbering, replace, creating folders, a
+planted `.desktop`, `settings.json`, escapes through a link in the backup and in the home folder,
+`..`, a destination outside the roots), pruning for space, retention over 90 days of hourly
+backups, and encryption (sizes, round trips from 0 B to 1 MiB, a tampered byte, missing chunks,
+the wrong key, a wrong passphrase, an encrypted snapshot with hard links, and a restore that
+discards a tampered backup).
+
+Measured on VM 119 (4 vCPU Xeon Silver 4108, virtio disk on SSD), backing up the home folder
+(3.8 GB, 13,436 files) to an ext4 image on a loop device:
+
+| | |
+|---|---|
+| First full backup | 24 s; the thread used 0.3 s of user CPU and 8 s of system CPU (≈34 % of one core) |
+| Next backup with no changes | 1.0 s (13,403 linked, 29 copied) |
+| After changing 1.8 GB | 12.8 s (42 copied, 14,372 linked) |
+| First encrypted backup (1.8 GB, 10,704 files) | 18.3 s |
+| Wakeup latency of a thread every 10 ms during the backup | p50 0.1 ms, p99 0.2–2 ms (no backup: p99 0.26 ms) |
+| Cold 64 KiB read during the backup, with `mq-deadline` | p95 59–75 ms at idle priority, 121 ms without it |
+| Same with the `none` scheduler (the VM's) | p95 44–70 ms at idle, 61–74 ms without: `none` ignores priorities |
+
+`ioprio` only has an effect with a scheduler that honours it (`mq-deadline`, BFQ); with `none`
+(NVMe and the VM, by default) what protects the desktop is nice 19, dropping the page cache and
+the thread not competing with the compositor for CPU (wakeup p99 of 2 ms at most). Setting
+`LORD_BACKUP_NOPRIO=1` in the session environment turns off nice and ioprio, for measuring only.
+
+### Pending
+
+- Test "Pause on battery" on a laptop (the VM has no battery).
+- Notice when the backup disk is plugged in (today it checks again every 5 minutes).
+- Store the encryption passphrase in the session keyring.
+- File versions (every backup of one file, like "Enter Time Machine").
+- RTL was reviewed in code (rows the engine mirrors, text with `start`/`end`, the progress bar in
+ `ltr`); there is no Arabic screenshot.
+
+<!-- SECCION:REGISTROS -->
+
+## Clock (`apps/clock`)
+
+World clock, alarms, timer and stopwatch, like the macOS Clock or GNOME Clocks.
+
+| Tab | What it does |
+|---|---|
+| World clock | Local time plus the cities you add (search over tzdata's `zone1970.tab`), with an analog face, "today/tomorrow/yesterday", the hour difference and the zone abbreviation (CEST, AEDT…) |
+| Alarms | Time, repeat days (or just once), label, on/off, edit and delete. Shows how long until the next one |
+| Timer | Hours, minutes and seconds or presets (1–30 min), pause and resume, progress bar |
+| Stopwatch | Laps with split and total; the fastest in green and the slowest in red |
+
+### Another city's time: our own TZif reader
+
+The process time zone is never touched to compute another city's time: `setenv("TZ")` would change
+the `Date` of the whole theme (the bar, the other apps). Instead:
+
+- `server/src/ui/tzif.c` reads the TZif files in `/usr/share/zoneinfo` (RFC 8536, versions 1 to 4:
+ the 64-bit block, binary search for the transition, and the footer with the POSIX TZ rule for
+ dates after the last transition) and evaluates POSIX rules (`CET-1CEST,M3.5.0,M10.5.0/3`, `Jn`,
+ `n`, `Mm.w.d`, negative or >24 h times, `<+0545>` names).
+- **Validated:** zone names only allow `[A-Za-z0-9/_+-]`, no `..` and no leading `/`; the real path
+ (tzdata uses links) must stay inside `/usr/share/zoneinfo/`; regular files up to 1 MB; every count
+ and index in the file is checked before reading.
+- **JS:** `lord.time.zoneOffset(zone, unixSeconds)` → `{ offset, abbr, dst }` or `null`
+ (`server/src/ui/js_help.c`, which adds it to the `lord.time` object created by `js_sys.c`).
+- **Test** (`make -C server test` → `build/tzif-test`, `tests/tzif_test.c`): POSIX rules at known
+ instants (Europe, Australia, the US, Nepal, zones without DST), a TZif v2 built inside the test
+ with **every truncated prefix** (each must fail without over-reading) and an invalid type index,
+ and a comparison against glibc (`localtime_r` with `TZ`) in 24 tricky zones (Lord Howe, Chatham,
+ Casablanca, Gaza, Santiago, Kathmandu, St Johns…) every ~3 days from 1970 to 2045:
+ **216,168 instants, 0 differences** on VM 119.
+
+### Alarms with the app closed (`sdk/alarms.js`)
+
+Alarms, the timer and the stopwatch live in the SDK, not in the window: `startShell` calls
+`startAlarms()` once per session. So they ring with Clock closed and also with the session in the
+background (fast user switching, or viewed only from the browser): the `lord-server` session keeps
+running, and so does its JS.
+
+- **Storage:** `settings.clock = { alarms: [{ id, h, m, days, label, on, snooze, fired }],
+ cities: [...] }` in `~/.config/lordos/settings.json`. `fired` is the instant it last rang, so it
+ does not ring again when the session restarts.
+- **No polling:** a single `setTimeout` until the next thing due (alarm, snooze or end of the
+ timer). It is re-armed when the alarms change (settings subscription).
+- **Clock changes and suspend:** `lord-server` timers use `CLOCK_MONOTONIC`, which does not advance
+ while suspended. So the wait is cut into slices —1 minute if something is due within the hour,
+ 10 minutes otherwise— and each wake-up recomputes with the real time. Anything that should have
+ rung less than 10 minutes ago still rings; older ones are dropped (yesterday's alarm does not ring
+ after a long suspend). With no alarms and no timer there is no timer at all.
+- **When it rings:** a sticky [notification](#session-notifications-sdknotifyjs) with "Stop" and
+ "Snooze 9 min", plus the `notify` sound from `lord.sound.play` every 2.5 s for one minute or until
+ the notification is touched. One-time alarms switch themselves off. The timer notifies the same
+ way, with "Repeat".
+- **Menu bar:** `registerStatusItem('clock', …)` shows ⏱ with the time left on the timer (redrawn
+ every second only while it runs) or ⏰ with the time of the next alarm if it rings within 24 h.
+ A click opens Clock on that tab.
+
+### Menu bar status items (`sdk/statusitems.js`)
+
+`registerStatusItem(id, Component, order)` and `<StatusItems color />`: an optional registry so
+system apps can show something in the theme's bar, like macOS "menu extras". The `default` theme
+(next to the privacy indicators) and `classic` (in the taskbar) draw it; a theme that does not draw
+it simply doesn't show them.
+
+### Session notifications (`sdk/notify.js`)
+
+LordOS had no notifications (only the short clipboard toast). Now there is one shared by every app,
+mounted by `startShell`, so it shows with any theme:
+
+```js
+import { notify, dismissNotification, notifyHistory } from '@lordos/sdk';
+const id = notify({
+ app: 'backup', // its icon and name (appName) in the banner
+ title: t('backup.notify.doneTitle'), // texts arrive already translated
+ body: '1234 files',
+ actions: [{ id: 'open', label: t('backup.notify.open'), primary: true, run: () => wm.open('backup') }],
+ sound: true, // the "notify" sound (lord.sound.play)
+ sticky: false, timeout: 6000, // sticky: stays until an action or the × is pressed
+ onClose: (reason) => {}, // 'closed', 'action' or the action id
+});
+dismissNotification(id);
+```
+
+- At the top, on the end side of the line (right; left in Arabic or Hebrew), below the theme's
+ `workArea`; up to four at a time, newest on top.
+- Clicking the banner runs the first action; the × closes it.
+- `notifyHistory`: the last 50 of the session, in memory only.
+- Up to three actions per notification. The API is stable: Clock and Backups use it.
+
+### Screenshots
+
+| | |
+|---|---|
+| ![world clock](m9-sistema-reloj-mundial.png) | ![alarm](m9-sistema-reloj-alarma.png) |
+| World clock with several cities | The alarm rings with Clock closed: notification with Stop and Snooze, ⏰ in the bar |
+
+## Help (`apps/help`)
+
+LordOS help and tips, like the macOS Tips app and help viewer.
+
+- **Articles:** one per app and per feature (desktop, windows, Spotlight, clipboard, keyboard and
+ input methods, Linux apps, touchpad, network, VPN, users and sessions, remote desktop, privacy,
+ printing, sound, updates, settings, appearance, language, and the system apps). 44 articles in
+ `assets/help/{en,es,pt}/<id>.md`, written from the documents in `docs/`. English is the default;
+ es and pt are translations.
+- **Sidebar** by section (Getting started, The desktop, Apps, System, Settings), with each app's
+ icon, and **search** over titles, keywords and text, with a snippet of the match.
+- **Rendered with the SDK's `<Markdown>`** (the same as Notes): headings, lists, tables, code.
+- **Custom links** in the text: `[Settings → Network](settings:network)` opens that Settings
+ section (`wm.open('settings', { args: { section } })`, which Settings already accepted);
+ `[Files](app:files)` opens an app; `[VPN](help:vpn)` another article. An app's article has an
+ "Open <app>" button.
+- **Help menu** in the `default` theme: "LordOS Help" and "Welcome to LordOS".
+
+### Article format
+
+```markdown
+---
+title: Clock
+app: clock # the app it explains ("Open" button and icon)
+section: apps # start | desktop | apps | system | settings
+order: 41
+keywords: alarm, timer, stopwatch
+---
+# Clock
+
+Markdown text…
+```
+
+**Fallback to English:** the list is the English one plus any extra articles of the interface
+language; each article is read in the interface language and, if that file is missing, in English.
+To add a language, copy the `en` folder and translate.
+
+### Reading: `lord.help` (`server/src/ui/js_help.c`)
+
+| Call | Returns |
+|---|---|
+| `lord.help.list(lang)` | `[{ id, title, app, section, order, keywords }]` (each `.md` header) |
+| `lord.help.read(lang, id)` | the article text or `null` |
+
+Read-only, like `lord.locale.catalog`: language and id only allow `[a-z0-9-]` (no dots or
+slashes), so nothing outside `<assets>/help/` can be reached; `O_NOFOLLOW`, regular files up to
+256 KB. In the SDK, `help` (`sdk/help.js`): `list`, `read`, `search`, `open(id)`, `startTour()` and
+`link(url)`.
+
+### Spotlight
+
+`sdk/spotlight.js` now has a source registry, `registerSpotlightSource(id, fn)`. Help registers
+its own: articles appear in the "Help" section with a snippet in the preview, and Enter opens the
+article. The section title comes from `shell.spotlight.section.<id>`.
+
+### "Welcome to LordOS"
+
+A six-step tour (welcome, the desktop, Spotlight, Settings with buttons to Appearance, Network and
+Users, the system apps, and where help is), with "Skip", "Back" and "Next".
+
+- It opens by itself **the first time** the session starts: `startShell` calls `maybeStartTour()`,
+ which writes `welcomeShown: true` to the settings before opening it (it doesn't come back even if
+ the window is closed). It doesn't appear on the live system, where the installer opens instead.
+- It can be watched again from the Help sidebar or the Help menu.
+- Its texts live in `assets/locales/<lang>/help.json` (`help.tour.<n>.title|body`).
+
+### Screenshots
+
+| | |
+|---|---|
+| ![welcome](m9-sistema-ayuda-bienvenida.png) | ![article](m9-sistema-ayuda-articulo.png) |
+| "Welcome to LordOS" on first login | An article opened from Spotlight, with links to other articles |
+| ![spotlight](m9-sistema-ayuda-spotlight.png) | |
+| Spotlight finds Help articles | |
+
+### Pending
+
+- Images inside articles (`<Markdown>` already draws them; per-language screenshots are missing).
+- A table of contents in long articles (`markdownHeadings` already exists).
diff --git a/docs/VM-SETUP.md b/docs/VM-SETUP.md
index d2413ee..7ef1f65 100644
--- a/docs/VM-SETUP.md
+++ b/docs/VM-SETUP.md
@@ -776,3 +776,104 @@ Ver `FIREWALL.md`, paso 2. En la VM 122 (172.17.0.56), que ya tenía `lord-sessi
- `/etc/firefox-esr/lordos.js` con `pref("browser.tabs.inTitlebar", 0)`;
- `assets/gtk/LordOS*` copiados a `/usr/share/themes/`.
+
+## Step — M9: Passwords and the system keyring (VM 116 `lordos-gpu`)
+
+See `PASSWORDS.md`. Everything was built in a new folder, `~/LordOS-pw` (the workers used
+`~/LordOS-pw-ctap`, `~/LordOS-pw-dbus`, `~/LordOS-pw-kdbx` and `~/LordOS-pw-qr`); `~/LordOS-iso`
+and `~/LordOS-m9` were not touched.
+
+- **Deploy:** `make -C server` in `~/LordOS-pw`, then `lord-server`, `lord-sessiond`,
+ `lord-vault` (new) and `lord-doc` installed into `/usr/local/lib/lordos/bin` (root, 755), and
+ `themes/` and `assets/` copied to `/usr/local/lib/lordos/`. Restarting the service needs the
+ sessions killed first (`KillMode=process`): `systemctl stop lordos`, `pkill -x lord-server`,
+ `reset-failed`, `start`.
+- **Test user** `pwtest` (`useradd -m -s /bin/bash -c "Prueba Contraseñas" pwtest`, test-only
+ password) so the login password path (`RP_KEYRING` → `login.lvault`) could be tested without
+ touching `lord`'s password; added to `plugdev` for the FIDO2 rule.
+- **Packages, test-only:**
+
+ | Package | Version | Why |
+ |---|---|---|
+ | `libsecret-tools` (+ `libsecret-1-0`) | 0.21.7-1 | `secret-tool` against our Secret Service |
+ | `chromium` | 155.0.8059.79-1~deb13u1 | saving and autofilling a login through the Secret Service |
+ | `keepassxc-minimal` | 2.7.10+dfsg1-1 | creating the KDBX test files (`server/tests/import/`) |
+ | `python3-venv` | 3.13.5-1 | a venv in `~/LordOS-pw-kdbx/venv` with pykeepass 4.2.0 for KDBX 4 variants |
+ | `libavcodec-dev`, `libavformat-dev`, `libavutil-dev`, `libswscale-dev`, `libswresample-dev` | Debian 13 | building `lord-media`, so LordOS screenshots work for the protected-window capture |
+
+- **FIDO2:** `/etc/udev/rules.d/71-lordos-fido.rules` (the rule in `PASSWORDS.md`); the software
+ authenticator `server/build/softfido` (from `tests/fido-soft/softfido.c`) runs as root on
+ `/dev/uhid` and shows up as `/dev/hidrawN` (`root:plugdev 0660`). No real key was available.
+- **Fake USB stick:** `/var/tmp/pendrive-pw-116.img` (32 MB ext4, label `PENDRIVE`) loop-mounted at
+ `/media/pwtest/PENDRIVE` (owned by `pwtest`) for the key-file screenshots.
+- **Remote desktop** turned on (`/etc/lordos/remote/config`: `enabled=1`, `port=5673`) while trying
+ the remote-viewer capture.
+- **Demo data:** `server/build/vault-demo lordos foto.jpg`, run as `pwtest`, creates a vault with
+ invented items of every template (test-only master password `lordos`); `/tmp/sitio-pw/` is a
+ local login page served on 127.0.0.1:8080 for the Chromium test.
+- **Screenshots** with `qm monitor 116` (`screendump`) from the Proxmox host; mouse via
+ `/root/lord-qmp-input.py 116`, keys via `sendkey` (`/root/lord-type.py`, and
+ `/root/lordos-latam-type.py` once the session uses the latam layout).
+- No network configuration was changed.
+
+## Step 20 — App polish pass (VM 120 `lordos-video`)
+
+See `DESIGN.md` and `docs/polish/`. VM 120 boots the **live ISO** (`lordos-live-0.7.0-amd64.iso`);
+its disk is empty. Nothing persistent was changed: everything below lives in the live session's
+RAM and disappears on reboot.
+
+- **Network:** untouched (DHCP, it got `172.17.0.22`). No SSH or listening service was added.
+- **Boot order:** set to `scsi0;ide2` for one boot to check the disk (empty), then restored to
+ `ide2;scsi0`.
+- **Deploying a build:** the tree goes into a raw `tar` file that is hot-plugged as a read-only
+ USB disk from the Proxmox monitor (`drive_add` + `device_add usb-storage`, removed with
+ `device_del`). It's installed from the session's Terminal (`sudo tar xf /dev/sdX -C /tmp` and
+ `instalar-pulido-120.sh`, which copies `bin`, `themes` and `assets` to `/usr/lib/lordos` and
+ restarts `lordos.service`).
+- **Libraries:** the 0.7.0 ISO doesn't have the runtime libraries of the current `lord-doc` and
+ `lord-media` (Poppler, libarchive, FFmpeg and their dependencies), so the PDF Viewer, Fonts and the
+ Photos thumbnails failed (`libpoppler-glib.so.8: cannot open shared object file`). The libraries
+ that were missing were copied from a Debian 13 container (`cp -n` into
+ `/usr/lib/x86_64-linux-gnu`, then `ldconfig`). They aren't installed with `apt`.
+- **Binaries:** built in a `debian:trixie` container with the `-dev` packages of steps 16 and 19.
+- **Sample content** in `/home/lordos`: generated photos in `Imágenes` (with `Viajes` and `Familia`
+ subfolders), `Documentos/Guia-LordOS.pdf` (5 pages with an outline), five notes in `Notas`, a
+ small project in `Proyectos/lordos-demo`, and the Arabic test pack in
+ `~/.local/share/lordos/locales/ar`.
+- **Screenshots:** a scratch-only harness (never in the repo) bundled into the test theme. F9/F8
+ step through 30 scenarios (6 apps × dark, light, RTL, minimum size, large), F7 opens a Terminal
+ and F6 shows a glyph test. Captured with `screendump` from the Proxmox monitor.
+
+## Step 21 — M8 app isolation: root-owned scopes, camera, several windows (VM 122 `lordos-sandbox`)
+
+See `PRIVACIDAD.md` («Root-owned app scopes», «Camera for isolated apps», «Several windows per
+isolated app»). On VM 122 (172.17.0.56):
+
+- **Packages:**
+ - `v4l2loopback-dkms` 0.15.0-2 and `linux-headers-6.12.111+deb13-amd64` (the cloud kernel
+ doesn't ship v4l2loopback; DKMS built and signed it);
+ - `ffmpeg` 7.1.5 and `v4l-utils` 1.30.1, to feed and inspect the virtual camera;
+ - `libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libswresample-dev libva-dev`, to
+ build `lord-media` (as in step 19).
+- **Virtual camera:** `/etc/modules-load.d/v4l2loopback.conf` (`v4l2loopback`) and
+ `/etc/modprobe.d/v4l2loopback.conf` (`video_nr=10 card_label="Camara virtual (v4l2loopback)"
+ exclusive_caps=1`) → `/dev/video10` (group `video`). The service
+ `/etc/systemd/system/lordos-test-camfeed.service` (enabled) runs `ffmpeg -re -f lavfi -i
+ testsrc2=size=1280x720:rate=30 -pix_fmt yuyv422 -f v4l2 /dev/video10`.
+- **`lordos.service`:** added `DelegateSubgroup=supervisor` (as in the ISO's unit).
+ `/usr/local/lib/lordos/bin` now also has `lord-media`.
+- **Test apps and files (test only):**
+ - `~/.local/share/applications/aisla.desktop` («Prueba de aislamiento»): `foot -e
+ ~/bin/escape-aisla-122.sh`, which tries to leave its scope and checks the network before and
+ after; `~/.config/lordos/firewall.json` restricts `desktop:aisla` (no internet, no incoming);
+ - `tests/lpk-legit` 1.1.0 (camera, «New window») unpacked into
+ `~/.local/share/lordos/apps/grabadora`;
+ - `~/foto.jpg` and `~/video.mp4`, saved through the powerbox during the test.
+- **Scripts:** `~/deploy-aisla-122.sh [full]` (installs the build; `full` stops/kills
+ `lordos.service`, clears `/run/lordos/autologin-done` and starts it) and
+ `~/vmbuild-aisla-122.sh` (runs `make`; while another agent's `src/hw` work was half done it added
+ those sources and `-include stddef.h` to the VM's copy only). From the Mac:
+ `sync-aisla-122.sh`, kept outside the repo.
+- **Screenshots:** `qm monitor 122` (`screendump`) on the Proxmox host; the mouse through
+ `/root/lord-qmp-input.py 122`, typing through `/root/lord-type.py 122`.
+- **Network:** untouched (no eth0 change, no nftables).
diff --git a/docs/m8-aislamiento-camara-revocada.png b/docs/m8-aislamiento-camara-revocada.png
new file mode 100644
index 0000000..132a616
Binary files /dev/null and b/docs/m8-aislamiento-camara-revocada.png differ
diff --git a/docs/m8-aislamiento-camara.png b/docs/m8-aislamiento-camara.png
new file mode 100644
index 0000000..c7fe6f2
Binary files /dev/null and b/docs/m8-aislamiento-camara.png differ
diff --git a/docs/m8-aislamiento-scope.png b/docs/m8-aislamiento-scope.png
new file mode 100644
index 0000000..e21c9c8
Binary files /dev/null and b/docs/m8-aislamiento-scope.png differ
diff --git a/docs/m8-aislamiento-ventanas.png b/docs/m8-aislamiento-ventanas.png
new file mode 100644
index 0000000..dae7d8e
Binary files /dev/null and b/docs/m8-aislamiento-ventanas.png differ
diff --git a/docs/m9-contrasenas-ajustes.png b/docs/m9-contrasenas-ajustes.png
new file mode 100644
index 0000000..28c9a69
Binary files /dev/null and b/docs/m9-contrasenas-ajustes.png differ
diff --git a/docs/m9-contrasenas-chromium-autocompletar.png b/docs/m9-contrasenas-chromium-autocompletar.png
new file mode 100644
index 0000000..9bafb3b
Binary files /dev/null and b/docs/m9-contrasenas-chromium-autocompletar.png differ
diff --git a/docs/m9-contrasenas-chromium-guardar.png b/docs/m9-contrasenas-chromium-guardar.png
new file mode 100644
index 0000000..2ece2dc
Binary files /dev/null and b/docs/m9-contrasenas-chromium-guardar.png differ
diff --git a/docs/m9-contrasenas-desbloquear-fido.png b/docs/m9-contrasenas-desbloquear-fido.png
new file mode 100644
index 0000000..63c59ea
Binary files /dev/null and b/docs/m9-contrasenas-desbloquear-fido.png differ
diff --git a/docs/m9-contrasenas-desbloquear-usb.png b/docs/m9-contrasenas-desbloquear-usb.png
new file mode 100644
index 0000000..fdc6eb1
Binary files /dev/null and b/docs/m9-contrasenas-desbloquear-usb.png differ
diff --git a/docs/m9-contrasenas-fido-permiso.png b/docs/m9-contrasenas-fido-permiso.png
new file mode 100644
index 0000000..4bbce6c
Binary files /dev/null and b/docs/m9-contrasenas-fido-permiso.png differ
diff --git a/docs/m9-contrasenas-generador-frase.png b/docs/m9-contrasenas-generador-frase.png
new file mode 100644
index 0000000..145b004
Binary files /dev/null and b/docs/m9-contrasenas-generador-frase.png differ
diff --git a/docs/m9-contrasenas-importar.png b/docs/m9-contrasenas-importar.png
new file mode 100644
index 0000000..d9d003f
Binary files /dev/null and b/docs/m9-contrasenas-importar.png differ
diff --git a/docs/m9-contrasenas-llavero-chromium.png b/docs/m9-contrasenas-llavero-chromium.png
new file mode 100644
index 0000000..eb855f7
Binary files /dev/null and b/docs/m9-contrasenas-llavero-chromium.png differ
diff --git a/docs/polish/calculator-after-dark.png b/docs/polish/calculator-after-dark.png
new file mode 100644
index 0000000..0fd7f91
Binary files /dev/null and b/docs/polish/calculator-after-dark.png differ
diff --git a/docs/polish/calculator-after-light.png b/docs/polish/calculator-after-light.png
new file mode 100644
index 0000000..19d7843
Binary files /dev/null and b/docs/polish/calculator-after-light.png differ
diff --git a/docs/polish/calculator-after-rtl.png b/docs/polish/calculator-after-rtl.png
new file mode 100644
index 0000000..00eb2f9
Binary files /dev/null and b/docs/polish/calculator-after-rtl.png differ
diff --git a/docs/polish/calculator-after-small.png b/docs/polish/calculator-after-small.png
new file mode 100644
index 0000000..ca20bd6
Binary files /dev/null and b/docs/polish/calculator-after-small.png differ
diff --git a/docs/polish/calculator-before-dark.png b/docs/polish/calculator-before-dark.png
new file mode 100644
index 0000000..60544c9
Binary files /dev/null and b/docs/polish/calculator-before-dark.png differ
diff --git a/docs/polish/calculator-before-light.png b/docs/polish/calculator-before-light.png
new file mode 100644
index 0000000..cceba4a
Binary files /dev/null and b/docs/polish/calculator-before-light.png differ
diff --git a/docs/polish/calculator-before-rtl.png b/docs/polish/calculator-before-rtl.png
new file mode 100644
index 0000000..0aa0365
Binary files /dev/null and b/docs/polish/calculator-before-rtl.png differ
diff --git a/docs/polish/calculator-before-small.png b/docs/polish/calculator-before-small.png
new file mode 100644
index 0000000..7a5dec5
Binary files /dev/null and b/docs/polish/calculator-before-small.png differ
diff --git a/docs/polish/calculator-comparison.png b/docs/polish/calculator-comparison.png
new file mode 100644
index 0000000..449e72d
Binary files /dev/null and b/docs/polish/calculator-comparison.png differ
diff --git a/docs/polish/editor-after-dark.png b/docs/polish/editor-after-dark.png
new file mode 100644
index 0000000..145a2db
Binary files /dev/null and b/docs/polish/editor-after-dark.png differ
diff --git a/docs/polish/editor-after-light.png b/docs/polish/editor-after-light.png
new file mode 100644
index 0000000..a076e63
Binary files /dev/null and b/docs/polish/editor-after-light.png differ
diff --git a/docs/polish/editor-after-rtl.png b/docs/polish/editor-after-rtl.png
new file mode 100644
index 0000000..f613554
Binary files /dev/null and b/docs/polish/editor-after-rtl.png differ
diff --git a/docs/polish/editor-after-small.png b/docs/polish/editor-after-small.png
new file mode 100644
index 0000000..7e18c4e
Binary files /dev/null and b/docs/polish/editor-after-small.png differ
diff --git a/docs/polish/editor-before-dark.png b/docs/polish/editor-before-dark.png
new file mode 100644
index 0000000..bd469a4
Binary files /dev/null and b/docs/polish/editor-before-dark.png differ
diff --git a/docs/polish/editor-before-light.png b/docs/polish/editor-before-light.png
new file mode 100644
index 0000000..0b39a0a
Binary files /dev/null and b/docs/polish/editor-before-light.png differ
diff --git a/docs/polish/editor-before-rtl.png b/docs/polish/editor-before-rtl.png
new file mode 100644
index 0000000..dad031c
Binary files /dev/null and b/docs/polish/editor-before-rtl.png differ
diff --git a/docs/polish/editor-before-small.png b/docs/polish/editor-before-small.png
new file mode 100644
index 0000000..70e80e1
Binary files /dev/null and b/docs/polish/editor-before-small.png differ
diff --git a/docs/polish/editor-comparison.png b/docs/polish/editor-comparison.png
new file mode 100644
index 0000000..3722c51
Binary files /dev/null and b/docs/polish/editor-comparison.png differ
diff --git a/docs/polish/fonts-after-dark.png b/docs/polish/fonts-after-dark.png
new file mode 100644
index 0000000..52614f4
Binary files /dev/null and b/docs/polish/fonts-after-dark.png differ
diff --git a/docs/polish/fonts-after-light.png b/docs/polish/fonts-after-light.png
new file mode 100644
index 0000000..11054d7
Binary files /dev/null and b/docs/polish/fonts-after-light.png differ
diff --git a/docs/polish/fonts-after-rtl.png b/docs/polish/fonts-after-rtl.png
new file mode 100644
index 0000000..6c90fcb
Binary files /dev/null and b/docs/polish/fonts-after-rtl.png differ
diff --git a/docs/polish/fonts-after-small.png b/docs/polish/fonts-after-small.png
new file mode 100644
index 0000000..1becda4
Binary files /dev/null and b/docs/polish/fonts-after-small.png differ
diff --git a/docs/polish/fonts-before-dark.png b/docs/polish/fonts-before-dark.png
new file mode 100644
index 0000000..6baab13
Binary files /dev/null and b/docs/polish/fonts-before-dark.png differ
diff --git a/docs/polish/fonts-before-light.png b/docs/polish/fonts-before-light.png
new file mode 100644
index 0000000..69c15e5
Binary files /dev/null and b/docs/polish/fonts-before-light.png differ
diff --git a/docs/polish/fonts-before-rtl.png b/docs/polish/fonts-before-rtl.png
new file mode 100644
index 0000000..798bbb7
Binary files /dev/null and b/docs/polish/fonts-before-rtl.png differ
diff --git a/docs/polish/fonts-before-small.png b/docs/polish/fonts-before-small.png
new file mode 100644
index 0000000..8e62019
Binary files /dev/null and b/docs/polish/fonts-before-small.png differ
diff --git a/docs/polish/fonts-comparison.png b/docs/polish/fonts-comparison.png
new file mode 100644
index 0000000..c61c4f4
Binary files /dev/null and b/docs/polish/fonts-comparison.png differ
diff --git a/docs/polish/notes-after-dark.png b/docs/polish/notes-after-dark.png
new file mode 100644
index 0000000..0e9b8f3
Binary files /dev/null and b/docs/polish/notes-after-dark.png differ
diff --git a/docs/polish/notes-after-light.png b/docs/polish/notes-after-light.png
new file mode 100644
index 0000000..8961b8f
Binary files /dev/null and b/docs/polish/notes-after-light.png differ
diff --git a/docs/polish/notes-after-rtl.png b/docs/polish/notes-after-rtl.png
new file mode 100644
index 0000000..462716a
Binary files /dev/null and b/docs/polish/notes-after-rtl.png differ
diff --git a/docs/polish/notes-after-small.png b/docs/polish/notes-after-small.png
new file mode 100644
index 0000000..cd9b4ae
Binary files /dev/null and b/docs/polish/notes-after-small.png differ
diff --git a/docs/polish/notes-before-dark.png b/docs/polish/notes-before-dark.png
new file mode 100644
index 0000000..db47191
Binary files /dev/null and b/docs/polish/notes-before-dark.png differ
diff --git a/docs/polish/notes-before-light.png b/docs/polish/notes-before-light.png
new file mode 100644
index 0000000..a4fae25
Binary files /dev/null and b/docs/polish/notes-before-light.png differ
diff --git a/docs/polish/notes-before-rtl.png b/docs/polish/notes-before-rtl.png
new file mode 100644
index 0000000..712fa41
Binary files /dev/null and b/docs/polish/notes-before-rtl.png differ
diff --git a/docs/polish/notes-before-small.png b/docs/polish/notes-before-small.png
new file mode 100644
index 0000000..c4cceb7
Binary files /dev/null and b/docs/polish/notes-before-small.png differ
diff --git a/docs/polish/notes-comparison.png b/docs/polish/notes-comparison.png
new file mode 100644
index 0000000..ae0013d
Binary files /dev/null and b/docs/polish/notes-comparison.png differ
diff --git a/docs/polish/pdf-after-dark.png b/docs/polish/pdf-after-dark.png
new file mode 100644
index 0000000..b92480c
Binary files /dev/null and b/docs/polish/pdf-after-dark.png differ
diff --git a/docs/polish/pdf-after-light.png b/docs/polish/pdf-after-light.png
new file mode 100644
index 0000000..3ba6f32
Binary files /dev/null and b/docs/polish/pdf-after-light.png differ
diff --git a/docs/polish/pdf-after-rtl.png b/docs/polish/pdf-after-rtl.png
new file mode 100644
index 0000000..d72e47c
Binary files /dev/null and b/docs/polish/pdf-after-rtl.png differ
diff --git a/docs/polish/pdf-after-small.png b/docs/polish/pdf-after-small.png
new file mode 100644
index 0000000..98b64ce
Binary files /dev/null and b/docs/polish/pdf-after-small.png differ
diff --git a/docs/polish/pdf-before-dark.png b/docs/polish/pdf-before-dark.png
new file mode 100644
index 0000000..57fdc71
Binary files /dev/null and b/docs/polish/pdf-before-dark.png differ
diff --git a/docs/polish/pdf-before-light.png b/docs/polish/pdf-before-light.png
new file mode 100644
index 0000000..b2ce3ce
Binary files /dev/null and b/docs/polish/pdf-before-light.png differ
diff --git a/docs/polish/pdf-before-rtl.png b/docs/polish/pdf-before-rtl.png
new file mode 100644
index 0000000..f1a2398
Binary files /dev/null and b/docs/polish/pdf-before-rtl.png differ
diff --git a/docs/polish/pdf-before-small.png b/docs/polish/pdf-before-small.png
new file mode 100644
index 0000000..9cc23d2
Binary files /dev/null and b/docs/polish/pdf-before-small.png differ
diff --git a/docs/polish/pdf-comparison.png b/docs/polish/pdf-comparison.png
new file mode 100644
index 0000000..ccddfbe
Binary files /dev/null and b/docs/polish/pdf-comparison.png differ
diff --git a/docs/polish/photos-after-dark.png b/docs/polish/photos-after-dark.png
new file mode 100644
index 0000000..bf1cb29
Binary files /dev/null and b/docs/polish/photos-after-dark.png differ
diff --git a/docs/polish/photos-after-light.png b/docs/polish/photos-after-light.png
new file mode 100644
index 0000000..bb6ed53
Binary files /dev/null and b/docs/polish/photos-after-light.png differ
diff --git a/docs/polish/photos-after-rtl.png b/docs/polish/photos-after-rtl.png
new file mode 100644
index 0000000..dc6c2b6
Binary files /dev/null and b/docs/polish/photos-after-rtl.png differ
diff --git a/docs/polish/photos-after-small.png b/docs/polish/photos-after-small.png
new file mode 100644
index 0000000..64e496b
Binary files /dev/null and b/docs/polish/photos-after-small.png differ
diff --git a/docs/polish/photos-before-dark.png b/docs/polish/photos-before-dark.png
new file mode 100644
index 0000000..959cef1
Binary files /dev/null and b/docs/polish/photos-before-dark.png differ
diff --git a/docs/polish/photos-before-light.png b/docs/polish/photos-before-light.png
new file mode 100644
index 0000000..073abb0
Binary files /dev/null and b/docs/polish/photos-before-light.png differ
diff --git a/docs/polish/photos-before-rtl.png b/docs/polish/photos-before-rtl.png
new file mode 100644
index 0000000..f48a66c
Binary files /dev/null and b/docs/polish/photos-before-rtl.png differ
diff --git a/docs/polish/photos-before-small.png b/docs/polish/photos-before-small.png
new file mode 100644
index 0000000..9d1774b
Binary files /dev/null and b/docs/polish/photos-before-small.png differ
diff --git a/docs/polish/photos-comparison.png b/docs/polish/photos-comparison.png
new file mode 100644
index 0000000..dbf7b72
Binary files /dev/null and b/docs/polish/photos-comparison.png differ
diff --git a/packaging/udev/71-lordos-fido.rules b/packaging/udev/71-lordos-fido.rules
new file mode 100644
index 0000000..4e83c1f
--- /dev/null
+++ b/packaging/udev/71-lordos-fido.rules
@@ -0,0 +1,7 @@
+# LordOS: FIDO2 security keys for the session user (docs/PASSWORDS.md).
+# lord-sessiond sessions are not logind seat sessions, so TAG+="uaccess" alone does not reach them.
+# ID_FIDO_TOKEN comes from systemd's 60-fido-id.rules. Only lord-server opens the device (after the
+# app's `usb` permission) and hands the fd to the sandboxed lord-vault.
+ACTION=="remove", GOTO="lordos_fido_end"
+SUBSYSTEM=="hidraw", ENV{ID_FIDO_TOKEN}=="1", GROUP="plugdev", MODE="0660"
+LABEL="lordos_fido_end"
diff --git a/runtime/app-host.js b/runtime/app-host.js
index 1a9c5b8..dcd219e 100644
--- a/runtime/app-host.js
+++ b/runtime/app-host.js
@@ -1,27 +1,32 @@
-// app-host.js — el «host» que corre dentro del proceso de una app .lpk aislada
-// (lord-server --app <id>, ver server/src/app/appclient.c). Trae React, el runtime y el SDK
-// (con el objeto `lord` del broker, que da fs/clipboard/perms verificados por lord-server),
-// carga el app.js del paquete y lo dibuja. La app usa `@lordos/sdk` igual que siempre.
+// app-host.js — the «host» that runs inside the process of an isolated .lpk app
+// (lord-server --app <id>, see server/src/app/appclient.c). It brings React, the runtime and the SDK
+// (with the broker's `lord` object, whose fs/clipboard/perms are checked by lord-server), loads the
+// package's app.js and draws it. The app uses `@lordos/sdk` as always.
//
-// Tema, idioma y dirección (RTL) llegan de lord-server: el estado al arrancar
-// (lord.broker.state()) y después en vivo (__lordBrokerEvent), así la app se ve como el resto
-// del escritorio y cambia junto con él (modo claro/oscuro, acento, fondo, idioma).
+// Theme, language and direction (RTL) come from lord-server: the state at startup
+// (lord.broker.state()) and then live (__lordBrokerEvent), so the app looks like the rest of the
+// desktop and changes with it (light/dark mode, accent, wallpaper, language).
+//
+// Several windows: the app's windows live in the SDK's window store of THIS process (wm.open with
+// the app's own id, wm.close, wm.setTitle…). Each one is rendered as a child of the React root and
+// becomes its own Wayland toplevel (lord.appWindows, one surface per window), so the theme frames
+// it, the Dock groups it under the app and the compositor routes focus and input to it.
import * as React from 'react';
import * as jsxRuntime from 'react/jsx-runtime';
import * as runtime from '@lordos/runtime';
import * as sdk from '@lordos/sdk';
-// Los módulos compartidos que la app pide con globalThis.__lordos.require (como en el tema).
+// Shared modules the app asks for with globalThis.__lordos.require (as in the theme).
const shared = { react: React, 'react/jsx-runtime': jsxRuntime, '@lordos/runtime': runtime, '@lordos/sdk': sdk };
globalThis.__lordos = globalThis.__lordos || {};
globalThis.__lordos.require = (name) => {
- if (!(name in shared)) throw new Error(`módulo no disponible: ${name}`);
+ if (!(name in shared)) throw new Error(`module not available: ${name}`);
return shared[name];
};
const { createElement: h, Fragment } = React;
const { render } = runtime;
-const { ThemeProvider, DEFAULT_TOKENS, PermissionPrompt, createStore, useStore, locale } = sdk;
+const { ThemeProvider, DEFAULT_TOKENS, PermissionPrompt, AppHost, createStore, useStore, locale, windows, wm } = sdk;
const tokens = createStore(DEFAULT_TOKENS);
@@ -37,37 +42,90 @@ function applyState(st) {
applyLocale(st.locale);
}
-applyState(lord.broker.state()); // estado actual de la sesión, antes del primer cuadro
+applyState(lord.broker.state()); // current session state, before the first frame
+
+// ---- the app's windows ----
+const APP = lord.appId;
+const AW = lord.appWindows; // undefined with an older lord-server: one window
+const keys = new Map([[APP, 0]]); // window id → surface key in C (0 = main window)
+const idOfKey = (key) => { for (const [id, k] of keys) if (k === key) return id; return null; };
+
+function readManifest() {
+ try {
+ const b = new Uint8Array(lord.apps.packageFile(APP, 'manifest.json'));
+ let s = '';
+ for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);
+ return JSON.parse(decodeURIComponent(escape(s)));
+ } catch (e) { return {}; }
+}
+const manifest = readManifest();
+
+let mod = null;
+function AppMain() {
+ if (!mod) mod = lord.loadApp(); // evaluates app.js once → { default, Icon }
+ if (!mod || typeof mod.default !== 'function') return h(runtime.Text, { style: { color: '#fff', padding: 20 } }, 'The app does not export a component');
+ return h(mod.default);
+}
+sdk.registerBuiltinApp({ id: APP, name: APP, builtin: true, size: Array.isArray(manifest.size) ? manifest.size : [640, 420], Component: AppMain });
+wm.open(APP); // the main window (surface key 0, created in C)
+
+// keep the C toplevels in step with the window store (open, close, title)
+function syncWindows() {
+ if (!AW) return;
+ const list = windows.get();
+ const ids = new Set(list.map((w) => w.id));
+ for (const w of list) {
+ if (!keys.has(w.id)) {
+ const k = AW.open(w.title || '', w.w, w.h);
+ if (k >= 0) keys.set(w.id, k);
+ }
+ const k = keys.get(w.id);
+ if (k != null) AW.setTitle(k, w.title || '');
+ }
+ for (const [id, k] of [...keys]) if (!ids.has(id)) { keys.delete(id); AW.close(k); }
+}
+windows.subscribe(syncWindows);
+
+function attach(id, inst) {
+ const k = keys.get(id);
+ if (AW && inst && k != null) AW.attach(k, inst.id);
+}
globalThis.__lordBrokerEvent = (kind, data) => {
if (kind === 'theme' && data) tokens.set(data);
else if (kind === 'locale') applyLocale(data);
else if (kind === 'state') applyState(data);
else if (kind === 'revoke' && data && data.perm) {
- // el usuario revocó un permiso: se apaga el indicador y se avisa a la app
+ // the user revoked a permission: turn the indicator off and tell the app
try { sdk.markDeviceUse(lord.appId, data.perm, false); } catch (e) { /* */ }
- try { for (const fn of revokeListeners) fn(data.perm); } catch (e) { /* */ }
+ try { for (const fn of revokeListeners) fn(data.perm); } catch (e) { console.error('revoke listener:', e?.message || e); }
}
else if (kind === 'menu' && data && data.item) { try { sdk.appMenuClick(data.item); } catch (e) { /* */ } }
+ else if (kind === 'appwindow' && data) {
+ // from the compositor: close (the frame's button; close guards still apply) or focus
+ const id = idOfKey(data.key);
+ if (!id) return;
+ if (data.type === 'close') wm.close(id);
+ else if (data.type === 'focus') wm.focus(id);
+ }
+ else if (kind === 'window' && data && data.new) wm.open(APP, { new: true }); // Dock → «New window»
};
const revokeListeners = new Set();
globalThis.__lordOnRevoke = (fn) => { revokeListeners.add(fn); return () => revokeListeners.delete(fn); };
-let mod = null;
-function App() {
- if (!mod) mod = lord.loadApp(); // evalúa app.js una sola vez → { default, Icon }
- if (!mod || typeof mod.default !== 'function') return h(runtime.Text, { style: { color: '#fff', padding: 20 } }, 'La app no exporta un componente');
- return h(mod.default);
-}
-
function Root() {
const tk = useStore(tokens);
const { lang, region } = useStore(locale);
- // al cambiar de idioma se vuelve a montar la app, como en el tema (los textos se arman al dibujar)
+ const list = useStore(windows);
+ const focused = sdk.wm.focused();
+ // a language change remounts the app, as in the theme (texts are built while rendering)
return h(ThemeProvider, { tokens: tk },
h(Fragment, { key: `${lang}|${region}` },
- h(runtime.View, { style: { flex: 1, backgroundColor: tk.windowBg } }, h(App)),
- h(PermissionPrompt)));
+ list.map((w, i) => h(runtime.View, {
+ key: w.id,
+ ref: (inst) => attach(w.id, inst),
+ style: { position: 'absolute', left: 0, top: 0, width: '100%', height: '100%', backgroundColor: tk.windowBg },
+ }, h(AppHost, { id: w.id, focused: w.id === focused }), i === 0 ? h(PermissionPrompt) : null))));
}
render(h(Root));
diff --git a/sdk/alarms.js b/sdk/alarms.js
index 13403ff..1fe4ec9 100644
--- a/sdk/alarms.js
+++ b/sdk/alarms.js
@@ -1,21 +1,21 @@
-// alarms.js — alarmas, temporizador y cronómetro de la sesión (app Reloj, docs/SISTEMA.md).
+// alarms.js — the session's alarms, timer and stopwatch (Clock app, docs/SYSTEM.md).
//
-// Viven en el SDK y no en la ventana del Reloj: startShell llama a startAlarms() y las alarmas
-// suenan aunque la app esté cerrada (o la sesión esté sin monitor). El temporizador y el
-// cronómetro también siguen al cerrar la ventana.
+// They live in the SDK, not in the Clock window: startShell calls startAlarms() and alarms ring
+// even when the app is closed (or the session is not on the monitor). The timer and the stopwatch
+// also keep going when the window is closed.
//
-// settings.clock = { alarms: [{ id, h, m, days: [0..6] (0 = domingo; vacío = una vez), label, on,
-// snooze (ms o 0), fired (ms de la última vez que sonó) }],
+// settings.clock = { alarms: [{ id, h, m, days: [0..6] (0 = Sunday; empty = once), label, on,
+// snooze (ms or 0), fired (ms of the last time it rang) }],
// cities: ['Europe/Madrid', …] }
-// clockAlarms.add({ h, m, days, label }) / update(id, cambios) / remove(id) / nextFire(alarma)
-// clockTimer (store) + timerStart(segundos) / timerPause() / timerResume() / timerReset()
+// clockAlarms.add({ h, m, days, label }) / update(id, changes) / remove(id) / nextFire(alarm)
+// clockTimer (store) + timerStart(seconds) / timerPause() / timerResume() / timerReset()
// stopwatch (store) + swStart() / swStop() / swLap() / swReset() / swElapsed()
//
-// Sin sondeos: un solo setTimeout hasta lo próximo que tiene que sonar. Los timers del servidor
-// van con CLOCK_MONOTONIC, que no avanza mientras el equipo está suspendido; por eso la espera se
-// corta en tramos (como mucho 1 minuto si algo suena dentro de la hora, si no 10 minutos) y en
-// cada despertar se mira la hora real: si saltó (cambio de hora, suspensión), se recalcula.
-// Lo que debió sonar hace menos de 10 minutos suena igual; lo más viejo se da por perdido.
+// No polling: a single setTimeout until the next thing due. The server's timers use
+// CLOCK_MONOTONIC, which does not advance while the computer is suspended; so the wait is cut into
+// slices (at most 1 minute if something is due within the hour, 10 minutes otherwise) and each
+// wake-up looks at the real time: if it jumped (clock change, suspend), everything is recomputed.
+// Anything that should have rung less than 10 minutes ago still rings; older ones are dropped.
import { createElement as h, useEffect, useState } from 'react';
import { View, Text } from '@lordos/runtime';
import { createStore, useStore } from './store.js';
@@ -35,7 +35,7 @@ const saveAlarms = (alarms) => settings.set({ clock: { ...conf(), alarms } });
const atDay = (base, addDays, hh, mm) => { const d = new Date(base); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + addDays); d.setHours(hh, mm, 0, 0); return d.getTime(); };
const dayOk = (a, ms) => !a.days?.length || a.days.includes(new Date(ms).getDay());
-// Próxima vez que suena (ms), o null si está apagada.
+// Next time it rings (ms), or null if it is off.
export function nextFire(a, now = Date.now()) {
if (!a.on) return null;
if (a.snooze && a.snooze > now) return a.snooze;
@@ -46,7 +46,7 @@ export function nextFire(a, now = Date.now()) {
return null;
}
-// La última vez que tendría que haber sonado (≤ ahora), para saber si quedó una pendiente.
+// The last time it should have rung (≤ now), to know whether one is pending.
function lastDue(a, now) {
if (!a.on) return null;
if (a.snooze) return a.snooze <= now ? a.snooze : null;
@@ -66,14 +66,14 @@ export const clockAlarms = {
return a.id;
},
update(id, patch) {
- // al prenderla o cambiar la hora no tiene que sonar por algo "pendiente" de antes
+ // turning it on or changing the time must not ring for something "pending" from before
saveAlarms(alarmsOf().map((a) => (a.id === id ? { ...a, ...patch, snooze: 'snooze' in patch ? patch.snooze : 0, fired: Date.now() } : a)));
},
remove(id) { saveAlarms(alarmsOf().filter((a) => a.id !== id)); },
nextFire,
};
-// ---- temporizador y cronómetro (en memoria de la sesión) ----
+// ---- timer and stopwatch (in session memory) ----
export const clockTimer = createStore({ state: 'idle', duration: 0, endsAt: 0, left: 0 });
export function timerStart(seconds) {
@@ -101,9 +101,9 @@ export const swStop = () => { const s = stopwatch.get(); if (s.running) stopwatc
export const swLap = () => { const s = stopwatch.get(); stopwatch.set({ laps: [swElapsed(s), ...s.laps].slice(0, 200) }); };
export const swReset = () => stopwatch.set({ running: false, start: 0, acc: 0, laps: [] });
-// ---- sonar ----
+// ---- ringing ----
-export const ringing = createStore([]); // ids de notificación que están sonando
+export const ringing = createStore([]); // notification ids that are ringing
function ring(notifyOpts) {
let iv = null, stopAt = Date.now() + RING_MS;
const id = notify({
@@ -137,10 +137,10 @@ function fireTimer() {
});
}
-// ---- programación ----
+// ---- scheduling ----
let handle = null, started = false;
-export const nextAlarm = createStore(null); // { at, label } la próxima alarma (para la barra)
+export const nextAlarm = createStore(null); // { at, label } the next alarm (for the bar)
function check() {
const now = Date.now();
@@ -162,7 +162,7 @@ function check() {
export function arm() {
clearTimeout(handle);
if (!started) return;
- check(); // puede volver a entrar acá (guardar las alarmas avisa a la suscripción)
+ check(); // may re-enter here (saving the alarms notifies the subscription)
clearTimeout(handle);
const now = Date.now();
let next = Infinity, nextA = null;
@@ -179,7 +179,7 @@ export function arm() {
handle = setTimeout(arm, Math.max(0, Math.min(wait, cap)));
}
-// La barra: ⏱ con lo que falta del temporizador, o ⏰ si hay una alarma en las próximas 24 h.
+// The bar: ⏱ with the time left on the timer, or ⏰ if an alarm rings within the next 24 h.
function TimerLeft({ color }) {
const s = useStore(clockTimer);
useTick(s.state === 'running');
@@ -188,7 +188,7 @@ function TimerLeft({ color }) {
const txt = `${sec >= 3600 ? `${Math.floor(sec / 3600)}:` : ''}${String(Math.floor(sec / 60) % 60).padStart(sec >= 3600 ? 2 : 1, '0')}:${String(sec % 60).padStart(2, '0')}`;
return h(Text, { style: { fontSize: 12, fontWeight: 600, color, fontFamily: 'monospace' } }, `⏱ ${txt}`);
}
-// vuelve a dibujar cada segundo, solo mientras corre
+// redraws every second, only while it runs
function useTick(on) {
const [, set] = useState(0);
useEffect(() => { if (!on) return undefined; const id = setInterval(() => set((x) => x + 1), 1000); return () => clearInterval(id); }, [on]);
@@ -207,7 +207,7 @@ function ClockStatus({ color, height }) {
soon && tm.state === 'idle' ? h(Text, { style: { fontSize: 12, color } }, `⏰ ${formatTime(new Date(na.at))}`) : null);
}
-// La llama startShell una vez. Las alarmas se vuelven a programar cuando cambian.
+// Called once by startShell. Alarms are re-armed when they change.
export function startAlarms() {
if (started) return;
started = true;
diff --git a/sdk/backup.js b/sdk/backup.js
index 71d56dc..536112f 100644
--- a/sdk/backup.js
+++ b/sdk/backup.js
@@ -1,15 +1,15 @@
-// backup.js — Copias de seguridad (lord.backup, ver server/src/backup y docs/SISTEMA.md).
+// backup.js — Backups (lord.backup, see server/src/backup and docs/SYSTEM.md).
//
-// const st = useBackup() estado en vivo: { state, progress, last, next, dest, … }
+// const st = useBackup() live status: { state, progress, last, next, dest, … }
// backup.config() / backup.configure({ dest, interval, pauseOnBattery, exclude })
// backup.runNow() / pause(on) / cancel()
// backup.list() → [{ id, time }] backup.ls(id, rel) → [{ name, dir, link, size, mtime }]
-// backup.restore(id, rel, { replace, suffix }) ('' = todo; el resultado llega en estado.restore)
-// backup.unlock(frase, crear) / backup.lock() copias cifradas (resultado en estado.unlock)
+// backup.restore(id, rel, { replace, suffix }) ('' = everything; result in status.restore)
+// backup.unlock(pass, create) / backup.lock() encrypted backups (result in status.unlock)
//
-// La copia la hace un hilo de lord-server con la prioridad más baja; el estado llega solo
-// (__lordBackup), sin consultar. Al terminar mal (o bien, si la pidió el usuario) se avisa con
-// notify(), aunque la app esté cerrada.
+// A lord-server thread at the lowest priority does the copying; the status is pushed
+// (__lordBackup), never polled. When a run fails (or succeeds, if the user asked for it) the
+// user is notified with notify(), even with the app closed.
import { createStore, useStore } from './store.js';
import { notify } from './notify.js';
import { t } from './i18n.js';
@@ -20,9 +20,9 @@ const has = () => typeof lord !== 'undefined' && lord.backup;
const read = () => { try { return has() ? lord.backup.status() : null; } catch (e) { return null; } };
export const backupStatus = createStore(read());
-let asked = false; // «Copiar ahora»: se avisa también si termina bien
+let asked = false; // "Back Up Now": also notify on success
let restoring = false;
-let lockedNoticed = false; // «desbloqueá las copias»: una vez por sesión
+let lockedNoticed = false; // "unlock your backups": once per session
function changed(prev, st) {
if (!prev || !st) return;
@@ -69,7 +69,7 @@ export const backup = {
return lord.backup.restore(id, rel, { suffix: t('backup.restoredSuffix'), ...opts });
},
remove: (id) => lord.backup.remove(id),
- // cifrado (Monocypher): la frase se convierte en la clave en el hilo de la copia; queda solo en memoria
+ // encryption (Monocypher): the passphrase becomes the key in the backup thread; kept only in memory
unlock: (pass, create = false) => lord.backup.unlock(String(pass), !!create),
lock: () => lord.backup.lock(),
};
diff --git a/sdk/components.jsx b/sdk/components.jsx
index dad2e5d..753cf77 100644
--- a/sdk/components.jsx
+++ b/sdk/components.jsx
@@ -8,14 +8,20 @@ import { useStore } from './store.js';
import { textDirection } from './i18n.js';
import { ime, useIme, Preedit } from './ime.js';
-export function Button({ label, onClick, primary, style }) {
+// Push button. Optional (all additive): small (22 px high), plain (no fill until hover), disabled,
+// destructive (red text) and icon (a glyph before the label). See docs/DESIGN.md.
+export function Button({ label, onClick, primary, style, small, plain, disabled, destructive, icon }) {
const t = useTheme();
const [hover, setHover] = useState(false);
+ const fg = primary ? '#fff' : destructive ? '#ff453a' : t.text;
+ const bg = primary ? t.accent : plain ? (hover && !disabled ? t.hover : 'transparent') : t.control;
return (
- <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
- style={[{ height: 28, paddingHorizontal: 14, borderRadius: 7, justifyContent: 'center', alignItems: 'center',
- backgroundColor: primary ? t.accent : t.control, opacity: hover ? 0.85 : 1 }, style]}>
- <Text style={{ fontSize: 13, fontWeight: 500, color: primary ? '#fff' : t.text }}>{label}</Text>
+ <View onClick={disabled ? undefined : onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={[{ height: small ? 22 : 28, paddingHorizontal: small ? 10 : 14, borderRadius: small ? 6 : 7, flexDirection: 'row', gap: 6,
+ justifyContent: 'center', alignItems: 'center', backgroundColor: bg,
+ opacity: disabled ? 0.4 : hover && !plain ? 0.85 : 1 }, style]}>
+ {icon ? <Text style={{ fontSize: small ? 12 : 14, color: fg }}>{icon}</Text> : null}
+ {label != null && label !== '' ? <Text style={{ fontSize: small ? 12 : 13, fontWeight: 500, color: fg, whiteSpace: 'nowrap' }}>{label}</Text> : null}
</View>
);
}
@@ -31,29 +37,42 @@ export function Toggle({ on, onChange }) {
);
}
-export function Segmented({ options, value, onChange }) {
+// appearance: 'accent' (default: the selected segment is filled with the accent) or 'neutral'
+// (macOS view switcher: a raised neutral segment). small: 22 px high instead of 28. fill: the
+// segments share the full width of the control.
+export function Segmented({ options, value, onChange, appearance = 'accent', small, fill, style }) {
const t = useTheme();
+ const neutral = appearance === 'neutral';
+ const raised = t.mode === 'dark' ? 'rgba(255,255,255,0.18)' : '#ffffff';
return (
- <View style={{ flexDirection: 'row', backgroundColor: t.control, borderRadius: 8, padding: 2 }}>
- {options.map(([v, label]) => (
- <View key={v} onClick={() => onChange(v)} style={{ paddingHorizontal: 14, height: 26, borderRadius: 6,
- justifyContent: 'center', backgroundColor: value === v ? t.accent : 'transparent' }}>
- <Text style={{ fontSize: 12, fontWeight: 600, color: value === v ? '#fff' : t.text }}>{label}</Text>
- </View>
- ))}
+ <View style={[{ flexDirection: 'row', backgroundColor: t.control, borderRadius: small ? 6 : 8, padding: 2 }, style]}>
+ {options.map(([v, label]) => {
+ const on = value === v;
+ return (
+ <View key={v} onClick={() => onChange(v)} style={{ paddingHorizontal: small ? 10 : 14, height: small ? 18 : 24, borderRadius: small ? 5 : 6,
+ justifyContent: 'center', alignItems: 'center', flexGrow: fill ? 1 : 0,
+ backgroundColor: on ? (neutral ? raised : t.accent) : 'transparent',
+ boxShadow: on && neutral ? '0 1px 2px rgba(0,0,0,0.18)' : 'none' }}>
+ <Text style={{ fontSize: small ? 11 : 12, fontWeight: on && neutral ? 600 : neutral ? 500 : 600, whiteSpace: 'nowrap',
+ color: on && !neutral ? '#fff' : t.text }}>{label}</Text>
+ </View>
+ );
+ })}
</View>
);
}
-export function SidebarItem({ label, selected, onClick, icon }) {
+// Source-list row. Optional: detail (trailing text, e.g. a count) and indent (nesting level).
+export function SidebarItem({ label, selected, onClick, icon, detail, indent = 0 }) {
const t = useTheme();
const [hover, setHover] = useState(false);
return (
<View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
- style={{ height: 28, paddingHorizontal: 10, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 8,
+ style={{ height: 28, paddingLeft: 10 + indent * 14, paddingRight: 10, borderRadius: 6, flexDirection: 'row', alignItems: 'center', gap: 8,
backgroundColor: selected ? t.accent : hover ? t.hover : 'transparent' }}>
- {icon}
- <Text style={{ fontSize: 13, fontWeight: 500, color: selected ? '#fff' : t.text }}>{label}</Text>
+ {typeof icon === 'string' ? <Text style={{ width: 18, textAlign: 'center', fontSize: 14, color: selected ? '#fff' : t.accent }}>{icon}</Text> : icon}
+ <Text style={{ flex: 1, fontSize: 13, fontWeight: 500, color: selected ? '#fff' : t.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{label}</Text>
+ {detail != null ? <Text style={{ fontSize: 11, color: selected ? 'rgba(255,255,255,0.8)' : t.textDim }}>{detail}</Text> : null}
</View>
);
}
@@ -186,7 +205,7 @@ export function TextInput({ value, onChange, placeholder, onSubmit, onCancel, on
return (
<View onMouseDown={() => { focusedNow = true; setFocus(token); }}
- style={[{ height: Math.max(30, size + 17), paddingHorizontal: 10, borderRadius: 7, flexDirection: 'row', alignItems: 'center',
+ style={[{ height: Math.max(28, size + 15), paddingHorizontal: 10, borderRadius: 7, flexDirection: 'row', alignItems: 'center',
// el cursor va al final lógico: a la izquierda si el texto es árabe o hebreo
direction: secure ? 'ltr' : value ? textDirection(value) : 'inherit',
backgroundColor: t.inputBg, border: `1px solid ${isFocused ? t.accent : t.separator}`, overflow: 'hidden' }, style]}>
diff --git a/sdk/controls.jsx b/sdk/controls.jsx
new file mode 100644
index 0000000..47b481c
--- /dev/null
+++ b/sdk/controls.jsx
@@ -0,0 +1,210 @@
+// controls.jsx — shared building blocks for the macOS-style layout of LordOS apps: toolbar buttons
+// with tooltips, toolbars, a "more" menu button, a search field, empty states and grouped
+// ("inset") forms. The spacing and type scale they follow is in docs/DESIGN.md.
+import { View, Text, addListener } from '@lordos/runtime';
+import { useEffect, useRef, useState } from 'react';
+import { useTheme } from './theme.js';
+import { TextInput, useAppWindow } from './components.jsx';
+import { wm } from './windows.js';
+import { direction } from './i18n.js';
+
+// Design tokens (docs/DESIGN.md): an 8 px grid, macOS-like type sizes and control heights.
+export const spacing = { xxs: 2, xs: 4, s: 8, m: 12, l: 16, xl: 20, xxl: 24, xxxl: 32 };
+export const typeScale = { caption: 11, body: 13, callout: 12, headline: 15, title: 17, largeTitle: 22 };
+export const controlSize = { regular: 28, small: 22, toolbar: 44, radius: 7, radiusSmall: 6, groupRadius: 10 };
+
+// Is a point on the trailing half of the window? Tooltips and menus open toward the inside.
+function nearEnd(winId, node) {
+ try {
+ const [x, , w] = lord.getLayout(node.id);
+ const f = wm.get(winId);
+ const mid = f ? f.x + f.w / 2 : 640;
+ const end = x + w / 2 > mid;
+ return direction() === 'rtl' ? !end : end;
+ } catch (e) { return false; }
+}
+
+// Hover tooltip (shown after a short delay), as macOS does for icon-only toolbar items.
+function useTooltip(title) {
+ const [show, setShow] = useState(false);
+ const timer = useRef(0);
+ useEffect(() => () => clearTimeout(timer.current), []);
+ const enter = () => { if (!title) return; clearTimeout(timer.current); timer.current = setTimeout(() => setShow(true), 550); };
+ const leave = () => { clearTimeout(timer.current); setShow(false); };
+ return [show, enter, leave];
+}
+
+function TooltipBubble({ text, end, top }) {
+ const t = useTheme();
+ return (
+ <View style={{ position: 'absolute', top, [end ? 'right' : 'left']: 0, zIndex: 1000, pointerEvents: 'none',
+ paddingHorizontal: 8, height: 22, borderRadius: 6, justifyContent: 'center',
+ backgroundColor: t.mode === 'dark' ? '#3a3a40' : '#fbfbfd', border: `1px solid ${t.separator}`, boxShadow: '0 4px 12px rgba(0,0,0,0.25)' }}>
+ <Text style={{ fontSize: 11, color: t.text, whiteSpace: 'nowrap' }}>{text}</Text>
+ </View>
+ );
+}
+
+// Toolbar item: an icon (a glyph) and/or a short label, borderless until hovered.
+// title: tooltip text (required for icon-only buttons). active: a toggled-on state.
+export function ToolbarButton({ icon, label, title, onClick, active, disabled, small, iconSize, color, style }) {
+ const t = useTheme();
+ const { id: winId } = useAppWindow();
+ const ref = useRef(null);
+ const [hover, setHover] = useState(false);
+ const [tip, tipEnter, tipLeave] = useTooltip(title);
+ const h = small ? controlSize.small : controlSize.regular;
+ const fg = disabled ? t.textDim : active ? t.accent : color || t.text;
+ return (
+ <View ref={ref} onClick={() => { tipLeave(); if (!disabled) onClick?.(); }}
+ onMouseEnter={() => { setHover(true); tipEnter(); }} onMouseLeave={() => { setHover(false); tipLeave(); }}
+ style={[{ height: h, minWidth: h, paddingHorizontal: label ? 8 : 0, borderRadius: controlSize.radiusSmall, flexDirection: 'row', gap: 6,
+ alignItems: 'center', justifyContent: 'center', opacity: disabled ? 0.45 : 1, zIndex: tip ? 1000 : 0,
+ backgroundColor: active ? (t.mode === 'dark' ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.08)') : hover && !disabled ? t.hover : 'transparent' }, style]}>
+ {icon != null ? <Text style={{ fontSize: iconSize || (small ? 13 : 15), color: fg, textAlign: 'center' }}>{icon}</Text> : null}
+ {label ? <Text style={{ fontSize: small ? 12 : 13, fontWeight: 500, color: fg, whiteSpace: 'nowrap' }}>{label}</Text> : null}
+ {tip && title ? <TooltipBubble text={title} end={nearEnd(winId, ref.current)} top={h + 6} /> : null}
+ </View>
+ );
+}
+
+// Buttons that belong together (zoom −/+, markup tools): one rounded track.
+export function ToolbarGroup({ children, style }) {
+ const t = useTheme();
+ return <View style={[{ flexDirection: 'row', alignItems: 'center', gap: 2, padding: 2, borderRadius: 8, backgroundColor: t.control }, style]}>{children}</View>;
+}
+
+// The app's toolbar row under the title bar: 44 px, 12 px side insets, 8 px between items and a
+// hairline at the bottom.
+export function Toolbar({ children, style, separator = true }) {
+ const t = useTheme();
+ return (
+ <View style={[{ height: controlSize.toolbar, flexDirection: 'row', alignItems: 'center', gap: spacing.s, paddingHorizontal: spacing.m, zIndex: 10 }, style]}>
+ {separator ? <View style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: 1, backgroundColor: t.separator }} /> : null}
+ {children}
+ </View>
+ );
+}
+
+export const ToolbarSpacer = () => <View style={{ flex: 1 }} />;
+
+// Thin vertical divider between toolbar groups.
+export function ToolbarDivider() {
+ const t = useTheme();
+ return <View style={{ width: 1, height: 18, marginHorizontal: 2, backgroundColor: t.separator }} />;
+}
+
+// "More" button that opens a small menu: items = [{ label, onClick, checked, disabled, destructive } | '-'].
+export function MenuButton({ icon = '⋯', title, items, small }) {
+ const t = useTheme();
+ const { id: winId } = useAppWindow();
+ const [open, setOpen] = useState(false);
+ const btn = useRef(null), menu = useRef(null);
+ useEffect(() => {
+ if (!open) return undefined;
+ return addListener('pointerdown', (e) => {
+ const inside = (n) => { if (!n) return false; const [x, y, w, h] = lord.getLayout(n.id); return e.x >= x && e.x <= x + w && e.y >= y && e.y <= y + h; };
+ if (!inside(menu.current) && !inside(btn.current)) setOpen(false);
+ });
+ }, [open]);
+ const end = open && nearEnd(winId, btn.current);
+ return (
+ <View ref={btn} style={{ zIndex: open ? 1000 : 0 }}>
+ <ToolbarButton icon={icon} title={open ? null : title} small={small} active={open} onClick={() => setOpen((o) => !o)} />
+ {open && (
+ <View ref={menu} style={{ position: 'absolute', top: (small ? controlSize.small : controlSize.regular) + 4, [end ? 'right' : 'left']: 0, zIndex: 1000,
+ minWidth: 200, paddingVertical: 5, paddingHorizontal: 5, borderRadius: 8, 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) => (it === '-' ? <View key={`s${i}`} style={{ height: 1, marginVertical: 4, marginHorizontal: 6, backgroundColor: t.separator }} />
+ : <MenuRow key={it.label} it={it} onDone={() => setOpen(false)} />))}
+ </View>
+ )}
+ </View>
+ );
+}
+
+function MenuRow({ it, onDone }) {
+ const t = useTheme();
+ const [hover, setHover] = useState(false);
+ const on = hover && !it.disabled;
+ return (
+ <View onClick={() => { if (it.disabled) return; onDone(); it.onClick?.(); }} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ height: 24, paddingHorizontal: 8, borderRadius: 5, flexDirection: 'row', alignItems: 'center', gap: 6, backgroundColor: on ? t.accent : 'transparent',
+ opacity: it.disabled ? 0.4 : 1 }}>
+ <Text style={{ width: 12, fontSize: 11, color: on ? '#fff' : t.text }}>{it.checked ? '✓' : ''}</Text>
+ <Text style={{ flex: 1, fontSize: 13, whiteSpace: 'nowrap', color: on ? '#fff' : it.destructive ? '#ff453a' : t.text }}>{it.label}</Text>
+ </View>
+ );
+}
+
+// Search field: a TextInput with a magnifier and a clear button.
+export function SearchField({ value, onChange, placeholder, onSubmit, onCancel, onKeyDown, autoFocus, width, style }) {
+ const t = useTheme();
+ // the magnifier sits at the leading edge and the clear button at the trailing one
+ const rtl = direction() === 'rtl';
+ const lead = rtl ? 'right' : 'left', trail = rtl ? 'left' : 'right';
+ return (
+ <View style={[{ width, flexDirection: 'row', alignItems: 'center' }, style]}>
+ <TextInput value={value} onChange={onChange} placeholder={placeholder} onSubmit={onSubmit} onKeyDown={onKeyDown} autoFocus={autoFocus}
+ onCancel={() => { if (value) onChange(''); onCancel?.(); }}
+ style={{ flex: 1, [rtl ? 'paddingRight' : 'paddingLeft']: 26, [rtl ? 'paddingLeft' : 'paddingRight']: value ? 26 : 10 }} />
+ <Text style={{ position: 'absolute', [lead]: 9, top: 5, fontSize: 13, color: t.textDim, pointerEvents: 'none' }}>⌕</Text>
+ {value ? (
+ <View onClick={() => onChange('')} style={{ position: 'absolute', [trail]: 6, top: 6, width: 16, height: 16, borderRadius: 8,
+ alignItems: 'center', justifyContent: 'center', backgroundColor: t.textDim }}>
+ <Text style={{ fontSize: 10, fontWeight: 700, color: t.mode === 'dark' ? '#1f1f23' : '#fff' }}>✕</Text>
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+// Empty state: an icon (a glyph or an element), a short title and one hint line, centered.
+export function EmptyState({ icon, title, hint, action, style }) {
+ const t = useTheme();
+ return (
+ <View style={[{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: spacing.s, padding: spacing.xxl }, style]}>
+ {typeof icon === 'string' ? <Text style={{ fontSize: 40, color: t.textDim, marginBottom: spacing.xs }}>{icon}</Text> : icon}
+ {title ? <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text, textAlign: 'center' }}>{title}</Text> : null}
+ {hint ? <Text style={{ fontSize: typeScale.callout, color: t.textDim, textAlign: 'center', maxWidth: 360, lineHeight: 1.4 }}>{hint}</Text> : null}
+ {action ? <View style={{ marginTop: spacing.s }}>{action}</View> : null}
+ </View>
+ );
+}
+
+// Grouped ("inset") section like macOS Settings: an optional caption above a rounded box whose rows
+// are separated by hairlines. Children are FormRow (or any element).
+export function GroupBox({ title, children, footer, style }) {
+ const t = useTheme();
+ const rows = (Array.isArray(children) ? children.flat() : [children]).filter(Boolean);
+ const box = t.mode === 'dark' ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.025)';
+ return (
+ <View style={[{ gap: 6 }, style]}>
+ {title ? <Text style={{ fontSize: typeScale.caption, fontWeight: 600, color: t.textDim, marginLeft: spacing.s }}>{title}</Text> : null}
+ <View style={{ borderRadius: controlSize.groupRadius, backgroundColor: box, border: `1px solid ${t.separator}`, paddingHorizontal: spacing.m }}>
+ {rows.map((r, i) => (
+ <View key={i}>
+ {i > 0 ? <View style={{ height: 1, backgroundColor: t.separator }} /> : null}
+ {r}
+ </View>
+ ))}
+ </View>
+ {footer ? <Text style={{ fontSize: typeScale.caption, color: t.textDim, marginLeft: spacing.s }}>{footer}</Text> : null}
+ </View>
+ );
+}
+
+// A row of a GroupBox: label at the start, value or control at the end (labelWidth: a right-aligned
+// label column, as in macOS forms).
+export function FormRow({ label, children, labelWidth, minHeight = 36 }) {
+ const t = useTheme();
+ const value = typeof children === 'string' || typeof children === 'number'
+ ? <Text style={{ fontSize: typeScale.body, color: t.text }}>{String(children)}</Text> : children;
+ return (
+ <View style={{ minHeight, flexDirection: 'row', alignItems: 'center', gap: spacing.m, paddingVertical: 6 }}>
+ <Text style={labelWidth ? { width: labelWidth, fontSize: typeScale.body, color: t.textDim, textAlign: 'end' }
+ : { fontSize: typeScale.body, color: t.text }}>{label}</Text>
+ <View style={{ flex: 1, alignItems: labelWidth ? 'flex-start' : 'flex-end' }}>{value}</View>
+ </View>
+ );
+}
diff --git a/sdk/defaults.js b/sdk/defaults.js
new file mode 100644
index 0000000..0539791
--- /dev/null
+++ b/sdk/defaults.js
@@ -0,0 +1,75 @@
+// defaults.js — default applications (Settings → Default Apps, docs/SETTINGS.md). They are kept
+// in ~/.config/mimeapps.list (freedesktop spec, so GNOME/KDE apps and xdg-open agree) through
+// lord.mime; the terminal goes in ~/.config/xdg-terminals.list. LordOS's own apps are written as
+// "lordos-<app>.desktop".
+//
+// DEFAULT_CATEGORIES [{ id, mimes, natives }]
+// defaultFor(categoryId) 'lordos-photos.desktop' | 'org.gnome.Loupe.desktop' | null
+// setDefaultFor(categoryId, id) writes every MIME type of the category
+// candidatesFor(categoryId, linux) [{ id, name, Icon, native }] that can be chosen
+// defaultOpenerId(mime) the default for one type (Files: "Open With", double click)
+import { getApp } from './windows.js';
+import { appName } from './i18n.js';
+
+const NATIVE = (id) => `lordos-${id}.desktop`;
+export const nativeOf = (desktopId) => (desktopId && /^lordos-[a-z0-9_-]+\.desktop$/.test(desktopId) ? desktopId.slice(7, -8) : null);
+
+// First MIME type is the one read back to show the current choice.
+export const DEFAULT_CATEGORIES = [
+ { id: 'browser', mimes: ['x-scheme-handler/https', 'x-scheme-handler/http', 'text/html', 'application/xhtml+xml'], natives: [] },
+ { id: 'mail', mimes: ['x-scheme-handler/mailto', 'message/rfc822'], natives: ['mail'] },
+ { id: 'music', mimes: ['audio/mpeg', 'audio/flac', 'audio/ogg', 'audio/x-vorbis+ogg', 'audio/x-opus+ogg', 'audio/mp4', 'audio/aac', 'audio/x-wav', 'audio/x-m4a'], natives: ['player'] },
+ { id: 'video', mimes: ['video/mp4', 'video/x-matroska', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/mpeg', 'video/ogg'], natives: ['player'] },
+ { id: 'images', mimes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'image/tiff', 'image/svg+xml', 'image/heic'], natives: ['photos'] },
+ { id: 'pdf', mimes: ['application/pdf'], natives: ['pdf'] },
+ { id: 'text', mimes: ['text/plain', 'text/markdown', 'text/x-log'], natives: ['editor'] },
+ { id: 'terminal', mimes: [], natives: ['terminal'], terminal: true },
+];
+
+const cat = (id) => DEFAULT_CATEGORIES.find((c) => c.id === id);
+const api = () => typeof lord !== 'undefined' && lord.mime;
+
+export function defaultFor(id) {
+ const c = cat(id);
+ if (!c || !api()) return null;
+ if (c.terminal) return lord.mime.terminal() || NATIVE('terminal');
+ for (const m of c.mimes) { const d = lord.mime.get(m); if (d) return d; }
+ return c.natives.find((n) => getApp(n)) ? NATIVE(c.natives.find((n) => getApp(n))) : null;
+}
+
+export function setDefaultFor(id, desktopId) {
+ const c = cat(id);
+ if (!c || !api() || !desktopId) return false;
+ if (c.terminal) return lord.mime.setTerminal(desktopId);
+ let ok = true;
+ for (const m of c.mimes) ok = lord.mime.set(m, desktopId) && ok;
+ return ok;
+}
+
+// Does a Linux app's MimeType list cover the category? (its main type, or the whole family)
+function covers(mimeTypes, c) {
+ if (!mimeTypes) return false;
+ const list = mimeTypes.split(';').filter(Boolean);
+ const main = c.mimes[0], top = main.split('/')[0];
+ return list.includes(main) || list.includes(`${top}/*`) || (c.id === 'browser' && list.includes('text/html') && list.includes('x-scheme-handler/http'));
+}
+
+export function candidatesFor(id, linuxApps = []) {
+ const c = cat(id);
+ if (!c) return [];
+ const out = c.natives.map((n) => getApp(n)).filter(Boolean).map((a) => ({ id: NATIVE(a.id), name: appName(a), Icon: a.Icon, native: true }));
+ for (const a of linuxApps) {
+ if (a.kind !== 'linux') continue;
+ const ok = c.terminal ? /(^|;)TerminalEmulator(;|$)/.test(a.categories || '') : covers(a.mimeTypes, c);
+ if (ok) out.push({ id: `${a.desktopId}.desktop`, name: a.name, Icon: a.Icon, native: false });
+ }
+ return out;
+}
+
+export function defaultOpenerId(mime) {
+ if (!api() || !mime) return null;
+ const d = lord.mime.get(mime);
+ if (d) return d;
+ const c = DEFAULT_CATEGORIES.find((x) => x.mimes.includes(mime) || (x.mimes[0] && mime.startsWith(`${x.mimes[0].split('/')[0]}/`) && x.id !== 'browser' && x.id !== 'mail'));
+ return c ? defaultFor(c.id) : null;
+}
diff --git a/sdk/disks.js b/sdk/disks.js
index dbe0370..8e4c7ad 100644
--- a/sdk/disks.js
+++ b/sdk/disks.js
@@ -1,19 +1,19 @@
-// disks.js — discos y particiones (app Discos; ver docs/SISTEMA.md, «Discos»).
+// disks.js — disks and partitions (Disks app; see docs/SYSTEM.md, "Disks").
//
-// const [lista, recargar] = useDisks() // se actualiza sola al montar, desmontar o enchufar
-// disks.list() disks.tools() // lord.disks, de solo lectura y sin root
+// const [list, reload] = useDisks() // updates itself on mount, unmount or plug-in
+// disks.list() disks.tools() // lord.disks, read-only and without root
//
-// Lo que cambia algo va por el ayudante con las acciones cerradas disk-* (admin.run): disk-smart,
-// disk-mount, disk-unmount, disk-eject, disk-format, disk-label, disk-erase, disk-write-image y
-// disk-cancel. Los avisos de cambios (mountinfo y udev, sin sondeo) solo están prendidos mientras
-// alguien usa useDisks().
+// Anything that changes something goes through the helper with the closed disk-* actions
+// (admin.run): disk-smart, disk-mount, disk-unmount, disk-eject, disk-format, disk-label,
+// disk-erase, disk-write-image and disk-cancel. Change notifications (mountinfo and udev, no
+// polling) are only on while someone uses useDisks().
import { useEffect, useState } from 'react';
const listeners = new Set();
let timer = null;
globalThis.__lordDisks = () => {
- // los avisos de udev llegan de a varios: se juntan en uno
+ // udev events come in bursts: coalesce them into one
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
diff --git a/sdk/dock.js b/sdk/dock.js
index b7a70f7..21e35b7 100644
--- a/sdk/dock.js
+++ b/sdk/dock.js
@@ -73,6 +73,7 @@ windows.subscribe(() => {
export function launcherIdOf(w) {
if (!String(w.id).startsWith('linux#')) return appIdOf(w.id);
const appId = w.args?.appId || '';
+ if (w.args?.pkg && appId && getApp(appId)?.package) return appId; // isolated .lpk app: grouped under its own entry
const a = linuxAppFor(appId);
return a ? a.id : `linux:${appId || w.id}`;
}
diff --git a/sdk/hardware.jsx b/sdk/hardware.jsx
new file mode 100644
index 0000000..66afc61
--- /dev/null
+++ b/sdk/hardware.jsx
@@ -0,0 +1,362 @@
+// hardware.jsx — the session side of Settings' hardware pages (docs/SETTINGS.md):
+//
+// displays store with lord.display.list() (outputs, modes, Night Shift, backlight)
+// applyDisplay change resolution/refresh/rotation/main display live, with the 15-second
+// "Keep these display settings?" countdown (<DisplayConfirm />, drawn by the system)
+// night Night Shift scheduler: sunset to sunrise (from the time zone's coordinates, never
+// from the network) or custom hours, with a 30-minute fade, plus "on until tomorrow"
+// battery store with lord.power.state(); low-battery notice; battery in the menu bar
+// idle screen off / lock / sleep after N minutes (deadlines live in lord-server)
+// bluetooth store with lord.bt.state(); pairing requests (<BluetoothPrompt />)
+// timedate NTP state from timedated (read-only)
+// menuClock(d) the menu bar clock with the format chosen in Settings → Date & Time
+//
+// Everything arrives as __lordHw(kind, data) from lord-server (ui/js_hw.c): no polling.
+import { createElement as h, useEffect, useState } from 'react';
+import { View, Text } from '@lordos/runtime';
+import { createStore, useStore } from './store.js';
+import { settings } from './settings.js';
+import { useTheme } from './theme.js';
+import { t, formatDate, formatTime, weekdayName } from './i18n.js';
+import { notify, dismissNotification } from './notify.js';
+import { linuxAppFor } from './apps.js';
+import { admin } from './admin.js';
+import { registerStatusItem } from './statusitems.js';
+import { TextInput } from './components.jsx';
+
+const has = (name) => typeof lord !== 'undefined' && lord[name] && typeof lord[name] === 'object';
+const call = (fn, fallback) => { try { return fn(); } catch (e) { return fallback; } };
+
+export const displays = createStore(has('display') ? call(() => lord.display.list(), null) : null);
+export const battery = createStore(has('power') ? call(() => lord.power.state(), null) : null);
+export const powerProfiles = createStore(has('power') ? call(() => lord.power.profiles(), null) : null);
+export const bluetooth = createStore(has('bt') ? call(() => lord.bt.state(), null) : null);
+export const timedate = createStore(null);
+export const displayConfirm = createStore(null); // { conn, old, deadline, left }
+const btResults = new Set();
+const ppdResults = new Set();
+
+export const useDisplays = () => useStore(displays);
+export const useBattery = () => useStore(battery);
+export const useBluetooth = () => useStore(bluetooth);
+export const usePowerProfiles = () => useStore(powerProfiles);
+export const useTimedate = () => useStore(timedate);
+export const onBluetoothResult = (fn) => { btResults.add(fn); return () => btResults.delete(fn); };
+export const onPowerProfileResult = (fn) => { ppdResults.add(fn); return () => ppdResults.delete(fn); };
+
+// ---- defaults kept in settings.json ----
+
+export const NIGHT_DEFAULTS = { schedule: 'off', from: 22 * 60, to: 7 * 60, temp: 3400, manual: null };
+export const POWER_DEFAULTS = { offAC: 600, offBattery: 180, lockDelay: 0, sleepAC: 0, sleepBattery: 900, lowBattery: true, menuPercent: true };
+export const CLOCK_DEFAULTS = { hour24: 'auto', date: 'short', seconds: false };
+export const nightPrefs = (s = settings.get()) => ({ ...NIGHT_DEFAULTS, ...(s.night || {}) });
+export const powerPrefs = (s = settings.get()) => ({ ...POWER_DEFAULTS, ...(s.power || {}) });
+export const clockPrefs = (s = settings.get()) => ({ ...CLOCK_DEFAULTS, ...(s.clock || {}) });
+
+// ---- the menu bar clock ----
+
+export function menuClock(d) {
+ const c = clockPrefs();
+ const time = formatTime(d, { seconds: !!c.seconds });
+ if (c.date === 'none') return time;
+ if (c.date === 'weekday') return `${weekdayName(d.getDay())} ${time}`;
+ return `${formatDate(d, 'short')} ${time}`;
+}
+
+// ---- Night Shift ----
+
+const NEUTRAL = 6500;
+const minutesOf = (d) => d.getHours() * 60 + d.getMinutes() + d.getSeconds() / 60;
+
+// Same as night_amount() in server/src/hw/night.c (tested there).
+export function nightAmount(now, from, to, fade = 30) {
+ const len = (((to - from) % 1440) + 1440) % 1440;
+ if (!len) return 0;
+ const d = (((now - from) % 1440) + 1440) % 1440;
+ if (d >= len) return 0;
+ if (fade <= 0) return 1;
+ return Math.max(0, Math.min(1, d / fade, (len - d) / fade));
+}
+
+// Sunset and sunrise today, in local minutes, from the chosen time zone's coordinates.
+export function sunTimes(day = new Date()) {
+ if (!has('display') || !lord.time) return null;
+ const zone = call(() => lord.time.zone(), '');
+ const s = call(() => lord.display.sun(zone, day.getFullYear(), day.getMonth() + 1, day.getDate()), null);
+ if (!s) return null;
+ const local = (utcMin) => {
+ const d = new Date(Date.UTC(day.getFullYear(), day.getMonth(), day.getDate()) + utcMin * 60000);
+ return d.getHours() * 60 + d.getMinutes();
+ };
+ return { sunset: local(s.set), sunrise: local(s.rise) };
+}
+
+// The window (local minutes) when the schedule is on, or null.
+export function nightWindow(p = nightPrefs()) {
+ if (p.schedule === 'custom') return { from: p.from, to: p.to };
+ if (p.schedule === 'sun') {
+ const s = sunTimes();
+ return s ? { from: s.sunset, to: s.sunrise } : { from: NIGHT_DEFAULTS.from, to: NIGHT_DEFAULTS.to };
+ }
+ return null;
+}
+
+function nightTarget(now = new Date()) {
+ const p = nightPrefs();
+ const w = nightWindow(p);
+ let amount = w ? nightAmount(minutesOf(now), w.from, w.to) : 0;
+ if (p.manual && now.getTime() < p.manual.until) amount = p.manual.on ? 1 : 0;
+ return { kelvin: Math.round(NEUTRAL - (NEUTRAL - p.temp) * amount), amount, fading: amount > 0 && amount < 1 };
+}
+
+export const nightActive = () => nightTarget().amount > 0;
+
+// "Turn on until tomorrow" / "off until the next night" (like Control Center on macOS): an override
+// that lasts until the end of the current (or next) scheduled night, or 07:00 without a schedule.
+export function setNightManual(on) {
+ const now = new Date(), m = minutesOf(now), w = nightWindow();
+ const scheduled = w ? nightAmount(m, w.from, w.to, 0) > 0 : false;
+ const manual = on === scheduled ? null
+ : { on: !!on, until: now.getTime() + ((((((w ? w.to : 7 * 60) - m) % 1440) + 1440) % 1440) || 1440) * 60000 };
+ settings.set({ night: { ...nightPrefs(), manual } });
+}
+
+let nightTimer = 0;
+export function nightTick() {
+ clearTimeout(nightTimer);
+ if (!has('display')) return;
+ const { kelvin, fading } = nightTarget();
+ if (call(() => lord.display.temperature(), NEUTRAL) !== kelvin) call(() => lord.display.setTemperature(kelvin));
+ const p = nightPrefs();
+ if (p.schedule === 'off' && !(p.manual && Date.now() < p.manual.until)) return;
+ // next check: every 30 s while fading, else at most 5 minutes (survives clock and zone changes)
+ nightTimer = setTimeout(nightTick, fading ? 30000 : 300000);
+}
+
+// Preview while dragging the warmth slider in Settings.
+export function previewNight(kelvin) { if (has('display')) call(() => lord.display.setTemperature(kelvin)); }
+
+// ---- displays ----
+
+// Applies a mode live and starts the 15-second countdown; keepDisplay() saves it, revert brings back
+// the previous one (also when the countdown runs out with nobody answering).
+export function applyDisplay(out, { w, h: hh, refresh = 0, rotation = 0, conn = out.id }) {
+ if (!has('display')) return false;
+ const d = displays.get();
+ const cur = (d?.outputs || []).find((o) => o.current) || out;
+ const old = { conn: cur.id, w: cur.mode?.w || 0, h: cur.mode?.h || 0, refresh: cur.mode?.refresh || 0, rotation: d?.rotation || 0 };
+ if (!lord.display.apply(conn, w, hh, refresh, rotation)) return false;
+ const prev = displayConfirm.get();
+ displayConfirm.set({ conn, old: prev ? prev.old : old, deadline: Date.now() + 15000, left: 15 });
+ scheduleConfirm();
+ return true;
+}
+
+let confirmTimer = 0;
+function scheduleConfirm() {
+ clearTimeout(confirmTimer);
+ const c = displayConfirm.get();
+ if (!c) return;
+ const left = Math.ceil((c.deadline - Date.now()) / 1000);
+ if (left <= 0) { revertDisplay(); return; }
+ if (left !== c.left) displayConfirm.set({ ...c, left });
+ confirmTimer = setTimeout(scheduleConfirm, 250);
+}
+
+export function keepDisplay() {
+ const c = displayConfirm.get();
+ clearTimeout(confirmTimer);
+ displayConfirm.set(null);
+ if (c && has('display')) lord.display.save(c.conn);
+}
+
+export function revertDisplay() {
+ const c = displayConfirm.get();
+ clearTimeout(confirmTimer);
+ displayConfirm.set(null);
+ if (c && has('display')) lord.display.apply(c.old.conn, c.old.w, c.old.h, c.old.refresh, c.old.rotation);
+}
+
+// System dialogs are drawn outside the theme's provider: light or dark from the user's setting.
+function useSystemTokens() {
+ const th = useTheme();
+ const mode = useStore(settings, (s) => s.mode);
+ return mode === 'light' ? { ...th, mode: 'light', windowBg: '#f6f6f8', text: '#1d1d1f', textDim: 'rgba(60,60,67,0.62)',
+ separator: 'rgba(0,0,0,0.12)', control: '#e2e2e7' } : th;
+}
+
+export function DisplayConfirm() {
+ const c = useStore(displayConfirm);
+ const th = useSystemTokens();
+ if (!c) return null;
+ return h(View, { style: { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center',
+ backgroundColor: 'rgba(0,0,0,0.25)', zIndex: 100001 } },
+ h(View, { style: { width: 340, borderRadius: 14, padding: 22, gap: 10, alignItems: 'center', backgroundColor: th.windowBg,
+ border: `1px solid ${th.separator}`, boxShadow: '0 20px 60px rgba(0,0,0,0.45)' } },
+ h(DisplayGlyph, { size: 48, color: th.accent }),
+ h(Text, { style: { fontSize: 14, fontWeight: 700, color: th.text, textAlign: 'center' } }, t('prefs.display.keepTitle')),
+ h(Text, { style: { fontSize: 12, color: th.textDim, textAlign: 'center', lineHeight: 1.4 } }, t('prefs.display.keepBody', { count: c.left })),
+ h(View, { style: { flexDirection: 'row', gap: 10, marginTop: 8, alignSelf: 'stretch' } },
+ h(DialogButton, { label: t('prefs.display.revert'), onClick: revertDisplay, th }),
+ h(DialogButton, { label: t('prefs.display.keep'), onClick: keepDisplay, primary: true, th }))));
+}
+
+export function DisplayGlyph({ size = 40, color = '#0a84ff' }) {
+ const w = size, hh = size * 0.68;
+ return h(View, { style: { width: w, height: size, alignItems: 'center' } },
+ h(View, { style: { width: w, height: hh, borderRadius: size * 0.08, border: `${Math.max(2, size / 18)}px solid ${color}`, backgroundColor: 'rgba(10,132,255,0.12)' } }),
+ h(View, { style: { width: size * 0.12, height: size * 0.14, backgroundColor: color } }),
+ h(View, { style: { width: size * 0.42, height: Math.max(2, size / 18), borderRadius: 2, backgroundColor: color } }));
+}
+
+function DialogButton({ label, onClick, primary, th }) {
+ const [hover, setHover] = useState(false);
+ return h(View, { onClick, onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
+ style: { flex: 1, height: 30, borderRadius: 8, alignItems: 'center', justifyContent: 'center',
+ backgroundColor: primary ? th.accent : th.control, opacity: hover ? 0.85 : 1 } },
+ h(Text, { style: { fontSize: 13, fontWeight: 600, color: primary ? '#fff' : th.text } }, label));
+}
+
+// ---- idle: screen off, lock, sleep ----
+
+export function applyIdle() {
+ if (!has('display')) return;
+ const p = powerPrefs();
+ const ac = battery.get()?.onAC !== false;
+ const off = ac ? p.offAC : p.offBattery;
+ const lock = p.lockDelay < 0 || !off ? 0 : off + p.lockDelay;
+ call(() => lord.display.setIdle(off || 0, lock, (ac ? p.sleepAC : p.sleepBattery) || 0));
+}
+
+function onIdle(stage) {
+ if (stage === 'lock' && typeof lord.session !== 'undefined' && lord.session.managed()) lord.session.lock();
+ if (stage === 'sleep') admin.run('power-suspend', '', undefined, { quiet: true }).catch((e) => console.log(`suspender: ${e.message}`));
+}
+
+// ---- battery: low-battery notice and the menu bar item ----
+
+let lowNotified = 100;
+function checkLow(b) {
+ if (!b || !b.hasBattery) return;
+ if (b.charging || b.onAC) { lowNotified = 100; return; }
+ if (!powerPrefs().lowBattery || b.percent < 0) return;
+ const level = b.percent <= 5 ? 5 : b.percent <= 10 ? 10 : b.percent <= 20 ? 20 : 100;
+ if (level >= lowNotified || level === 100) return;
+ lowNotified = level;
+ notify({ app: 'settings', title: t(level === 5 ? 'prefs.power.criticalTitle' : 'prefs.power.lowTitle'),
+ body: t('prefs.power.lowBody', { pct: b.percent }), sticky: level === 5 });
+}
+
+export function BatteryGlyph({ percent, charging, color, width = 24 }) {
+ const hh = Math.round(width / 2);
+ const fill = Math.max(0, Math.min(100, percent < 0 ? 0 : percent));
+ const low = !charging && percent >= 0 && percent <= 20;
+ return h(View, { style: { flexDirection: 'row', alignItems: 'center', direction: 'ltr' } },
+ h(View, { style: { width, height: hh, borderRadius: 3, border: `1.2px solid ${color}`, padding: 1.5, opacity: 0.95 } },
+ h(View, { style: { width: `${fill}%`, height: '100%', borderRadius: 1.5, backgroundColor: low ? '#ff453a' : charging ? '#30d158' : color } })),
+ h(View, { style: { width: 2, height: hh * 0.4, borderRadius: 1, backgroundColor: color, opacity: 0.7, marginLeft: 1 } }),
+ charging ? h(Text, { style: { position: 'absolute', left: width / 2 - 4, top: -2, fontSize: 10, color: '#fff' } }, '⚡') : null);
+}
+
+function BatteryStatus({ color, height }) {
+ const b = useBattery();
+ const s = useStore(settings);
+ if (!b || !b.hasBattery) return null;
+ const p = powerPrefs(s);
+ return h(View, { style: { height, paddingHorizontal: 6, flexDirection: 'row', alignItems: 'center', gap: 5 } },
+ p.menuPercent && b.percent >= 0 ? h(Text, { style: { fontSize: 12, fontWeight: 500, color } }, `${b.percent}%`) : null,
+ h(BatteryGlyph, { percent: b.percent, charging: b.charging, color }));
+}
+
+// ---- Bluetooth pairing requests (drawn by the system, like macOS) ----
+
+export function BluetoothPrompt() {
+ const st = useBluetooth();
+ const th = useSystemTokens();
+ const [value, setValue] = useState('');
+ const p = st?.prompt;
+ useEffect(() => setValue(''), [p?.id]);
+ if (!p) return null;
+ const typed = p.kind === 'pin' || p.kind === 'passkey';
+ const shows = p.kind === 'confirm' || p.kind === 'display-pin' || p.kind === 'display-passkey';
+ const answer = (ok) => lord.bt.answer(p.id, ok, typed ? value : null);
+ const valid = !typed || (p.kind === 'pin' ? /^[A-Za-z0-9]{1,16}$/.test(value) : /^\d{1,6}$/.test(value));
+ return h(View, { style: { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'flex-start',
+ backgroundColor: 'rgba(0,0,0,0.3)', zIndex: 100000 } },
+ h(View, { style: { marginTop: 90, width: 340, borderRadius: 14, padding: 22, gap: 10, alignItems: 'center', backgroundColor: th.windowBg,
+ border: `1px solid ${th.separator}`, boxShadow: '0 20px 60px rgba(0,0,0,0.45)' } },
+ h(View, { style: { width: 46, height: 46, borderRadius: 23, backgroundColor: '#0a84ff', alignItems: 'center', justifyContent: 'center' } },
+ h(Text, { style: { fontSize: 24, fontWeight: 700, color: '#fff' } }, 'ᛒ')),
+ h(Text, { style: { fontSize: 14, fontWeight: 700, color: th.text, textAlign: 'center' } }, t(`prefs.bt.prompt.${p.kind}.title`, { name: p.name })),
+ h(Text, { style: { fontSize: 12, color: th.textDim, textAlign: 'center', lineHeight: 1.4 } }, t(`prefs.bt.prompt.${p.kind}.body`, { name: p.name })),
+ shows && p.value ? h(Text, { style: { fontSize: 28, fontWeight: 700, color: th.text, letterSpacing: 4, marginVertical: 4, direction: 'ltr' } }, p.value) : null,
+ typed ? h(View, { style: { alignSelf: 'stretch' } }, h(TextInput, { value, onChange: setValue, autoFocus: true, placeholder: t(`prefs.bt.prompt.${p.kind}.placeholder`),
+ onSubmit: () => valid && answer(true), onCancel: () => answer(false) })) : null,
+ h(View, { style: { flexDirection: 'row', gap: 10, marginTop: 8, alignSelf: 'stretch' } },
+ p.kind.startsWith('display-')
+ ? h(DialogButton, { label: t('prefs.bt.prompt.cancel'), onClick: () => answer(false), th })
+ : [h(DialogButton, { key: 'n', label: t(p.kind === 'service' || p.kind === 'authorize' ? 'prefs.bt.prompt.deny' : 'prefs.bt.prompt.cancel'), onClick: () => answer(false), th }),
+ h(DialogButton, { key: 'y', label: t(p.kind === 'service' || p.kind === 'authorize' ? 'prefs.bt.prompt.allow' : 'prefs.bt.prompt.pair'), primary: true, th,
+ onClick: () => valid && answer(true) })])));
+}
+
+// ---- Linux apps' notifications (org.freedesktop.Notifications, server/src/hw/notifyd.c) ----
+
+const fromLinux = new Map(); // D-Bus id → our notification id
+function linuxNotify(n) {
+ if (!n || !n.id) return;
+ const app = linuxAppFor(n.desktop || n.app);
+ const key = `linux:${app?.desktopId || n.desktop || n.app || 'app'}`;
+ const prev = fromLinux.get(n.id);
+ if (prev) dismissNotification(prev, 'replaced');
+ const reason = { closed: 2, expired: 1, action: 2, replaced: 0, remote: 0 };
+ const id = notify({
+ app: key, label: app?.name || n.app, title: n.title, body: n.body, sticky: n.urgency === 2,
+ timeout: n.timeout > 0 ? n.timeout : 6000,
+ actions: (n.actions || []).filter(([k]) => k !== 'default').map(([k, label]) => ({ id: k, label, run: () => lord.notifyd.action(n.id, k) })),
+ onClose: (why) => { if (fromLinux.get(n.id) === id) fromLinux.delete(n.id); if (reason[why]) lord.notifyd.closed(n.id, reason[why]); },
+ });
+ if (id) fromLinux.set(n.id, id);
+}
+
+// ---- events from lord-server ----
+
+globalThis.__lordHw = (kind, data) => {
+ switch (kind) {
+ case 'display': displays.set(data); break;
+ case 'idle': onIdle(data?.stage); break;
+ case 'power': {
+ const wasAC = battery.get()?.onAC;
+ battery.set(data);
+ checkLow(data);
+ if (data?.onAC !== wasAC) applyIdle();
+ break;
+ }
+ case 'bt': case 'bt-prompt': bluetooth.set(data); break;
+ case 'bt-result': for (const fn of btResults) { try { fn(data); } catch (e) { console.log(`bt: ${e}`); } } break;
+ case 'ppd': powerProfiles.set(data); break;
+ case 'ppd-result': for (const fn of ppdResults) { try { fn(data); } catch (e) { console.log(`ppd: ${e}`); } } break;
+ case 'timedate': timedate.set(data); break;
+ case 'notify': linuxNotify(data); break;
+ case 'notify-close': { const own = fromLinux.get(data?.id); if (own) dismissNotification(own, 'remote'); break; }
+ default: break;
+ }
+};
+
+// Called once by startShell: Night Shift, idle timers and the battery item.
+export function startHardware() {
+ if (!has('display')) return;
+ nightTick();
+ applyIdle();
+ let last = '';
+ settings.subscribe(() => {
+ const s = settings.get();
+ const key = JSON.stringify([s.night, s.power]);
+ if (key === last) return;
+ last = key;
+ nightTick();
+ applyIdle();
+ });
+ registerStatusItem('battery', BatteryStatus, 5);
+ checkLow(battery.get());
+}
diff --git a/sdk/help.js b/sdk/help.js
index 50d2f79..de9dcb4 100644
--- a/sdk/help.js
+++ b/sdk/help.js
@@ -1,30 +1,37 @@
-// help.js — artículos de la app Ayuda (assets/help/<idioma>/<id>.md) y el recorrido de bienvenida.
+// help.js — articles of the Help app (assets/help/<lang>/<id>.md) and the welcome tour.
//
-// help.list() → [{ id, title, app, section, order, keywords }] en el idioma de la interfaz
-// help.read(id) → { id, title, app, section, keywords, body } o null
-// help.open(id) → abre Ayuda en ese artículo
-// help.search(texto) → [{ id, title, score, snippet }]
-// help.startTour() → abre «Bienvenido a LordOS»
+// help.list() → [{ id, title, app, section, order, keywords }] in the interface language
+// help.read(id) → { id, title, app, section, keywords, body } or null
+// help.open(id) → opens Help on that article
+// help.search(text) → [{ id, title, score, snippet }]
+// help.startTour() → opens "Welcome to LordOS"
//
-// Cada artículo es markdown con un encabezado:
+// English is the default language: every article exists in assets/help/en, and es/pt (or any other
+// language) are translations. The list is the English one plus any extra articles of the interface
+// language; each article is read in the interface language and falls back to English when that
+// language does not have it.
+//
+// Each article is markdown with a header:
// ---
-// title: Reloj
-// app: clock (la app que explica, para el botón «Abrir»)
-// section: apps (grupo en la barra lateral: start, desktop, apps, system, settings)
+// title: Clock
+// app: clock (the app it explains, for the "Open" button)
+// section: apps (sidebar group: start, desktop, apps, system, settings)
// order: 10
-// keywords: alarma, temporizador
+// keywords: alarm, timer
// ---
-// Los enlaces especiales del texto: [Abrir Ajustes → Red](settings:network), [Archivos](app:files)
-// y [otro artículo](help:spotlight). Spotlight indexa los artículos (registerSpotlightSource).
-// Los lee lord.help (server/src/ui/js_help.c), solo de la carpeta assets/help de LordOS.
+// Special links in the text: [Open Settings → Network](settings:network), [Files](app:files)
+// and [another article](help:spotlight). Spotlight indexes the articles (registerSpotlightSource).
+// They are read by lord.help (server/src/ui/js_help.c), only from LordOS's assets/help folder.
import { locale, t } from './i18n.js';
import { settings } from './settings.js';
import { wm, getApp, isLiveSystem } from './windows.js';
import { registerSpotlightSource } from './spotlight.js';
+const DEFAULT_LANG = 'en';
const has = () => typeof lord.help !== 'undefined';
-const langOf = () => String(locale.get().lang || 'en').split('-')[0];
-const cache = new Map(); // 'es' → { list, bodies: Map }
+const langOf = () => String(locale.get().lang || DEFAULT_LANG).split('-')[0];
+const lists = new Map(); // 'es' → raw list of that language
+const bodies = new Map(); // 'es/clock' → parsed article (with the fallback applied)
function parse(txt) {
const out = { body: txt, meta: {} };
@@ -38,36 +45,52 @@ function parse(txt) {
return out;
}
-function langData(lang) {
- if (cache.has(lang)) return cache.get(lang);
+function rawList(lang) {
+ if (lists.has(lang)) return lists.get(lang);
let list = [];
try { list = has() ? lord.help.list(lang) : []; } catch (e) { list = []; }
- const d = { list: list.sort((a, b) => (a.order || 0) - (b.order || 0) || a.title.localeCompare(b.title)), bodies: new Map() };
- cache.set(lang, d);
- return d;
+ lists.set(lang, list);
+ return list;
+}
+
+const byOrder = (a, b) => (a.order || 0) - (b.order || 0) || a.title.localeCompare(b.title);
+
+// English articles, replaced by the translated ones where they exist, plus the articles only the
+// interface language has.
+function mergedList(lang) {
+ const base = rawList(DEFAULT_LANG);
+ if (lang === DEFAULT_LANG) return base.slice().sort(byOrder);
+ const own = new Map(rawList(lang).map((a) => [a.id, a]));
+ const out = base.map((a) => own.get(a.id) || a);
+ for (const a of own.values()) if (!base.some((b) => b.id === a.id)) out.push(a);
+ return out.sort(byOrder);
}
-// el idioma de la interfaz; si no tiene artículos, inglés
-function current() {
- const l = langOf();
- const d = langData(l);
- return d.list.length ? [l, d] : ['en', langData('en')];
+function readRaw(lang, id) {
+ try { return has() ? lord.help.read(lang, id) : null; } catch (e) { return null; }
}
const fold = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
+let listCache = null; // { lang, list }
+
export const help = {
available: has,
- list: () => current()[1].list,
+ list() {
+ const lang = langOf();
+ if (!listCache || listCache.lang !== lang) listCache = { lang, list: mergedList(lang) };
+ return listCache.list;
+ },
read(id) {
- const [lang, d] = current();
- if (d.bodies.has(id)) return d.bodies.get(id);
- let txt = null;
- try { txt = has() ? lord.help.read(lang, id) : null; } catch (e) { txt = null; }
+ const lang = langOf();
+ const key = `${lang}/${id}`;
+ if (bodies.has(key)) return bodies.get(key);
+ let txt = readRaw(lang, id);
+ if (txt == null && lang !== DEFAULT_LANG) txt = readRaw(DEFAULT_LANG, id); // not translated yet
if (txt == null) return null;
const p = parse(txt);
const a = { id, title: p.meta.title || id, app: p.meta.app || '', section: p.meta.section || '', keywords: p.meta.keywords || '', body: p.body };
- d.bodies.set(id, a);
+ bodies.set(key, a);
return a;
},
open(id) { wm.open('help', { args: { article: id } }); },
@@ -89,14 +112,14 @@ export const help = {
const raw = a.body.replace(/[#*`>[\]()_]/g, '').replace(/\s+/g, ' ');
const k = fold(raw).indexOf(q);
let from = Math.max(0, k - 60);
- while (from > 0 && from < k && raw[from - 1] !== ' ') from++; // empieza en una palabra entera
+ while (from > 0 && from < k && raw[from - 1] !== ' ') from++; // start at a whole word
snippet = `${from > 0 ? '…' : ''}${raw.slice(from, k + 140).trim()}`;
}
out.push({ id: a.id, title: a.title, score, snippet: snippet || a.body.replace(/^#.*$/m, '').replace(/\s+/g, ' ').trim().slice(0, 180) });
}
return out.sort((x, y) => y.score - x.score);
},
- // Qué hacer con un enlace del texto. Devuelve true si lo atendió.
+ // What to do with a link in the text. Returns true if it handled it.
link(url) {
const u = String(url || '');
let m;
@@ -107,7 +130,7 @@ export const help = {
},
};
-// Spotlight: los artículos de Ayuda
+// Spotlight: the Help articles
registerSpotlightSource('help', (q, query) => {
if (!getApp('help') || q.length < 2) return [];
return help.search(query).slice(0, 4).map((r) => ({
@@ -116,13 +139,13 @@ registerSpotlightSource('help', (q, query) => {
}));
});
-// Primer ingreso: «Bienvenido a LordOS», una sola vez (settings.welcomeShown). En el live lo que
-// se abre es el instalador.
+// First login: "Welcome to LordOS", only once (settings.welcomeShown). On the live system the
+// installer opens instead.
export function maybeStartTour() {
if (settings.get().welcomeShown || isLiveSystem() || !getApp('help') || !has()) return;
settings.set({ welcomeShown: true });
setTimeout(() => help.startTour(), 1200);
}
-// al cambiar el idioma, se vuelven a leer
-locale.subscribe(() => cache.clear());
+// when the language changes, everything is read again
+locale.subscribe(() => { lists.clear(); bodies.clear(); listCache = null; });
diff --git a/sdk/i18n.js b/sdk/i18n.js
index 6c443b0..4ffbcc6 100644
--- a/sdk/i18n.js
+++ b/sdk/i18n.js
@@ -153,6 +153,8 @@ export const appName = (app) => (app ? (lookup(locale.get().lang, `apps.${app.id
// ---- formatos (fecha, hora, números) ----
+const clock24 = () => settings.get().clock?.hour24 || 'auto';
+
// Como en macOS: nombres de días y meses en el idioma de la interfaz; orden de la fecha,
// separadores y reloj de 12/24 h según la región (es_AR, pt_BR, en_US…).
function formats() {
@@ -165,7 +167,8 @@ function formats() {
return {
...names,
date: { ...(names.date || {}), numeric: r.date?.numeric || names.date?.numeric, ...(own ? r.date : {}) },
- decimal: r.decimal, group: r.group, hour12: r.hour12,
+ // Settings → Date & Time can force a 24-hour or 12-hour clock over the region's
+ decimal: r.decimal, group: r.group, hour12: clock24() === '24' ? false : clock24() === '12' ? true : r.hour12,
am: own ? r.am : names.am || r.am, pm: own ? r.pm : names.pm || r.pm,
};
}
@@ -183,7 +186,7 @@ export function formatDate(d, style = 'short') {
});
}
-// Nombre del día de la semana (0 = domingo) en el idioma de la interfaz: weekdayName(1) → "lun".
+// Weekday name (0 = Sunday) in the interface language: weekdayName(1) → "Mon".
export function weekdayName(wd, short = true) {
const f = formats();
return (short ? f.weekdaysShort : f.weekdays)?.[wd] ?? String(wd);
diff --git a/sdk/index.js b/sdk/index.js
index 357737a..4ce9e21 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -44,13 +44,14 @@ export { packages, packageList, refreshPackages, packageFile, loadWasm } from '.
import { refreshPackages } from './packages.js';
export {
windows, wm, useWindows, configureWindows, getApp, listApps, isLiveSystem, appIdOf, workArea, appMenus, useAppMenus, windowTitle, appRegistry, appMenuClick,
+ registerBuiltinApp,
} from './windows.js';
export { WindowShell, WINDOW_EDGE } from './windowshell.jsx';
export { term } from './terminal.js';
export { clipboard, clipboardHistory, clipboardPanel, clipboardKind } from './clipboard.js';
export { spotlight, spotlightOpen, calc as spotlightCalc, convert as spotlightConvert } from './spotlight.js';
export { registerSpotlightSource } from './spotlight.js';
-// avisos de la sesión, íconos de estado de la barra, Reloj (alarmas) y Ayuda (docs/SISTEMA.md)
+// session notifications, menu bar status items, Clock (alarms) and Help (docs/SYSTEM.md)
export { notify, dismissNotification, useNotifications, notifications, notifyHistory, clearNotifyHistory, NotificationBanner } from './notify.js';
export { registerStatusItem, StatusItems, statusItems } from './statusitems.js';
export { clockAlarms, clockTimer, timerStart, timerPause, timerResume, timerReset, timerLeft, stopwatch, swStart, swStop, swLap, swReset, swElapsed, nextAlarm, nextFire } from './alarms.js';
@@ -69,11 +70,24 @@ export {
AppHost, useAppWindow, useKeyboard, focusToken, restoreFocus, pasteIntoFocused, FloatingWindows, useWindowState,
} from './components.jsx';
import { FloatingWindows } from './components.jsx';
+export {
+ ToolbarButton, ToolbarGroup, Toolbar, ToolbarSpacer, ToolbarDivider, MenuButton, SearchField, EmptyState, GroupBox, FormRow, spacing, typeScale, controlSize,
+} from './controls.jsx';
export { media, useMedia, usePlayer, nowPlaying, useNowPlaying, NowPlayingTile, mediaFormatTime, thumbFor, useThumb, userDirs } from './media.js';
export { disks, useDisks } from './disks.js';
-export { backup, useBackup, backupStatus } from './backup.js'; // Copias de seguridad (docs/SISTEMA.md)
-export { vaultAvailable, vaultRequest, onVaultEvent, keyring, autofill, autofillReveal, KeyringPrompt } from './vault.js'; // Contraseñas y llavero (docs/CONTRASENAS.md)
+export { backup, useBackup, backupStatus } from './backup.js'; // Backups (docs/SYSTEM.md)
+export { vaultAvailable, vaultRequest, onVaultEvent, keyring, autofill, autofillReveal, KeyringPrompt, AutofillButton } from './vault.js'; // Contraseñas y llavero (docs/CONTRASENAS.md)
import { KeyringPrompt } from './vault.js';
+// Settings' hardware pages (docs/SETTINGS.md): displays, Night Shift, battery, Bluetooth, idle, clock
+export {
+ displays, useDisplays, applyDisplay, keepDisplay, revertDisplay, displayConfirm, DisplayGlyph, nightPrefs, NIGHT_DEFAULTS, nightWindow,
+ nightActive, nightAmount, setNightManual, previewNight, nightTick, sunTimes, battery, useBattery, BatteryGlyph, powerPrefs, POWER_DEFAULTS,
+ powerProfiles, usePowerProfiles, onPowerProfileResult, bluetooth, useBluetooth, onBluetoothResult, timedate, useTimedate, menuClock, clockPrefs,
+ CLOCK_DEFAULTS, applyIdle,
+} from './hardware.jsx';
+import { DisplayConfirm, BluetoothPrompt, startHardware } from './hardware.jsx';
+export { DEFAULT_CATEGORIES, defaultFor, setDefaultFor, candidatesFor, defaultOpenerId, nativeOf } from './defaults.js';
+export { notifyPrefs, appNotifyPrefs, setAppNotifyPrefs, dndActive, NOTIFY_DEFAULTS } from './notify.js';
// ---- temas instalados ----
@@ -124,8 +138,9 @@ export function startShell(element) {
render(createElement(LocaleRoot, null, element));
// ISO live: el asistente de instalación se abre solo, al frente
if (isLiveSystemOf() && getAppOf('installer')) setTimeout(() => wmOf.open('installer'), 300);
- startAlarms(); // alarmas y temporizador del Reloj, con la app cerrada
- maybeStartTour(); // «Bienvenido a LordOS», la primera vez
+ startAlarms(); // Clock alarms and timer, with the app closed
+ maybeStartTour(); // "Welcome to LordOS", the first time
+ startHardware(); // Night Shift, idle timers, battery in the menu bar (hardware.jsx)
}
// Al cambiar el idioma se vuelve a montar toda la interfaz (las ventanas, pestañas y
@@ -133,5 +148,5 @@ export function startShell(element) {
function LocaleRoot({ children }) {
const { lang, region } = useStore(locale);
const rev = useStore(screenRev);
- return createElement(Fragment, { key: `${lang}|${region}` }, rev ? cloneElement(children, { screenRev: rev }) : children, createElement(ClipboardPanel), createElement(SpotlightPanel), createElement(ClipboardToast), createElement(RemoteBadge), createElement(ImeOverlay), createElement(FloatingWindows), createElement(PermissionPrompt), createElement(EmojiPanel), createElement(PrintDialog), createElement(Powerbox), createElement(NotificationBanner), createElement(KeyringPrompt));
+ return createElement(Fragment, { key: `${lang}|${region}` }, rev ? cloneElement(children, { screenRev: rev }) : children, createElement(ClipboardPanel), createElement(SpotlightPanel), createElement(ClipboardToast), createElement(RemoteBadge), createElement(ImeOverlay), createElement(FloatingWindows), createElement(PermissionPrompt), createElement(EmojiPanel), createElement(PrintDialog), createElement(Powerbox), createElement(NotificationBanner), createElement(KeyringPrompt), createElement(BluetoothPrompt), createElement(DisplayConfirm));
}
diff --git a/sdk/logs.js b/sdk/logs.js
index 57c366d..2161f05 100644
--- a/sdk/logs.js
+++ b/sdk/logs.js
@@ -1,4 +1,4 @@
-// logs.js — registros para la app Registros (lord.logs, server/src/ui/js_logs.c; docs/SISTEMA.md).
+// logs.js — registros para la app Registros (lord.logs, server/src/ui/js_logs.c; docs/SYSTEM.md).
//
// await logs.query({ scope: 'user'|'system', since, until, prio, kernel, match, grep, limit })
// → [{ t (µs), s, p, pid, uid, k, id, u, b, m }] (lo lee un hilo de lord-server, como el
diff --git a/sdk/notify.js b/sdk/notify.js
index 0ddaf3b..6a7fd51 100644
--- a/sdk/notify.js
+++ b/sdk/notify.js
@@ -1,16 +1,16 @@
-// notify.js — avisos de la sesión (como las notificaciones de macOS o GNOME).
+// notify.js — session notifications (like macOS or GNOME notifications).
//
-// const id = notify({ app: 'backup', title: 'Copia terminada', body: '1234 archivos',
-// actions: [{ id: 'open', label: 'Abrir', run: () => wm.open('backup') }],
+// const id = notify({ app: 'backup', title: 'Backup done', body: '1234 files',
+// actions: [{ id: 'open', label: 'Open', run: () => wm.open('backup') }],
// sound: true, sticky: false, timeout: 6000 })
// dismissNotification(id)
-// useNotifications() → los avisos en pantalla; notifyHistory (store) → los de esta sesión
+// useNotifications() → the banners on screen; notifyHistory (store) → this session's notifications
//
-// <NotificationBanner /> lo monta startShell, así que se ve con cualquier tema: arriba, del
-// lado del final de la línea (a la derecha; a la izquierda en árabe o hebreo), debajo de la barra
-// del tema (workArea). Un aviso se va solo a los `timeout` ms, salvo los `sticky` (alarmas), que
-// esperan a que se toque una acción o la ×. Un clic en el aviso corre la primera acción.
-// Los textos los pasa la app ya traducidos (t()). El historial vive solo en memoria.
+// <NotificationBanner /> is mounted by startShell, so it shows with any theme: at the top, on the
+// end side of the line (right; left in Arabic or Hebrew), below the theme's bar (workArea). A
+// notification goes away after `timeout` ms, except `sticky` ones (alarms), which wait until an
+// action or the × is pressed. Clicking the banner runs the first action.
+// The app passes texts already translated (t()). The history lives in memory only.
import { createElement as h, useEffect, useState } from 'react';
import { View, Text } from '@lordos/runtime';
import { createStore, useStore } from './store.js';
@@ -18,21 +18,66 @@ import { useTheme } from './theme.js';
import { direction, formatTime, appName } from './i18n.js';
import { getApp, workArea } from './windows.js';
import { sound } from './sound.js';
+import { settings } from './settings.js';
+import { perms } from './privacy.js';
import { screen } from '@lordos/runtime';
const MAX_SHOWN = 4, HISTORY = 50;
-export const notifications = createStore([]); // en pantalla, el más nuevo primero
+export const notifications = createStore([]); // on screen, newest first
export const notifyHistory = createStore([]);
let seq = 1;
const timers = new Map();
-export function notify({ app = '', title = '', body = '', actions = [], sound: withSound = true, sticky = false, timeout = 6000, onClose } = {}) {
+// ---- Settings → Notifications (docs/SETTINGS.md): per-app style, Do Not Disturb, grouping ----
+//
+// settings.notifications = { dnd: false | until (ms), schedule: { on, from, to } (local minutes),
+// grouping: 'app' | 'off', apps: { [app]: { allow, style: 'banner' | 'alert' | 'none', sound, lock } },
+// seen: [app ids that have notified] }
+// app is an app id ('backup'), a package id, or 'linux:<desktop id or name>' for Linux apps
+// (org.freedesktop.Notifications, server/src/hw/notifyd.c). For .lpk packages "allow" is the
+// sandbox's "notifications" permission (the same switch as in Privacy & Security).
+export const NOTIFY_DEFAULTS = { dnd: false, schedule: { on: false, from: 22 * 60, to: 7 * 60 }, grouping: 'app', apps: {}, seen: [] };
+export const notifyPrefs = (s = settings.get()) => ({ ...NOTIFY_DEFAULTS, ...(s.notifications || {}) });
+const isPackage = (app) => { try { return !!getApp(app)?.package; } catch (e) { return false; } };
+export function appNotifyPrefs(app, s = settings.get()) {
+ const p = { allow: true, style: 'banner', sound: true, lock: true, ...(notifyPrefs(s).apps[app] || {}) };
+ if (isPackage(app)) p.allow = perms.get(app, 'notifications') !== 'deny';
+ return p;
+}
+export function setAppNotifyPrefs(app, patch) {
+ if (isPackage(app) && 'allow' in patch) perms.set(app, 'notifications', patch.allow ? 'allow' : 'deny');
+ settings.set((s) => {
+ const p = notifyPrefs(s);
+ return { ...s, notifications: { ...p, apps: { ...p.apps, [app]: { ...(p.apps[app] || {}), ...patch } } } };
+ });
+}
+export function dndActive(now = new Date(), s = settings.get()) {
+ const p = notifyPrefs(s);
+ if (p.dnd === true || (typeof p.dnd === 'number' && now.getTime() < p.dnd)) return true;
+ if (!p.schedule?.on) return false;
+ const m = now.getHours() * 60 + now.getMinutes(), len = (((p.schedule.to - p.schedule.from) % 1440) + 1440) % 1440;
+ return len > 0 && (((m - p.schedule.from) % 1440) + 1440) % 1440 < len;
+}
+function remember(app) {
+ const p = notifyPrefs();
+ if (!app || p.seen.includes(app)) return;
+ settings.set((s) => ({ ...s, notifications: { ...notifyPrefs(s), seen: [app, ...notifyPrefs(s).seen].slice(0, 64) } }));
+}
+
+export function notify({ app = '', title = '', body = '', actions = [], sound: withSound = true, sticky = false, timeout = 6000, onClose, label = '' } = {}) {
+ app = String(app);
+ const ap = appNotifyPrefs(app);
+ remember(app);
+ if (!ap.allow) return 0; // not delivered at all (like macOS)
const id = seq++;
- const n = { id, app: String(app), title: String(title), body: String(body), actions: Array.isArray(actions) ? actions.slice(0, 3) : [], sticky: !!sticky, time: Date.now(), onClose };
+ const n = { id, app, label: String(label), title: String(title), body: String(body), actions: Array.isArray(actions) ? actions.slice(0, 3) : [],
+ sticky: !!sticky || ap.style === 'alert', time: Date.now(), onClose };
+ notifyHistory.set((l) => [{ id, app: n.app, label: n.label, title: n.title, body: n.body, time: n.time }, ...l].slice(0, HISTORY));
+ // Do Not Disturb or "no banner": kept in the history only, without a sound
+ if (dndActive() || ap.style === 'none') return id;
notifications.set((l) => [n, ...l].slice(0, MAX_SHOWN));
- notifyHistory.set((l) => [{ id, app: n.app, title: n.title, body: n.body, time: n.time }, ...l].slice(0, HISTORY));
- if (withSound) sound.play('notify');
- if (!sticky) timers.set(id, setTimeout(() => dismissNotification(id), Math.max(1500, timeout)));
+ if (withSound && ap.sound) sound.play('notify');
+ if (!n.sticky) timers.set(id, setTimeout(() => dismissNotification(id), Math.max(1500, timeout)));
return id;
}
@@ -67,7 +112,8 @@ function Banner({ n, th }) {
app?.Icon ? h(app.Icon, { size: 34 }) : h(View, { style: { width: 34, height: 34, borderRadius: 8, backgroundColor: th.accent } }),
h(View, { style: { flex: 1, gap: 2 } },
h(View, { style: { flexDirection: 'row', gap: 6 } },
- h(Text, { style: { flex: 1, fontSize: 11, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' } }, app ? appName(app) : ''),
+ h(Text, { style: { flex: 1, fontSize: 11, color: th.textDim, whiteSpace: 'nowrap', overflow: 'hidden', textAlign: 'start' } },
+ `${app ? appName(app) : n.label}${n.more ? ` · +${n.more}` : ''}`),
h(Text, { style: { fontSize: 11, color: th.textDim } }, formatTime(new Date(n.time)))),
h(Text, { style: { fontSize: 13, fontWeight: 700, color: th.text, textAlign: 'start' } }, n.title),
n.body ? h(Text, { style: { fontSize: 12, color: th.text, lineHeight: 1.35, textAlign: 'start' } }, n.body) : null),
@@ -92,5 +138,19 @@ export function NotificationBanner() {
const rtl = direction() === 'rtl';
const left = rtl ? (area.x || 0) + 12 : (area.x || 0) + (area.w || screen.width) - 352;
return h(View, { style: { position: 'absolute', left, top: (area.y || 0) + 10, width: 340, gap: 10 } },
- ...list.map((n) => h(Banner, { key: n.id, n, th })));
+ ...grouped(list).map((n) => h(Banner, { key: n.id, n, th })));
+}
+
+// Grouping by app (Settings → Notifications): the newest banner of each app, with "+N".
+function grouped(list) {
+ if (notifyPrefs().grouping === 'off') return list;
+ const out = [], seen = new Map();
+ for (const n of list) {
+ const k = n.app || n.label;
+ if (seen.has(k)) { seen.get(k).more++; continue; }
+ const g = { ...n, more: 0 };
+ seen.set(k, g);
+ out.push(g);
+ }
+ return out;
}
diff --git a/sdk/packages.js b/sdk/packages.js
index a873f85..882601e 100644
--- a/sdk/packages.js
+++ b/sdk/packages.js
@@ -49,7 +49,12 @@ const isolated = () => typeof lord.apps !== 'undefined' && typeof lord.apps.laun
function Redirect({ id }) {
const win = sdk.useAppWindow();
React.useEffect(() => {
- lord.apps.launchPackage(id);
+ // already running: a plain open focuses its window; «New window» (wm.open(id, { new: true }))
+ // asks the running process for another window (lord-server forwards it over the broker)
+ const running = windows.get().filter((w) => w.args?.pkg && w.args?.appId === id);
+ const wantsNew = win && win.id && String(win.id).includes('#');
+ if (running.length && !wantsNew) wm.focus(running[running.length - 1].id);
+ else lord.apps.launchPackage(id);
if (win && win.id) wm.close(win.id, true);
}, []);
return null;
diff --git a/sdk/spotlight.js b/sdk/spotlight.js
index c9cd711..f080312 100644
--- a/sdk/spotlight.js
+++ b/sdk/spotlight.js
@@ -248,9 +248,9 @@ function loadNotes() {
// ---- secciones de Ajustes ----
-// ---- otras fuentes (artículos de Ayuda, …) ----
+// ---- other sources (Help articles, …) ----
// registerSpotlightSource('help', (q, query, { fold, best }) => [{ key, score, title, subtitle, glyph, preview, run }])
-// q es la búsqueda normalizada (minúsculas, sin acentos). El título de la sección es
+// q is the normalized query (lowercase, no accents). The section title is
// t('shell.spotlight.section.<id>').
const sources = new Map();
export function registerSpotlightSource(id, fn) { sources.set(id, fn); return () => sources.delete(id); }
@@ -320,7 +320,7 @@ function buildResults(raw, apps) {
.map((c) => ({ key: `clip:${c.id || c.time}`, score: 20, title: c.text.replace(/\s+/g, ' ').slice(0, 80), subtitle: t('shell.spotlight.fromClipboard'), glyph: '📋',
preview: { kind: 'text', text: c.text }, run: () => clipboard.use(c), hint: t('shell.spotlight.copy') })));
- // fuentes registradas (Ayuda…)
+ // registered sources (Help…)
for (const [id, fn] of sources) {
let items = [];
try { items = fn(q, query, { fold, best }) || []; } catch (e) { console.error(`spotlight ${id}:`, e); }
diff --git a/sdk/statusitems.js b/sdk/statusitems.js
index 94e2413..1beb5f9 100644
--- a/sdk/statusitems.js
+++ b/sdk/statusitems.js
@@ -1,11 +1,11 @@
-// statusitems.js — íconos de estado en la barra del tema (como los "menu extras" de macOS).
+// statusitems.js — status icons in the theme's bar (like macOS "menu extras").
//
-// const off = registerStatusItem('clock', ClockStatus, 10) // ClockStatus({ color }) dibuja el suyo
-// <StatusItems color={t.menuText} /> // el tema los muestra donde quiera
+// const off = registerStatusItem('clock', ClockStatus, 10) // ClockStatus({ color }) draws its own
+// <StatusItems color={t.menuText} /> // the theme shows them wherever it wants
//
-// Es opcional: un tema que no dibuja <StatusItems /> simplemente no los muestra. Los temas default
-// y classic los ponen junto a los indicadores de privacidad. Un ítem que no tiene nada que mostrar
-// devuelve null.
+// It is optional: a theme that does not draw <StatusItems /> simply doesn't show them. The default
+// and classic themes put them next to the privacy indicators. An item with nothing to show returns
+// null.
import { createElement as h } from 'react';
import { View } from '@lordos/runtime';
import { createStore, useStore } from './store.js';
diff --git a/sdk/vault.js b/sdk/vault.js
index 5a15d3d..51bb458 100644
--- a/sdk/vault.js
+++ b/sdk/vault.js
@@ -9,6 +9,7 @@
// el llavero de la sesión, por app: una app ve solo lo suyo (salvo que el usuario lo comparta)
// autofill(app, { url | service }) → [{ id, title, username }] de Contraseñas (si está abierta)
// <KeyringPrompt /> aviso del sistema para abrir el llavero (lo monta startShell)
+// <AutofillButton app service|url|ssid onFill /> "fill from Passwords" next to a login field
import { createElement as h, useEffect, useState } from 'react';
import { View, Text } from '@lordos/runtime';
import { createStore, useStore } from './store.js';
@@ -87,15 +88,16 @@ export const keyring = {
const hostOf = (u) => String(u || '').replace(/^[a-z]+:\/\//i, '').split(/[/:?#]/)[0].toLowerCase().replace(/^www\./, '');
-// Entradas de Contraseñas que sirven para ese sitio o servicio (solo si la bóveda está abierta).
-export async function autofill(app, { url, service } = {}) {
+// Passwords entries that match a site, a service or a Wi-Fi network (only while the vault is unlocked).
+export async function autofill(app, { url, service, ssid } = {}) {
const host = hostOf(url || service);
- if (!host) return [];
+ if (!host && !ssid) return [];
let list;
try { list = (await vaultRequest('list')).entries || []; } catch (e) { return []; }
- return list.filter((e) => !e.trash && (hostOf(e.url) === host || hostOf(e.url).endsWith(`.${host}`) || host.endsWith(`.${hostOf(e.url)}`) ||
- String(e.title).toLowerCase().includes(host.split('.')[0])))
- .map((e) => ({ id: e.id, title: e.title, username: e.sub || '' }));
+ const hit = (e) => (ssid ? e.cat === 'wifi' && e.sub === ssid
+ : hostOf(e.url) === host || hostOf(e.url).endsWith(`.${host}`) || (hostOf(e.url) && host.endsWith(`.${hostOf(e.url)}`)) ||
+ String(e.title).toLowerCase().includes(host.split('.')[0]));
+ return list.filter((e) => !e.trash && hit(e)).map((e) => ({ id: e.id, title: e.title, username: e.sub || '' }));
}
// El usuario eligió una: usuario y contraseña (la contraseña sale de lord-vault solo ahora).
@@ -141,3 +143,35 @@ export function KeyringPrompt() {
h(Button, { label: t('passwords.cancel'), onClick: () => done(false) }),
h(Button, { label: busy ? t('passwords.unlock.working') : t('passwords.keyring.unlock'), primary: true, onClick: submit }))));
}
+
+// ---- "fill from Passwords" button for native login fields ----
+//
+// <AutofillButton app="settings" service="wifi:Casa" ssid="Casa" onFill={({ username, password }) => …} />
+// Offers what the app saved in the session keyring (service) and matching Passwords entries.
+// The secret leaves lord-vault only when the user picks one.
+export function AutofillButton({ app, service, url, ssid, onFill }) {
+ const th = useTheme();
+ const [open, setOpen] = useState(false);
+ const [items, setItems] = useState(null);
+ const load = async () => {
+ const out = [];
+ if (service) { try { const k = await keyring.get(app, { service }); if (k) out.push({ kind: 'kr', title: k.label || service, username: k.account, secret: k.secret }); } catch (e) { /* locked */ } }
+ for (const e of await autofill(app, { url, service: url ? undefined : service, ssid })) out.push({ kind: 'pw', ...e });
+ setItems(out);
+ };
+ const pick = async (it) => {
+ setOpen(false);
+ if (it.kind === 'kr') { onFill({ username: it.username, password: it.secret }); return; }
+ try { onFill(await autofillReveal(it.id)); } catch (e) { /* locked */ }
+ };
+ return h(View, null,
+ h(View, { onClick: () => { setOpen(!open); if (!open) load(); }, style: { width: 30, height: 30, borderRadius: 7, alignItems: 'center', justifyContent: 'center',
+ backgroundColor: th.control } }, h(Text, { style: { fontSize: 14 } }, '🔑')),
+ open ? h(View, { style: { position: 'absolute', top: 34, right: 0, width: 260, zIndex: 100, padding: 4, borderRadius: 9, backgroundColor: th.windowBg,
+ border: `1px solid ${th.separator}`, boxShadow: '0 10px 28px rgba(0,0,0,0.4)' } },
+ h(Text, { style: { fontSize: 11, fontWeight: 600, color: th.textDim, padding: 6 } }, t('passwords.autofill.title')),
+ items == null ? null : !items.length ? h(Text, { style: { fontSize: 12, color: th.textDim, padding: 6 } }, t('passwords.autofill.none'))
+ : items.map((it, i) => h(View, { key: i, onClick: () => pick(it), style: { padding: 6, borderRadius: 6 } },
+ h(Text, { style: { fontSize: 13, color: th.text } }, it.title),
+ it.username ? h(Text, { style: { fontSize: 11, color: th.textDim } }, it.username) : null))) : null);
+}
diff --git a/sdk/wayland.js b/sdk/wayland.js
index 26bdef0..729f333 100644
--- a/sdk/wayland.js
+++ b/sdk/wayland.js
@@ -126,8 +126,8 @@ locale.subscribe(() => setTimeout(() => {
// los clics vuelven a la app por lord.broker.menuClick. Ver docs/PRIVACIDAD.md.
function applyAppMenus(app) {
if (typeof lord === 'undefined' || !lord.broker || typeof lord.broker.menus !== 'function') return;
- const win = windows.get().find((w) => surfaceOf(w.id) > 0 && w.args?.appId === app);
- if (!win) return;
+ const wins = windows.get().filter((w) => surfaceOf(w.id) > 0 && w.args?.appId === app); // every window of the app
+ if (!wins.length) return;
let raw;
try { raw = lord.broker.menus(app); } catch (e) { return; }
const groups = (Array.isArray(raw) ? raw : []).map((g) => ({
@@ -140,6 +140,6 @@ function applyAppMenus(app) {
return row;
}),
}));
- wm.setMenus(win.id, groups);
+ for (const win of wins) wm.setMenus(win.id, groups);
}
if (typeof globalThis !== 'undefined') globalThis.__lordApplyAppMenus = applyAppMenus;
diff --git a/server/Makefile b/server/Makefile
index 7765d5e..b005a48 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -50,9 +50,9 @@ QJS_OBJ := $(patsubst %,build/qjs/%.o,quickjs libregexp libunicode cutils dtoa)
MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c
# Medios (src/media, docs/MEDIOS.md): solo el lado de lord-server. FFmpeg lo enlaza solo lord-media.
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
+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
# Modo app: lord-server --app <id> corre una app .lpk como cliente Wayland aislado (src/app)
-APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c
+APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.c
SRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/ime.c src/wl/wl.c \
src/ui/node.c src/ui/style.c src/ui/layout.c src/ui/text.c src/ui/image.c \
src/ui/paint.c src/ui/js.c src/ui/js_sys.c src/ui/js_term.c src/ui/js_wasm.c src/wasm/wasm.c src/wasm/wasm_run.c src/ui/js_sound.c src/ui/js_net.c src/sound/snd.c src/sound/pulse.c src/ui/otf.c src/ui/fonts.c \
@@ -82,20 +82,20 @@ SRC += $(TP_SRC)
# Contraseñas (src/vault/dbus.c, docs/CONTRASENAS.md).
WM_SRC := src/cursor.c src/ui/grab.c src/ui/js_wm.c src/ui/portal.c src/vault/dbus.c
SRC += $(WM_SRC)
-# Reloj y Ayuda (docs/SISTEMA.md): zonas horarias con un lector TZif propio y los artículos de ayuda
+# Clock and Help (docs/SYSTEM.md): time zones with our own TZif reader, and the help articles
CLOCK_SRC := src/ui/tzif.c src/ui/js_help.c
SRC += $(CLOCK_SRC)
-# Registros (docs/SISTEMA.md): lector propio del journal de systemd, la acción logs-system y lord.logs
+# Registros (docs/SYSTEM.md): lector propio del journal de systemd, la acción logs-system y lord.logs
LOGS_SRC := src/logs/journal.c src/logs/logs_admin.c src/ui/js_logs.c
SRC += $(LOGS_SRC)
HDR += $(wildcard src/logs/*.h)
-# Copias de seguridad (docs/SISTEMA.md): instantáneas con enlaces duros en un hilo de baja prioridad
+# Backups (docs/SYSTEM.md): hard-linked snapshots in a low-priority thread
BACKUP_SRC := src/backup/engine.c src/backup/crypt.c src/backup/backup.c src/ui/js_backup.c
SRC += $(BACKUP_SRC)
HDR += $(wildcard src/backup/*.h)
-# el cifrado opcional usa Monocypher (vendorizado, third_party/monocypher; su objeto es el de mk/vault.mk)
+# optional encryption uses Monocypher (vendored in third_party/monocypher; the object comes from mk/vault.mk)
build/obj/backup/%.o: CPPFLAGS += -isystem ../third_party/monocypher
-# Discos (docs/SISTEMA.md): discos, particiones y montajes sin root, SMART propio y las acciones disk-*
+# Disks (docs/SYSTEM.md): disks, partitions and mounts without root, our own SMART and the disk-* actions
DISK_SRC := src/disk/disk.c src/disk/smart.c src/disk/disk_admin.c src/ui/js_disk.c
SRC += $(DISK_SRC)
HDR += $(wildcard src/disk/*.h)
@@ -185,7 +185,7 @@ build/sandbox-test: tests/sandbox_test.c src/sec/sandbox.c src/sec/cgroup.c src/
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -D_GNU_SOURCE -o $@ tests/sandbox_test.c src/sec/sandbox.c src/sec/cgroup.c -lpthread
build/sign-test: tests/sign_test.c src/sec/json.c src/sec/sign.c src/lpk.c src/pkg/crypto.c build/obj/ui/stb.o $(wildcard src/sec/*.h) src/lpk.h src/pkg/crypto.h
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -DLORD_SIGN_TEST -o $@ tests/sign_test.c src/sec/json.c src/sec/sign.c src/lpk.c src/pkg/crypto.c build/obj/ui/stb.o -lm
-# zonas horarias del Reloj: TZif y reglas POSIX contra glibc (docs/SISTEMA.md)
+# Clock time zones: TZif and POSIX rules against glibc (docs/SYSTEM.md)
test: build/tzif-test
build/tzif-test: tests/tzif_test.c src/ui/tzif.c src/ui/tzif.h
@mkdir -p build
@@ -208,7 +208,7 @@ build/dnsmap-test: tests/dnsmap_test.c src/fw/dnsmap.c src/fw/rules.c src/fw/fwm
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/dnsmap_test.c src/fw/dnsmap.c src/fw/rules.c src/fw/fwmap.c src/sec/json.c
./$@ || { rm -f $@; exit 1; }
-# motor de Copias de seguridad: instantánea, enlaces duros, restaurar, retención, cortes, exclusiones
+# backup engine: snapshots, hard links, restore, retention, interruptions, exclusions, encryption
build/lord-server: build/obj/vault/monocypher.o
test: build/backup-test
build/backup-test: tests/backup_test.c src/backup/engine.c src/backup/crypt.c src/fsops.c src/backup/engine.h src/backup/crypt.h src/fsops.h build/obj/vault/monocypher.o
@@ -307,7 +307,7 @@ build/lord-server: $(OBJ) build/obj/ui/stb.o $(QJS_OBJ) $(WL_OBJ)
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
SESSIOND_OBJ := build/obj/remote/sessiond.o build/obj/remote/sess.o build/obj/remote/monitor.o build/obj/remote/conn.o \
- build/obj/remote/enc.o build/obj/remote/pages.o build/obj/sec/cgroup.o build/obj/remote/netsup.o
+ build/obj/remote/enc.o build/obj/remote/pages.o build/obj/sec/cgroup.o build/obj/remote/netsup.o build/obj/remote/cgsup.o
build/obj/remote/pages.o: src/remote/login.html src/remote/client.html
@mkdir -p $(dir $@)
$(LD) -r -b binary -z noexecstack -o $@ src/remote/login.html src/remote/client.html
@@ -355,8 +355,8 @@ build/doc-test: tests/doc_test.c src/doc/wire.c src/sec/json.c $(wildcard src/do
# Contraseñas y llavero del sistema (docs/CONTRASENAS.md): reglas en mk/vault*.mk
include $(sort $(wildcard mk/*.mk))
-# lord-netd (docs/RED.md, «La red es del sistema»): admin.c con LORD_NETD (solo las acciones net-*)
-# más la red y el motor de paquetes (net-vpn-enable). Solo libc; lo lanza y vigila lord-sessiond.
+# lord-netd (docs/RED.md, "The network belongs to the system"): admin.c with LORD_NETD (net-* actions
+# only) plus networking and the package engine (net-vpn-enable). libc only; lord-sessiond runs it.
all: build/lord-netd
NETD_OBJ := build/obj/netd/admin.o build/obj/netd/netd.o $(NET_SRC:src/%.c=build/obj/%.o) $(PKG_SRC:src/%.c=build/obj/%.o) build/obj/ui/stb.o
build/obj/netd/admin.o: src/admin.c $(HDR)
@@ -368,17 +368,17 @@ build/obj/netd/netd.o: src/net/netd.c src/admin.h
build/lord-netd: $(NETD_OBJ)
$(CC) $(LDFLAGS) -o $@ $^ -lm -lpthread
-# analizadores de SMART (ATA y NVMe) de la app Discos: datos armados a mano, sano/advertencia/falla
+# SMART parsers (ATA and NVMe) of the Disks app: hand-built data, healthy/warning/failing
test: build/smart-test
build/smart-test: tests/smart_test.c src/disk/smart.c src/disk/disk.h src/admin.h
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/smart_test.c src/disk/smart.c
./$@ || { rm -f $@; exit 1; }
-# prueba a mano de las acciones disk-* (root y dispositivos de verdad; no está en `test`)
+# manual test of the disk-* actions (root and real devices; not part of `test`)
build/disk-cli: tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/disk_admin.c src/pkg/crypto.c src/disk/disk.h
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/disk_cli.c src/disk/disk.c src/disk/smart.c src/disk/disk_admin.c src/pkg/crypto.c
-# carpetas del usuario (src/users/homedirs.c): idiomas, user-dirs.dirs, no pisar, no seguir enlaces
+# user folders (src/users/homedirs.c): languages, user-dirs.dirs, no overwriting, no symlinks
test: build/homedirs-test
build/homedirs-test: tests/homedirs_test.c src/users/homedirs.c src/users/homedirs.h
@mkdir -p build
diff --git a/server/mk/mail.mk b/server/mk/mail.mk
new file mode 100644
index 0000000..6b080d2
--- /dev/null
+++ b/server/mk/mail.mk
@@ -0,0 +1,27 @@
+# Mail, Calendar, Contacts and Reminders (docs/MAIL.md). lord-maild is the sandboxed helper that
+# speaks IMAP, SMTP, CalDAV and CardDAV; with lord-sessiond it is the only binary linking OpenSSL.
+MAIL_PARSE := src/mail/xml.c src/mail/mime.c src/mail/html.c src/mail/imapp.c src/mail/ical.c src/mail/vcard.c
+MAIL_HDR := $(wildcard src/mail/*.h) src/doc/wire.h src/sec/json.h src/ui/tzif.h
+# parsers: IMAP, MIME, HTML sanitizer, iCalendar, vCard and XML, with a small fuzzer (tests/mail_test.c)
+test: build/mail-test
+build/mail-test: tests/mail_test.c $(MAIL_PARSE) $(MAIL_HDR) src/doc/wire.c src/sec/json.c src/ui/tzif.c
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/mail_test.c $(MAIL_PARSE) src/doc/wire.c src/sec/json.c src/ui/tzif.c -lm
+ ./$@ || { rm -f $@; exit 1; }
+# the same under AddressSanitizer + UBSan (not part of `test`: slower)
+build/mail-test-asan: tests/mail_test.c $(MAIL_PARSE) $(MAIL_HDR) src/doc/wire.c src/sec/json.c src/ui/tzif.c
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer $(WARN) -std=c11 -o $@ tests/mail_test.c $(MAIL_PARSE) src/doc/wire.c src/sec/json.c src/ui/tzif.c -lm
+ ./$@
+.PHONY: mail-asan
+mail-asan: build/mail-test-asan
+# lord-server's side: start lord-maild, its channel, the connector (allowed servers only) and lord.mail
+MAILC_OBJ := build/obj/mail/mailc.o build/obj/ui/js_mail.o
+build/lord-server: $(MAILC_OBJ)
+$(MAILC_OBJ): $(wildcard src/mail/*.h) src/ui/js_mail.h
+# the connector's policy: allowed endpoints and the public-address check for remote images
+test: build/mailc-test
+build/mailc-test: tests/mailc_test.c src/mail/mailc.c src/mail/mailc.h src/doc/wire.c src/sec/json.c
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/mailc_test.c src/mail/mailc.c src/doc/wire.c src/sec/json.c -lpthread -lm
+ ./$@ || { rm -f $@; exit 1; }
diff --git a/server/mk/settings.mk b/server/mk/settings.mk
new file mode 100644
index 0000000..df117a2
--- /dev/null
+++ b/server/mk/settings.mk
@@ -0,0 +1,23 @@
+# Settings' hardware pages (src/hw, docs/SETTINGS.md): displays (EDID, modes, Night Shift),
+# Bluetooth (BlueZ over our own D-Bus client), battery and power, date and time, default apps.
+# Objects are added to lord-server as extra prerequisites ($^ in its link rule takes them).
+HW_SRC := src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/jbuf.c src/hw/display.c \
+ src/hw/uevent.c src/hw/sysbus.c src/hw/bt.c src/hw/ppd.c src/hw/hw.c src/hw/hw_admin.c src/hw/defaults.c src/hw/notifyd.c src/ui/js_hw.c
+HW_HDR := $(wildcard src/hw/*.h) src/ui/js_hw.h src/kms.h src/vault/dbus.h
+HW_OBJ := $(HW_SRC:src/%.c=build/obj/%.o)
+$(HW_OBJ): $(HW_HDR)
+build/lord-server: $(HW_OBJ)
+# pure parts: EDID, mode selection, gamma/temperature/sun math, mimeapps.list and globs2, power_supply,
+# and the admin actions' validators
+test: build/settings-hw-test
+build/settings-hw-test: tests/settings_hw_test.c src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/hw_admin.c src/sec/json.c $(HW_HDR)
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/settings_hw_test.c src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/hw_admin.c src/sec/json.c -lm
+ ./$@ || { rm -f $@; exit 1; }
+# BlueZ parsing (GetManagedObjects, PropertiesChanged, Battery1, paths, state JSON) without a bus
+test: build/bt-test
+BT_TEST_SRC := tests/bt_test.c src/hw/bt.c src/hw/sysbus.c src/hw/jbuf.c src/vault/dbus.c src/sec/json.c
+build/bt-test: $(BT_TEST_SRC) $(HW_HDR)
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(BT_TEST_SRC)
+ ./$@ || { rm -f $@; exit 1; }
diff --git a/server/src/admin.c b/server/src/admin.c
index 89de74a..5784901 100644
--- a/server/src/admin.c
+++ b/server/src/admin.c
@@ -34,6 +34,7 @@
#include "users/users_admin.h"
#include "disk/disk.h"
#include "logs/logs_admin.h"
+#include "hw/hw_admin.h"
#include <ctype.h>
#include <errno.h>
@@ -64,8 +65,8 @@
static int out_fd = -1; /* socket, o el pipe hacia el ayudante en un hijo */
static int cur_id;
-/* lord-netd (la red del sistema, ver más abajo): en su proceso principal las respuestas van al
- * cliente que pidió (cur_client) y los avisos (id 0) a todos. En los hijos vale 0. */
+/* lord-netd (the system network, see below): in its main process, replies go to the client that
+ * asked (cur_client) and events (id 0) to everyone. It is 0 in child processes. */
static int netd_main;
static int cur_client = -1;
static void netd_route(int id, const char *line, size_t n);
@@ -238,7 +239,7 @@ typedef struct {
int done; /* ya mandó OK/ERR */
int raw; /* programa externo: cada línea se envuelve en un EVENT */
char name[32]; /* residente */
- int client; /* lord-netd: cliente que pidió la acción (-1 ninguno) */
+ int client; /* lord-netd: client that requested the action (-1: none) */
char buf[2048];
size_t len;
} Kid;
@@ -285,8 +286,8 @@ int admin_daemon_fork(const char *name, void (*fn)(void *), void *arg) {
pid_t pid = fork();
if (pid == 0) {
close(p[0]);
- /* solo el pipe: ni el socket de lord-server ni, en lord-netd, su lock y su socket (si no,
- * un DHCP que sobrevive al lord-netd muerto le impediría arrancar al siguiente) */
+ /* only the pipe: neither lord-server's socket nor, in lord-netd, its lock and socket
+ * (otherwise a DHCP client outliving a dead lord-netd would keep the next one from starting) */
int keep = fcntl(p[1], F_DUPFD, 3);
for (int f = 3; f < 1024; f++) if (f != keep) close(f);
out_fd = keep;
@@ -376,7 +377,7 @@ static void a_langpack(const AdminReq *r, const char *a, size_t n) { (void)r; (v
static const struct { const char *name; ActionFn fn; int flags; } actions[] = {
#ifdef LORD_NETD
- /* lord-netd: solo la red (docs/RED.md, «La red es del sistema») */
+ /* lord-netd: networking only (docs/RED.md, "The network belongs to the system") */
NET_ADMIN_ACTIONS
#else
{ "locale-gen", a_locale_gen, A_FORK },
@@ -390,7 +391,8 @@ static const struct { const char *name; ActionFn fn; int flags; } actions[] = {
USERS_ADMIN_ACTIONS
DISK_ADMIN_ACTIONS
LOGS_ADMIN_ACTIONS
-#endif /* LORD_NETD: las acciones de otros módulos van arriba de esta línea */
+ HW_ADMIN_ACTIONS
+#endif /* LORD_NETD: other modules' actions go above this line */
};
#define N_ACTIONS (sizeof actions / sizeof actions[0])
@@ -595,13 +597,13 @@ static void act_langpack(const char *arg) {
#endif /* LORD_NETD */
-/* Saca del búfer los pedidos completos "<id> <acción> <largo>\n<argumento>" y llama a fn con cada
- * uno (el argumento en memoria propia, terminado en 0; fn no lo libera). */
+/* Takes the complete requests "<id> <action> <length>\n<argument>" out of the buffer and calls fn
+ * for each (the argument in its own NUL-terminated memory; fn does not free it). */
typedef void (*ReqFn)(int id, const char *action, char *arg, size_t len, void *ctx);
static void parse_requests(char *in, size_t *inlen, ReqFn fn, void *ctx) {
for (;;) {
char *nl = memchr(in, '\n', *inlen < 160 ? *inlen : 160);
- if (!nl) { if (*inlen >= 160) *inlen = 0; break; } /* encabezado inválido: se descarta */
+ if (!nl) { if (*inlen >= 160) *inlen = 0; break; } /* invalid header: dropped */
*nl = 0;
int id = 0;
char action[64] = "";
@@ -609,20 +611,20 @@ static void parse_requests(char *in, size_t *inlen, ReqFn fn, void *ctx) {
int ok = sscanf(in, "%d %63s %lu", &id, action, &len) == 3 && id > 0 && len <= ADMIN_ARG_MAX;
size_t head = (size_t)(nl - in) + 1;
if (!ok) { memmove(in, in + head, *inlen - head); *inlen -= head; continue; }
- if (*inlen < head + len) { *nl = '\n'; break; } /* falta el argumento */
+ if (*inlen < head + len) { *nl = '\n'; break; } /* argument not complete yet */
char *arg = malloc(len + 1);
if (arg) { memcpy(arg, in + head, len); arg[len] = 0; }
memmove(in, in + head + len, *inlen - head - len);
*inlen -= head + len;
if (!arg) continue;
fn(id, action, arg, len, ctx);
- explicit_bzero(arg, len); /* puede traer una contraseña (user-add, user-passwd, Wi-Fi) */
+ explicit_bzero(arg, len); /* may carry a password (user-add, user-passwd, Wi-Fi) */
free(arg);
}
}
-/* Corre la acción a (ya autorizada) con req: en un hijo si es A_FORK (que solo se queda con el pipe
- * de su salida). client: en lord-netd, a quién van sus respuestas (-1 en el ayudante de la sesión). */
+/* Runs action a (already authorized) with req: in a child if A_FORK (which keeps only its output
+ * pipe). client: in lord-netd, who gets its replies (-1 in a session's helper). */
static void run_action(size_t a, AdminReq *req, int id, const char *arg, size_t len, int client) {
if (actions[a].flags & A_FORK) {
Kid *k = kid_new();
@@ -631,7 +633,7 @@ static void run_action(size_t a, AdminReq *req, int id, const char *arg, size_t
pid_t pid = fork();
if (pid == 0) {
close(p[0]);
- /* sin los sockets de lord-server ni de los clientes de lord-netd: solo el pipe */
+ /* none of lord-server's or lord-netd's client sockets: only the pipe */
int keep = fcntl(p[1], F_DUPFD, 3);
for (int f = 3; f < 1024; f++) if (f != keep) close(f);
out_fd = keep;
@@ -652,21 +654,21 @@ static size_t find_action(const char *name) {
return a;
}
-/* ---- la red del sistema: lord-netd (docs/RED.md, «La red es del sistema») ----
+/* ---- the system network: lord-netd (docs/RED.md, "The network belongs to the system") ----
*
- * La red no es de una sesión: la levanta lord-netd, un proceso root chico que lanza y vigila
- * lord-sessiond al arrancar el equipo (antes de que alguien entre). Atiende solo las acciones
- * net-* de esta misma tabla, por /run/lordos/netd.sock (0600, solo root: los ayudantes de las
- * sesiones). Cada ayudante se presenta con "HELLO <usuario>" y lord-netd vuelve a calcular si ese
- * usuario es administrador. Las respuestas van al ayudante que pidió; los avisos (id 0), a todos.
- * Los procesos residentes (DHCP, wpa_supplicant, VPN) son hijos de lord-netd: sobreviven a que
- * las sesiones entren y salgan. Sin lord-netd (lord-server suelto, en desarrollo) el ayudante de
- * la sesión corre la red él mismo, como antes. */
+ * The network doesn't belong to a session: lord-netd brings it up, a small root process that
+ * lord-sessiond starts and supervises at boot (before anyone logs in). It serves only the net-*
+ * actions of this same table, on /run/lordos/netd.sock (0600, root only: the sessions' helpers).
+ * Each helper introduces itself with "HELLO <user>" and lord-netd works out again whether that
+ * user is an administrator. Replies go to the helper that asked; events (id 0) go to all of them.
+ * The resident processes (DHCP, wpa_supplicant, VPN) are lord-netd's children, so they outlive
+ * sessions logging in and out. Without lord-netd (a standalone lord-server, in development) the
+ * session's helper runs the network itself, as before. */
#define NETD_SOCK "/run/lordos/netd.sock"
-#define NETD_MARK "/run/lordos/netd.enabled" /* lo crea lord-sessiond al lanzar lord-netd */
-#define NETD_VPNS "/run/lordos/netd-vpns" /* VPN prendidas: vuelven si lord-netd se reinicia */
+#define NETD_MARK "/run/lordos/netd.enabled" /* created by lord-sessiond when it starts lord-netd */
+#define NETD_VPNS "/run/lordos/netd-vpns" /* VPNs that are up: restored if lord-netd restarts */
-/* lado del ayudante de la sesión */
+/* session helper side */
static int netd_fd = -1;
static char netd_user[64];
static char netd_buf[8192];
@@ -701,7 +703,7 @@ static void netd_lost(void) {
netd_npending = 0;
}
-/* Lo que llega de lord-netd va tal cual a lord-server (los id son los de esta sesión). */
+/* What lord-netd sends goes to lord-server unchanged (the ids are this session's). */
static void netd_read(void) {
ssize_t r = read(netd_fd, netd_buf + netd_len, sizeof netd_buf - 1 - netd_len);
if (r < 0 && (errno == EINTR || errno == EAGAIN)) return;
@@ -724,7 +726,7 @@ static void netd_read(void) {
if (netd_len >= sizeof netd_buf - 1) netd_len = 0;
}
-/* 1: no hay lord-netd (la sesión corre la red); 0: se le pasó; -1: tendría que estar y no está. */
+/* 1: no lord-netd (the session runs the network); 0: forwarded; -1: it should be there and isn't. */
static int netd_forward(int id, const char *action, const char *arg, size_t len) {
if (netd_connect()) return access(NETD_MARK, F_OK) == 0 ? -1 : 1;
char head[128];
@@ -770,8 +772,8 @@ static void helper(int fd, const char *user) {
char *in = malloc(ADMIN_ARG_MAX + 512);
size_t inlen = 0;
if (!in) _exit(1);
- /* lord-netd: conectarse ya (para recibir los avisos de la red) y volver a conectarse cuando
- * lord-sessiond lo reinicia (aparece de nuevo el socket: inotify, sin sondear) */
+ /* lord-netd: connect now (to receive network events) and reconnect when lord-sessiond restarts
+ * it (the socket appears again: inotify, no polling) */
netd_connect();
int ino = inotify_init1(IN_CLOEXEC | IN_NONBLOCK);
if (ino >= 0 && inotify_add_watch(ino, "/run/lordos", IN_CREATE | IN_MOVED_TO) < 0) { close(ino); ino = -1; }
@@ -810,12 +812,12 @@ static void helper(int fd, const char *user) {
_exit(0);
}
-/* lado de lord-netd */
+/* lord-netd side */
#define NETD_MAX_CLIENTS 32
typedef struct {
- int fd; /* -1: libre */
- int hello; /* ya dijo quién es */
+ int fd; /* -1: free */
+ int hello; /* has said who it is */
char user[64], home[PATH_MAX];
AdminReq req;
char *in;
@@ -826,7 +828,7 @@ static NetdClient clients[NETD_MAX_CLIENTS];
static void netd_route(int id, const char *line, size_t n) {
if (id == 0) {
- /* aviso: a todas las sesiones, y al registro (journal, por lord-sessiond) */
+ /* event: to every session, and to the log (the journal, through lord-sessiond) */
const char *t = memchr(line, ' ', n);
if (t) { t = memchr(t + 1, ' ', n - (size_t)(t + 1 - line)); }
if (t) fprintf(stderr, "lord-netd: %.*s", (int)(n - (size_t)(t + 1 - line)), t + 1);
@@ -842,10 +844,10 @@ static void netd_drop(int c) {
clients[c].fd = -1;
free(clients[c].in);
clients[c].in = NULL;
- for (int i = 0; i < MAX_KIDS; i++) if (kids[i].client == c) kids[i].client = -1; /* su respuesta ya no tiene a quién ir */
+ for (int i = 0; i < MAX_KIDS; i++) if (kids[i].client == c) kids[i].client = -1; /* its reply has nowhere to go now */
}
-/* Lista de VPN prendidas (una por línea): para volver a conectarlas si lord-netd se reinicia. */
+/* List of VPNs that are up (one per line): to reconnect them if lord-netd restarts. */
static void netd_vpn_note(const char *name, int up) {
char *t = NULL, line[64];
size_t tl = 0;
@@ -912,9 +914,9 @@ int admin_netd_serve(void) {
umask(022);
prctl(PR_SET_NAME, "lord-netd");
mkdir("/run/lordos", 0755);
- /* uno solo: si ya corre (sobrevivió a un reinicio de lord-sessiond), este se va */
+ /* only one: if one is already running (it outlived a lord-sessiond restart), this one exits */
int lk = open("/run/lordos/netd.lock", O_RDWR | O_CREAT | O_CLOEXEC, 0600);
- if (lk < 0 || flock(lk, LOCK_EX | LOCK_NB)) { fprintf(stderr, "lord-netd: ya hay otro corriendo\n"); return 3; }
+ if (lk < 0 || flock(lk, LOCK_EX | LOCK_NB)) { fprintf(stderr, "lord-netd: another instance is already running\n"); return 3; }
FILE *pf = fopen("/run/lordos/netd.pid", "w");
if (pf) { fprintf(pf, "%d\n", (int)getpid()); fclose(pf); }
for (int i = 0; i < NETD_MAX_CLIENTS; i++) clients[i].fd = -1;
@@ -923,18 +925,18 @@ int admin_netd_serve(void) {
struct sockaddr_un sa = { .sun_family = AF_UNIX };
snprintf(sa.sun_path, sizeof sa.sun_path, "%s.new", NETD_SOCK);
unlink(sa.sun_path);
- mode_t old = umask(077); /* 0600: solo root (los ayudantes de las sesiones) */
+ mode_t old = umask(077); /* 0600: root only (the sessions' helpers) */
int bad = lfd < 0 || bind(lfd, (struct sockaddr *)&sa, sizeof sa) || listen(lfd, 16);
umask(old);
- if (bad || rename(sa.sun_path, NETD_SOCK)) { fprintf(stderr, "lord-netd: no se pudo abrir %s: %s\n", NETD_SOCK, strerror(errno)); return 1; }
+ if (bad || rename(sa.sun_path, NETD_SOCK)) { fprintf(stderr, "lord-netd: cannot open %s: %s\n", NETD_SOCK, strerror(errno)); return 1; }
- /* la red al arrancar el equipo: configs guardadas, DHCP, Wi-Fi conocidas y DNS */
+ /* the network at boot: saved configs, DHCP, known Wi-Fi and DNS */
netd_main = 1;
static char sys_user[] = "root", sys_home[] = "/root";
AdminReq sys = { .user = sys_user, .home = sys_home, .uid = 0, .gid = 0, .admin = 1 };
cur_client = -1;
net_act_restore(&sys, "system", 6);
- /* las VPN que estaban prendidas antes de un reinicio de lord-netd (no las de antes de apagar) */
+ /* VPNs that were up before lord-netd restarted (not those from before a shutdown) */
{
FILE *f = fopen(NETD_VPNS, "r");
char line[64];
@@ -944,11 +946,11 @@ int admin_netd_serve(void) {
}
if (f) fclose(f);
}
- fprintf(stderr, "lord-netd: listo (%s)\n", NETD_SOCK);
+ fprintf(stderr, "lord-netd: ready (%s)\n", NETD_SOCK);
for (;;) {
struct pollfd pfd[1 + NETD_MAX_CLIENTS + MAX_KIDS];
- int ref[1 + NETD_MAX_CLIENTS + MAX_KIDS]; /* >= 0 cliente; < 0: -(kid + 1) */
+ int ref[1 + NETD_MAX_CLIENTS + MAX_KIDS]; /* >= 0: client; < 0: -(kid + 1) */
int n = 0;
pfd[n] = (struct pollfd){ lfd, POLLIN, 0 }; ref[n++] = 0;
for (int i = 0; i < NETD_MAX_CLIENTS; i++)
@@ -976,7 +978,7 @@ int admin_netd_serve(void) {
for (int i = 0; i < NETD_MAX_CLIENTS && slot < 0; i++) if (clients[i].fd < 0) slot = i;
char *in = slot >= 0 ? malloc(ADMIN_ARG_MAX + 512) : NULL;
if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) || cr.uid != 0 || !in) { free(in); close(fd); continue; }
- struct timeval tv = { 2, 0 }; /* una sesión trabada no frena la red */
+ struct timeval tv = { 2, 0 }; /* a stuck session doesn't block the network */
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
clients[slot] = (NetdClient){ .fd = fd, .in = in };
}
diff --git a/server/src/admin.h b/server/src/admin.h
index ee67141..ae21c44 100644
--- a/server/src/admin.h
+++ b/server/src/admin.h
@@ -19,8 +19,8 @@ int admin_known(const char *action); /* ¿está en la lista cer
int admin_send(const char *action, const char *arg, size_t len);
void admin_dispatch(void (*fn)(int id, const char *kind, const char *text));
-/* ---- lord-netd (root, lo lanza lord-sessiond): la red del sistema; ver admin.c y docs/RED.md ---- */
-int admin_netd_serve(void); /* no vuelve salvo por un error */
+/* ---- lord-netd (root, started by lord-sessiond): the system network; see admin.c, docs/RED.md ---- */
+int admin_netd_serve(void); /* returns only on error */
/* ---- lado del ayudante (root): para los módulos que agregan acciones ---- */
diff --git a/server/src/app/appclient.c b/server/src/app/appclient.c
index fe1b461..f700c49 100644
--- a/server/src/app/appclient.c
+++ b/server/src/app/appclient.c
@@ -47,27 +47,63 @@ static struct wl_seat *seat;
static struct wl_pointer *pointer;
static struct wl_keyboard *keyboard;
static struct zxdg_decoration_manager_v1 *decman;
-static struct wl_surface *surf;
-static struct xdg_surface *xsurf;
-static struct xdg_toplevel *top;
-
-static int W = 640, H = 480, cw, ch, configured, closed, need_render = 1, frame_pending;
-static double px_hx, px_hy; /* última posición del puntero */
-static int ptr_down[8], ptr_btn[8], nptr;
typedef struct { struct wl_buffer *b; uint32_t *px; size_t size; int busy, w, h; } Buf;
-static Buf bufs[2];
+
+/* One toplevel window of the app. The app host (runtime/app-host.js) renders every window as a
+ * child of the React root; `node` is that window's root node, laid out and painted on its own
+ * surface. Key 0 is the main window, created before the sandbox. */
+#define MAX_WINS 16
+typedef struct {
+ int used, key;
+ struct wl_surface *surf;
+ struct xdg_surface *xsurf;
+ struct xdg_toplevel *top;
+ struct zxdg_toplevel_decoration_v1 *deco;
+ int cw, ch, configured, need_render, frame_pending;
+ int node; /* root node of this window (0 until the app host attaches it) */
+ char title[256];
+ Buf bufs[2];
+} AppWin;
+static AppWin wins[MAX_WINS];
+static int next_key = 1, closed;
+static const char *app_id_str = "";
+static AppWin *ptr_win, *kbd_win; /* window under the pointer / with keyboard focus */
+
+static double px_hx, px_hy; /* last pointer position (surface-local) */
+static int ptr_down[8], ptr_btn[8], nptr;
static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
-/* ---- wl_shm doble búfer ---- */
+static AppWin *win_by_key(int key) { for (int i = 0; i < MAX_WINS; i++) if (wins[i].used && wins[i].key == key) return &wins[i]; return NULL; }
+static AppWin *win_by_surface(struct wl_surface *s) { for (int i = 0; i < MAX_WINS; i++) if (wins[i].used && wins[i].surf == s) return &wins[i]; return NULL; }
+/* The window's root node; the main window falls back to the whole tree (an app host that does not
+ * attach windows, or before its first commit). */
+static Node *win_root(const AppWin *w) {
+ if (!w) return NULL;
+ Node *n = w->node ? node_get(w->node) : NULL;
+ return n ? n : w->key == 0 ? ui.root : NULL;
+}
+
+/* tell the app host (JS): "close" (the compositor asked), "focus" */
+static void win_event(const AppWin *w, const char *type) {
+ char j[96];
+ int n = snprintf(j, sizeof j, "{\"key\":%d,\"type\":\"%s\"}", w->key, type);
+ js_broker_app_event("appwindow", j, (size_t)n);
+}
+
+/* ---- wl_shm double buffer ---- */
static void buf_release(void *d, struct wl_buffer *b) { (void)b; ((Buf *)d)->busy = 0; }
static const struct wl_buffer_listener buf_listener = { buf_release };
-static int make_buffer(Buf *b, int w, int h) {
+static void buf_free(Buf *b) {
if (b->b) { wl_buffer_destroy(b->b); b->b = NULL; }
if (b->px) { munmap(b->px, b->size); b->px = NULL; }
+}
+
+static int make_buffer(Buf *b, int w, int h) {
+ buf_free(b);
size_t stride = (size_t)w * 4, size = stride * h;
int fd = memfd_create("lordos-app", MFD_CLOEXEC);
if (fd < 0 || ftruncate(fd, (off_t)size)) { if (fd >= 0) close(fd); return -1; }
@@ -85,50 +121,61 @@ static int make_buffer(Buf *b, int w, int h) {
return 0;
}
-static const struct wl_callback_listener fl; /* definido abajo */
+static const struct wl_callback_listener fl; /* below */
-/* Layout y pintado de la UI en el búfer. */
-static void render(void) {
- Buf *b = !bufs[0].busy ? &bufs[0] : !bufs[1].busy ? &bufs[1] : NULL;
- if (!b || cw <= 0 || ch <= 0) { need_render = 1; return; }
- if (b->w != cw || b->h != ch) { if (make_buffer(b, cw, ch)) return; }
+/* Layout and paint one window into its buffer. */
+static void render(AppWin *w) {
+ Node *root = win_root(w);
+ if (!root) return; /* the app host has not attached it yet */
+ Buf *b = !w->bufs[0].busy ? &w->bufs[0] : !w->bufs[1].busy ? &w->bufs[1] : NULL;
+ if (!b || w->cw <= 0 || w->ch <= 0) return;
+ if (b->w != w->cw || b->h != w->ch) { if (make_buffer(b, w->cw, w->ch)) return; }
Canvas c;
- canvas_init(&c, b->px, cw, ch, cw);
- ui.width = (float)cw;
- ui.height = (float)ch;
- layout_root(ui.root, (float)cw, (float)ch);
+ canvas_init(&c, b->px, w->cw, w->ch, w->cw);
+ ui.width = (float)w->cw;
+ ui.height = (float)w->ch;
+ layout_root(root, (float)w->cw, (float)w->ch);
canvas_clear(&c, 0x00000000);
- paint_root(&c, ui.root);
+ /* every window shares node coordinates starting at 0,0: no "paint from the video" shortcut
+ * (an empty damage box turns off media_cover_node/opaque_cover_node in paint_root) */
+ ui.damage = (Box){ 0, 0, 0, 0 };
+ paint_root(&c, root);
b->busy = 1;
- wl_surface_attach(surf, b->b, 0, 0);
- wl_surface_damage_buffer(surf, 0, 0, cw, ch);
- struct wl_callback *cb = wl_surface_frame(surf);
- wl_callback_add_listener(cb, &fl, NULL);
- frame_pending = 1;
- wl_surface_commit(surf);
- ui.dirty = 0;
- need_render = 0;
+ wl_surface_attach(w->surf, b->b, 0, 0);
+ wl_surface_damage_buffer(w->surf, 0, 0, w->cw, w->ch);
+ struct wl_callback *cb = wl_surface_frame(w->surf);
+ wl_callback_add_listener(cb, &fl, w);
+ w->frame_pending = 1;
+ wl_surface_commit(w->surf);
+ w->need_render = 0;
}
-static void frame_done(void *d, struct wl_callback *cb, uint32_t t) { (void)d; (void)t; wl_callback_destroy(cb); frame_pending = 0; }
+static void frame_done(void *d, struct wl_callback *cb, uint32_t t) {
+ (void)t;
+ wl_callback_destroy(cb);
+ AppWin *w = d;
+ if (w->used) w->frame_pending = 0;
+}
static const struct wl_callback_listener fl = { frame_done };
/* ---- xdg ---- */
static void xs_configure(void *d, struct xdg_surface *x, uint32_t serial) {
- (void)d;
+ AppWin *w = d;
xdg_surface_ack_configure(x, serial);
- if (!cw || !ch) { cw = W; ch = H; }
- configured = 1;
- need_render = 1;
+ if (!w->cw || !w->ch) { w->cw = 640; w->ch = 480; }
+ w->configured = 1;
+ w->need_render = 1;
}
static const struct xdg_surface_listener xs_listener = { xs_configure };
-static void top_configure(void *d, struct xdg_toplevel *t, int32_t w, int32_t h, struct wl_array *st) {
- (void)d; (void)t; (void)st;
- if (w > 0 && h > 0) { cw = w; ch = h; }
+static void top_configure(void *d, struct xdg_toplevel *t, int32_t wd, int32_t ht, struct wl_array *st) {
+ (void)t; (void)st;
+ AppWin *w = d;
+ if (wd > 0 && ht > 0 && (wd != w->cw || ht != w->ch)) { w->cw = wd; w->ch = ht; w->need_render = 1; }
}
-static void top_close(void *d, struct xdg_toplevel *t) { (void)d; (void)t; closed = 1; }
+/* the compositor asks to close: the app host decides (wm.close, which honours close guards) */
+static void top_close(void *d, struct xdg_toplevel *t) { (void)t; win_event((AppWin *)d, "close"); }
static void top_cfg_bounds(void *d, struct xdg_toplevel *t, int32_t w, int32_t h) { (void)d; (void)t; (void)w; (void)h; }
static void top_caps(void *d, struct xdg_toplevel *t, struct wl_array *c) { (void)d; (void)t; (void)c; }
static const struct xdg_toplevel_listener top_listener = { top_configure, top_close, top_cfg_bounds, top_caps };
@@ -136,10 +183,112 @@ static const struct xdg_toplevel_listener top_listener = { top_configure, top_cl
static void wm_ping(void *d, struct xdg_wm_base *w, uint32_t serial) { (void)d; xdg_wm_base_pong(w, serial); }
static const struct xdg_wm_base_listener wm_listener = { wm_ping };
+/* New toplevel with server-side decoration (the theme draws the frame). Returns it or NULL. */
+static AppWin *win_create(int key, const char *title, int w, int h) {
+ AppWin *a = NULL;
+ for (int i = 0; i < MAX_WINS && !a; i++) if (!wins[i].used) a = &wins[i];
+ if (!a) return NULL;
+ memset(a, 0, sizeof *a);
+ a->used = 1;
+ a->key = key;
+ a->cw = w > 0 ? w : 640;
+ a->ch = h > 0 ? h : 480;
+ a->surf = wl_compositor_create_surface(comp);
+ a->xsurf = xdg_wm_base_get_xdg_surface(wm, a->surf);
+ xdg_surface_add_listener(a->xsurf, &xs_listener, a);
+ a->top = xdg_surface_get_toplevel(a->xsurf);
+ xdg_toplevel_add_listener(a->top, &top_listener, a);
+ xdg_toplevel_set_app_id(a->top, app_id_str); /* the Dock groups every window by this id */
+ snprintf(a->title, sizeof a->title, "%s", title && title[0] ? title : app_id_str);
+ xdg_toplevel_set_title(a->top, a->title);
+ if (decman) {
+ a->deco = zxdg_decoration_manager_v1_get_toplevel_decoration(decman, a->top);
+ zxdg_toplevel_decoration_v1_set_mode(a->deco, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
+ }
+ wl_surface_commit(a->surf);
+ return a;
+}
+
+static void win_destroy(AppWin *a) {
+ if (!a || !a->used) return;
+ if (ptr_win == a) ptr_win = NULL;
+ if (kbd_win == a) kbd_win = NULL;
+ if (a->deco) zxdg_toplevel_decoration_v1_destroy(a->deco);
+ xdg_toplevel_destroy(a->top);
+ xdg_surface_destroy(a->xsurf);
+ wl_surface_destroy(a->surf);
+ buf_free(&a->bufs[0]);
+ buf_free(&a->bufs[1]);
+ a->used = 0;
+ int left = 0;
+ for (int i = 0; i < MAX_WINS; i++) left += wins[i].used;
+ if (!left) closed = 1; /* last window closed: the app ends */
+}
+
+/* ---- lord.appWindows (app host only): the app's own windows ---- */
+
+static JSValue f_win_open(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *title = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(c, argv[0]) : NULL;
+ int32_t w = 640, h = 480;
+ if (argc > 1) JS_ToInt32(c, &w, argv[1]);
+ if (argc > 2) JS_ToInt32(c, &h, argv[2]);
+ if (w < 160 || w > 8192) w = 640;
+ if (h < 100 || h > 8192) h = 480;
+ AppWin *a = next_key < 1 << 20 ? win_create(next_key, title, w, h) : NULL;
+ if (title) JS_FreeCString(c, title);
+ if (!a) return JS_NewInt32(c, -1);
+ next_key++;
+ return JS_NewInt32(c, a->key);
+}
+static JSValue f_win_attach(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int32_t key = -1, node = 0;
+ if (argc < 2 || JS_ToInt32(c, &key, argv[0]) || JS_ToInt32(c, &node, argv[1])) return JS_FALSE;
+ AppWin *a = win_by_key(key);
+ if (!a || !node_get(node)) return JS_FALSE;
+ if (a->node != node) { a->node = node; a->need_render = 1; }
+ return JS_TRUE;
+}
+static JSValue f_win_close(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int32_t key = -1;
+ if (argc > 0) JS_ToInt32(c, &key, argv[0]);
+ win_destroy(win_by_key(key));
+ return JS_UNDEFINED;
+}
+static JSValue f_win_title(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int32_t key = -1;
+ if (argc < 2) return JS_UNDEFINED;
+ JS_ToInt32(c, &key, argv[0]);
+ AppWin *a = win_by_key(key);
+ const char *title = JS_ToCString(c, argv[1]);
+ if (a && title) {
+ const char *want = title[0] ? title : app_id_str;
+ if (strcmp(a->title, want)) { snprintf(a->title, sizeof a->title, "%s", want); xdg_toplevel_set_title(a->top, a->title); }
+ }
+ if (title) JS_FreeCString(c, title);
+ return JS_UNDEFINED;
+}
+static const JSCFunctionListEntry win_funcs[] = {
+ JS_CFUNC_DEF("open", 3, f_win_open), JS_CFUNC_DEF("attach", 2, f_win_attach),
+ JS_CFUNC_DEF("close", 1, f_win_close), JS_CFUNC_DEF("setTitle", 2, f_win_title),
+};
+
+void app_windows_register(JSContext *c, JSValue lord) {
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyFunctionList(c, o, win_funcs, sizeof win_funcs / sizeof win_funcs[0]);
+ JS_SetPropertyStr(c, lord, "appWindows", o);
+}
+
/* ---- entrada ---- */
+/* node under the pointer, in the window the pointer is over */
+static Node *hit_at(void) { Node *r = win_root(ptr_win); return r ? hit_test(r, (float)px_hx, (float)px_hy) : NULL; }
+
static void dispatch_pointer(void) {
- Node *target = hit_test(ui.root, (float)px_hx, (float)px_hy);
+ Node *target = hit_at();
int id = target ? target->id : 0;
js_pointer("move", id, (float)px_hx, (float)px_hy, 0);
for (int i = 0; i < nptr; i++) js_pointer(ptr_down[i] ? "down" : "up", id, (float)px_hx, (float)px_hy, ptr_btn[i]);
@@ -147,9 +296,12 @@ static void dispatch_pointer(void) {
}
static void p_enter(void *d, struct wl_pointer *p, uint32_t s, struct wl_surface *sf, wl_fixed_t x, wl_fixed_t y) {
- (void)d; (void)p; (void)s; (void)sf; px_hx = wl_fixed_to_double(x); px_hy = wl_fixed_to_double(y);
+ (void)d; (void)p; (void)s; ptr_win = win_by_surface(sf); px_hx = wl_fixed_to_double(x); px_hy = wl_fixed_to_double(y);
+}
+static void p_leave(void *d, struct wl_pointer *p, uint32_t s, struct wl_surface *sf) {
+ (void)d; (void)p; (void)s;
+ if (ptr_win && ptr_win->surf == sf) ptr_win = NULL;
}
-static void p_leave(void *d, struct wl_pointer *p, uint32_t s, struct wl_surface *sf) { (void)d; (void)p; (void)s; (void)sf; }
static void p_motion(void *d, struct wl_pointer *p, uint32_t t, wl_fixed_t x, wl_fixed_t y) {
(void)d; (void)p; (void)t; px_hx = wl_fixed_to_double(x); px_hy = wl_fixed_to_double(y); dispatch_pointer();
}
@@ -166,20 +318,20 @@ static void p_stop(void *d, struct wl_pointer *p, uint32_t t, uint32_t a) {
(void)d; (void)p; (void)t; (void)a;
if (!fine_on) return;
fine_on = 0;
- Node *n = hit_test(ui.root, (float)px_hx, (float)px_hy);
+ Node *n = hit_at();
js_gesture("scroll", "end", n ? n->id : 0, (float)px_hx, (float)px_hy, 0, 0, 0, 0);
}
static void p_axis(void *d, struct wl_pointer *p, uint32_t t, uint32_t a, wl_fixed_t v) {
(void)d; (void)p; (void)t;
if (axis_src == WL_POINTER_AXIS_SOURCE_FINGER) {
- Node *n = hit_test(ui.root, (float)px_hx, (float)px_hy);
+ Node *n = hit_at();
if (!fine_on) { fine_on = 1; js_gesture("scroll", "begin", n ? n->id : 0, (float)px_hx, (float)px_hy, 0, 0, 0, 0); }
double val = wl_fixed_to_double(v);
int h = a == WL_POINTER_AXIS_HORIZONTAL_SCROLL;
js_gesture("scroll", "update", n ? n->id : 0, (float)px_hx, (float)px_hy, h ? val : 0, h ? 0 : val, 0, 0);
return;
}
- if (a == WL_POINTER_AXIS_VERTICAL_SCROLL) { Node *n = hit_test(ui.root, (float)px_hx, (float)px_hy); js_pointer("wheel", n ? n->id : 0, (float)px_hx, (float)px_hy, wl_fixed_to_double(v) > 0 ? -1 : 1); }
+ if (a == WL_POINTER_AXIS_VERTICAL_SCROLL) { Node *n = hit_at(); js_pointer("wheel", n ? n->id : 0, (float)px_hx, (float)px_hy, wl_fixed_to_double(v) > 0 ? -1 : 1); }
}
static void p_frame(void *d, struct wl_pointer *p) { (void)d; (void)p; axis_src = -1; }
static void p_noop2(void *d, struct wl_pointer *p, uint32_t a, int32_t b) { (void)d; (void)p; (void)a; (void)b; }
@@ -188,7 +340,7 @@ static const struct wl_pointer_listener p_listener = { p_enter, p_leave, p_motio
/* pellizco y deslizar del touchpad (zwp_pointer_gestures_v1) → onPinch / onSwipe de la app */
static struct zwp_pointer_gestures_v1 *gestures;
static double g_rot;
-static int g_node(void) { Node *n = hit_test(ui.root, (float)px_hx, (float)px_hy); return n ? n->id : 0; }
+static int g_node(void) { Node *n = hit_at(); return n ? n->id : 0; }
static void pi_begin(void *d, struct zwp_pointer_gesture_pinch_v1 *g, uint32_t s, uint32_t t, struct wl_surface *sf, uint32_t f) {
(void)d; (void)g; (void)s; (void)t; (void)sf; (void)f;
g_rot = 0;
@@ -228,7 +380,12 @@ static void gestures_setup(void) {
}
static void k_keymap(void *d, struct wl_keyboard *k, uint32_t fmt, int32_t fd, uint32_t sz) { (void)d; (void)k; (void)fmt; (void)sz; if (fd >= 0) close(fd); }
-static void k_enter(void *d, struct wl_keyboard *k, uint32_t s, struct wl_surface *sf, struct wl_array *keys) { (void)d; (void)k; (void)s; (void)sf; (void)keys; }
+/* keyboard focus moved to one of our windows: the app host raises it (wm.focus) */
+static void k_enter(void *d, struct wl_keyboard *k, uint32_t s, struct wl_surface *sf, struct wl_array *keys) {
+ (void)d; (void)k; (void)s; (void)keys;
+ AppWin *w = win_by_surface(sf);
+ if (w && w != kbd_win) { kbd_win = w; win_event(w, "focus"); }
+}
static void k_leave(void *d, struct wl_keyboard *k, uint32_t s, struct wl_surface *sf) { (void)d; (void)k; (void)s; (void)sf; }
static void k_key(void *d, struct wl_keyboard *k, uint32_t s, uint32_t t, uint32_t key, uint32_t st) {
(void)d; (void)k; (void)s; (void)t;
@@ -290,19 +447,9 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
wl_display_roundtrip(dpy);
if (!comp || !shm || !wm) { fprintf(stderr, "lord-server --app: el compositor no ofrece lo necesario\n"); return 1; }
- surf = wl_compositor_create_surface(comp);
- xsurf = xdg_wm_base_get_xdg_surface(wm, surf);
- xdg_surface_add_listener(xsurf, &xs_listener, NULL);
- top = xdg_surface_get_toplevel(xsurf);
- xdg_toplevel_add_listener(top, &top_listener, NULL);
- xdg_toplevel_set_app_id(top, id); /* el Dock lo reconoce por su id */
- xdg_toplevel_set_title(top, id);
- if (decman) { /* que el tema dibuje el marco (como Qt) */
- struct zxdg_toplevel_decoration_v1 *deco = zxdg_decoration_manager_v1_get_toplevel_decoration(decman, top);
- zxdg_toplevel_decoration_v1_set_mode(deco, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
- }
- wl_surface_commit(surf);
- wl_display_roundtrip(dpy); /* primer configure */
+ app_id_str = id;
+ if (!win_create(0, id, 640, 480)) return 1; /* the main window (key 0) */
+ wl_display_roundtrip(dpy); /* first configure */
/* Caja de arena: después de conectar Wayland y abrir el broker, antes de cargar la app. */
js_broker_set_pkgdir(dir); /* la carpeta del paquete, antes de la caja de arena */
@@ -327,7 +474,13 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
double delay = -1;
for (int i = 0; i < 64; i++) { delay = js_tick(now_ms()); if (delay != 0) break; }
if (js_wants_frame()) { js_frame(now_ms()); }
- if (configured && (need_render || ui.dirty) && !frame_pending) render();
+ /* one node tree for all windows: any change repaints every window (cheap: apps are small) */
+ if (ui.dirty) { for (int i = 0; i < MAX_WINS; i++) if (wins[i].used) wins[i].need_render = 1; ui.dirty = 0; }
+ /* a window waiting for its frame callback or a free buffer renders when those arrive */
+ for (int i = 0; i < MAX_WINS; i++) {
+ AppWin *w = &wins[i];
+ if (w->used && w->configured && w->need_render && !w->frame_pending) render(w);
+ }
wl_display_flush(dpy);
struct pollfd pfd[2];
int n = 0;
@@ -335,12 +488,12 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
int bfd = js_broker_fd();
if (bfd >= 0) { pfd[n].fd = bfd; pfd[n].events = POLLIN; n++; }
int wait = delay < 0 ? 100 : (int)ceil(delay);
- if ((need_render || ui.dirty) && !frame_pending && configured) wait = 0;
+ if (js_broker_pending()) wait = 0; /* events that arrived during an RPC */
if (wl_display_prepare_read(dpy) != 0) { wl_display_dispatch_pending(dpy); continue; }
if (poll(pfd, (nfds_t)n, wait) < 0 && errno != EINTR) { wl_display_cancel_read(dpy); break; }
if (pfd[0].revents & POLLIN) wl_display_read_events(dpy); else wl_display_cancel_read(dpy);
wl_display_dispatch_pending(dpy);
- if (n > 1 && (pfd[1].revents & POLLIN)) js_broker_poll();
+ if ((n > 1 && (pfd[1].revents & POLLIN)) || js_broker_pending()) js_broker_poll();
if (pfd[0].revents & (POLLHUP | POLLERR)) break;
}
js_shutdown();
diff --git a/server/src/app/appspawn.c b/server/src/app/appspawn.c
index f3e6b44..faa47d2 100644
--- a/server/src/app/appspawn.c
+++ b/server/src/app/appspawn.c
@@ -27,6 +27,8 @@ int app_spawn(const char *id) {
char dir[PATH_MAX];
struct stat st;
if (!root || (size_t)snprintf(dir, sizeof dir, "%s/%s", root, id) >= sizeof dir || stat(dir, &st) || !S_ISDIR(st.st_mode)) return -1;
+ /* one process per app: if it is already running, it opens another window instead */
+ if (!brokersrv_new_window(id)) { fprintf(stderr, "lord-server: app '%s' already running: new window\n", id); return 0; }
char self[PATH_MAX];
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
@@ -44,6 +46,9 @@ int app_spawn(const char *id) {
if (fork() != 0) _exit(0); /* nieto huérfano, como el lanzador de apps Linux */
signal(SIGTERM, SIG_DFL);
signal(SIGHUP, SIG_DFL);
+ sigset_t none; /* lord-server blocks SIGINT/SIGTERM (signalfd): not the app */
+ sigemptyset(&none);
+ sigprocmask(SIG_SETMASK, &none, NULL);
char fdstr[16];
snprintf(fdstr, sizeof fdstr, "%d", sv[1]);
setenv(BROKER_FD_ENV, fdstr, 1);
diff --git a/server/src/apps.c b/server/src/apps.c
index 539ff26..6c70ba7 100644
--- a/server/src/apps.c
+++ b/server/src/apps.c
@@ -14,6 +14,7 @@
* inventar un comando.
* La salida de las apps va a ~/.cache/lordos/apps.log (se recorta al pasar 1 MB). */
#include "apps.h"
+#include "hw/defaults.h"
#include "fsops.h"
#include "sec/cgroup.h"
@@ -400,6 +401,10 @@ int apps_launch_with(const char *id, const char *path) {
char real[PATH_MAX];
struct stat st;
if (!path || !realpath(path, real) || !fsops_allowed(real) || stat(real, &st) || !(S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))) return -1;
+ /* id "" = the default app for the file's type (Settings → Default Apps, ~/.config/mimeapps.list);
+ * -1 if that is one of LordOS's own apps (the theme opens those) or there is none */
+ char def[160];
+ if (id && !id[0]) { if (defaults_app_for(real, def, sizeof def)) return -1; id = def; }
return launch(id, real);
}
diff --git a/server/src/backup/backup.c b/server/src/backup/backup.c
index 5ac2915..4ea66ee 100644
--- a/server/src/backup/backup.c
+++ b/server/src/backup/backup.c
@@ -1,16 +1,16 @@
-/* backup.c — el programador y el hilo de las copias de seguridad (ver backup.h).
+/* backup.c — the backup scheduler and worker thread (see backup.h).
*
- * ~/.config/lordos/backup.json la configuración: destino, frecuencia, exclusiones, batería.
- * Solo la escribe backup_configure (lord.fs no puede: decide a dónde
- * van los datos; está en fsops_protected).
+ * ~/.config/lordos/backup.json the configuration: destination, schedule, exclusions, battery.
+ * Only backup_configure writes it (lord.fs cannot: it decides
+ * where the data goes; it is in fsops_protected).
*
- * El hilo duerme en pthread_cond_timedwait hasta la próxima copia (sin sondear). Mientras copia:
- * - nice 19 y prioridad de E/S «idle» (setpriority/ioprio_set sobre su propio tid), y
- * posix_fadvise DONTNEED en lo copiado: no le saca la caché de páginas al escritorio;
- * - con batería (y «pausar con batería»), se detiene y vuelve a mirar cada 60 s;
- * - la pausa del usuario espera en la misma condición (sin sondear).
- * La hora de la última copia buena es la de la instantánea más nueva del destino: no hay otro
- * archivo de estado. La primera copia programada espera 5 minutos después de iniciar la sesión. */
+ * The thread sleeps in pthread_cond_timedwait until the next backup (no polling). While copying:
+ * - nice 19 and "idle" I/O priority (setpriority/ioprio_set on its own tid), and
+ * posix_fadvise DONTNEED on what was copied: it does not evict the desktop's page cache;
+ * - on battery (with "pause on battery"), it stops and checks again every 60 s;
+ * - a user pause waits on the same condition variable (no polling).
+ * The time of the last good backup is the newest snapshot on the destination: there is no other
+ * state file. The first scheduled backup waits 5 minutes after the session starts. */
#include "backup.h"
#include "engine.h"
#include "crypt.h"
@@ -37,9 +37,9 @@
#include <time.h>
#include <unistd.h>
-#define START_DELAY 300 /* s después de iniciar la sesión */
-#define RETRY_FAIL 900 /* s para reintentar después de un error */
-#define RETRY_NODEST 300 /* s para volver a mirar si apareció el disco */
+#define START_DELAY 300 /* s after the session starts */
+#define RETRY_FAIL 900 /* s before retrying after an error */
+#define RETRY_NODEST 300 /* s before checking again whether the disk is back */
#define BATTERY_RECHECK 60
static const char *const default_excl[] = { ".cache", ".local/share/Trash", ".local/share/lordos/apps",
@@ -49,10 +49,10 @@ typedef enum { S_IDLE, S_RUNNING, S_PAUSED, S_NODEST, S_RESTORING, S_DELETING, S
static const char *const state_names[] = { "idle", "running", "paused", "nodest", "restoring", "deleting", "locked", "unlocking" };
typedef struct {
- char dest[PATH_MAX]; /* carpeta elegida (real) */
- int interval; /* segundos; 0 = a mano */
+ char dest[PATH_MAX]; /* chosen folder (real path) */
+ int interval; /* seconds; 0 = manual */
int battery_pause;
- int encrypt; /* destino nuevo cifrado (crypt.h) */
+ int encrypt; /* new destination is encrypted (crypt.h) */
int nexcl;
char excl[BK_MAX_EXCL][256];
} Config;
@@ -67,22 +67,22 @@ static int want_run, user_pause, on_batt_pause;
static volatile int cancel_flag;
static time_t started_at, next_due, last_ok, last_try;
static char last_error[256];
-static BkRun run; /* progreso de la copia en curso */
+static BkRun run; /* progress of the running backup */
static char cur_file[512];
static double last_emit;
-/* resultado de la última copia */
+/* result of the last backup */
static struct { uint64_t files, copied, linked, bytes, errors; double secs; int ok; time_t when; char id[BK_ID_LEN]; } last;
-/* restaurar / borrar pendientes */
+/* pending restore / delete */
static struct { int pending; char id[BK_ID_LEN], rel[PATH_MAX / 2], suffix[80], to[PATH_MAX]; int replace; } rjob;
static struct { int pending; char id[BK_ID_LEN]; } djob;
-/* cifrado: la clave vive solo en memoria (bloqueada con mlock), mientras dure la sesión */
+/* encryption: the key lives only in memory (mlock'd), for as long as the session lasts */
static uint8_t key[BKC_KEY];
static int have_key, dest_enc;
static struct { int pending, create; char pass[256]; } ujob;
static struct { int done, ok; char error[160]; } ures;
static struct { int done; int ok; uint64_t files, kept, replaced, skipped, errors; char error[256]; char id[BK_ID_LEN]; } rres;
-/* snprintf para rutas: si no entra, deja la cadena vacía y devuelve -1 */
+/* snprintf for paths: if it does not fit, leaves the string empty and returns -1 */
__attribute__((format(printf, 3, 4)))
static int pathf(char *out, size_t n, const char *fmt, ...) {
va_list ap;
@@ -95,9 +95,9 @@ static int pathf(char *out, size_t n, const char *fmt, ...) {
static double now_s(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (double)t.tv_sec + t.tv_nsec / 1e9; }
-static void emit(void) { if (efd >= 0) { uint64_t one = 1; if (write(efd, &one, sizeof one) < 0) { /* lleno: ya hay aviso */ } } }
+static void emit(void) { if (efd >= 0) { uint64_t one = 1; if (write(efd, &one, sizeof one) < 0) { /* full: a notification is already pending */ } } }
-/* ---- configuración ---- */
+/* ---- configuration ---- */
static int machine_dir(const Config *c, char *out, size_t n) {
if (!c->dest[0]) return -1;
@@ -109,9 +109,9 @@ static int valid_dest(const char *in, char *real, size_t n, char *err, size_t en
char r[PATH_MAX];
struct stat st;
if (!in[0]) { real[0] = 0; return 0; }
- if (in[0] != '/' || !realpath(in, r) || stat(r, &st) || !S_ISDIR(st.st_mode)) { snprintf(err, en, "el destino no existe"); return -1; }
- if (!fsops_allowed(r) || fsops_protected(r)) { snprintf(err, en, "el destino tiene que estar en la carpeta personal o en un disco del usuario"); return -1; }
- if (access(r, W_OK)) { snprintf(err, en, "no se puede escribir en el destino"); return -1; }
+ if (in[0] != '/' || !realpath(in, r) || stat(r, &st) || !S_ISDIR(st.st_mode)) { snprintf(err, en, "the destination does not exist"); return -1; }
+ if (!fsops_allowed(r) || fsops_protected(r)) { snprintf(err, en, "the destination must be in the home folder or on one of the user's disks"); return -1; }
+ if (access(r, W_OK)) { snprintf(err, en, "cannot write to the destination"); return -1; }
snprintf(real, n, "%s", r);
return 0;
}
@@ -122,14 +122,14 @@ static int parse_config(const char *text, size_t len, Config *c, char *err, size
memset(c, 0, sizeof *c);
c->interval = 3600;
c->battery_pause = 1;
- if (json_parse(text, len, &d, jerr, sizeof jerr)) { snprintf(err, en, "configuración inválida: %s", jerr); return -1; }
+ if (json_parse(text, len, &d, jerr, sizeof jerr)) { snprintf(err, en, "invalid configuration: %s", jerr); return -1; }
const JVal *o = d.root;
int r = 0;
- if (!o || o->type != J_OBJ) { snprintf(err, en, "configuración inválida"); r = -1; goto out; }
+ if (!o || o->type != J_OBJ) { snprintf(err, en, "invalid configuration"); r = -1; goto out; }
const char *dest = json_str(o, "dest");
if (dest && strict && (strlen(dest) >= PATH_MAX || valid_dest(dest, c->dest, sizeof c->dest, err, en))) { r = -1; goto out; }
if (dest && !strict) {
- if (dest[0] != '/' || strlen(dest) >= sizeof c->dest || !bk_rel_valid(dest + 1)) { snprintf(err, en, "destino inválido"); r = -1; goto out; }
+ if (dest[0] != '/' || strlen(dest) >= sizeof c->dest || !bk_rel_valid(dest + 1)) { snprintf(err, en, "invalid destination"); r = -1; goto out; }
snprintf(c->dest, sizeof c->dest, "%s", dest);
}
const char *iv = json_str(o, "interval");
@@ -138,14 +138,14 @@ static int parse_config(const char *text, size_t len, Config *c, char *err, size
else if (!strcmp(iv, "daily")) c->interval = 86400;
else if (!strcmp(iv, "weekly")) c->interval = 7 * 86400;
else if (!strcmp(iv, "manual")) c->interval = 0;
- else { snprintf(err, en, "frecuencia inválida"); r = -1; goto out; }
+ else { snprintf(err, en, "invalid schedule"); r = -1; goto out; }
}
c->battery_pause = json_bool(o, "pauseOnBattery", 1);
const JVal *ex = json_get(o, "exclude");
if (ex && ex->type == J_ARR) {
for (const JVal *e = ex->kid; e; e = e->next) {
- if (e->type != J_STR || !e->len || e->len > 255 || !bk_rel_valid(e->str)) { snprintf(err, en, "exclusión inválida"); r = -1; goto out; }
- if (c->nexcl >= BK_MAX_EXCL - 8) { snprintf(err, en, "demasiadas exclusiones"); r = -1; goto out; }
+ if (e->type != J_STR || !e->len || e->len > 255 || !bk_rel_valid(e->str)) { snprintf(err, en, "invalid exclusion"); r = -1; goto out; }
+ if (c->nexcl >= BK_MAX_EXCL - 8) { snprintf(err, en, "too many exclusions"); r = -1; goto out; }
snprintf(c->excl[c->nexcl++], sizeof c->excl[0], "%s", e->str);
}
}
@@ -184,7 +184,7 @@ static void load_config(void) {
if (n <= 0) return;
buf[n] = 0;
Config c;
- /* sin exigir que el destino esté (un disco desenchufado): se valida antes de cada copia */
+ /* the destination need not be present (an unplugged disk): it is validated before each backup */
if (!parse_config(buf, (size_t)n, &c, err, sizeof err, 0)) cfg = c;
else fprintf(stderr, "backup: %s: %s\n", cfg_path, err);
}
@@ -202,7 +202,7 @@ static int save_config(const Config *c) {
return 0;
}
-/* ---- batería ---- */
+/* ---- battery ---- */
static int read_small(const char *p, char *out, size_t n) {
int fd = open(p, O_RDONLY | O_CLOEXEC);
@@ -215,7 +215,7 @@ static int read_small(const char *p, char *out, size_t n) {
return 0;
}
-/* Con batería = alguna batería descargándose y ninguna fuente de corriente conectada. */
+/* On battery = some battery discharging and no power source connected. */
static int on_battery(void) {
DIR *d = opendir("/sys/class/power_supply");
if (!d) return 0;
@@ -238,7 +238,7 @@ static int on_battery(void) {
return discharging && !mains;
}
-/* ---- el hilo ---- */
+/* ---- the thread ---- */
static void wait_until(time_t when) {
struct timespec ts = { .tv_sec = when, .tv_nsec = 0 };
@@ -247,7 +247,7 @@ static void wait_until(time_t when) {
static double last_batt_check;
-/* Entre archivos: progreso, pausa del usuario y batería. Con el mutex suelto. */
+/* Between files: progress, user pause and battery. Called with the mutex released. */
static int checkpoint(BkRun *r) {
(void)r;
double t = now_s();
@@ -286,9 +286,9 @@ static int latest_id(const char *machine, char out[BK_ID_LEN]) {
}
static void do_snapshot(void) {
- /* con el mutex tomado */
+ /* with the mutex held */
Config c = cfg;
- char machine[PATH_MAX], copias[PATH_MAX];
+ char machine[PATH_MAX], backups_dir[PATH_MAX];
struct stat st;
char dreal[PATH_MAX];
if (machine_dir(&c, machine, sizeof machine) || stat(c.dest, &st) || !S_ISDIR(st.st_mode) || access(c.dest, W_OK) ||
@@ -297,7 +297,7 @@ static void do_snapshot(void) {
emit();
return;
}
- if (pathf(copias, sizeof copias, "%s/" BK_DIRNAME, c.dest)) { state = S_NODEST; emit(); return; }
+ if (pathf(backups_dir, sizeof backups_dir, "%s/" BK_DIRNAME, c.dest)) { state = S_NODEST; emit(); return; }
memset(&run, 0, sizeof run);
run.home = home;
run.machine = machine;
@@ -314,9 +314,9 @@ static void do_snapshot(void) {
emit();
pthread_mutex_unlock(&mu);
- mkdir(copias, 0700);
+ mkdir(backups_dir, 0700);
char skip[PATH_MAX];
- run.skip_real = realpath(copias, skip) ? skip : NULL;
+ run.skip_real = realpath(backups_dir, skip) ? skip : NULL;
double t0 = now_s();
int r = bk_snapshot(&run, time(NULL));
double secs = now_s() - t0;
@@ -332,8 +332,8 @@ static void do_snapshot(void) {
last.ok = 0;
snprintf(last_error, sizeof last_error, "%s", run.error[0] ? run.error : "error");
} else {
- last.ok = -1; /* cortada: se retoma la próxima vez */
- snprintf(last_error, sizeof last_error, "interrumpida");
+ last.ok = -1; /* interrupted: resumed next time */
+ snprintf(last_error, sizeof last_error, "interrupted");
}
last.files = run.files;
last.copied = run.copied;
@@ -343,8 +343,8 @@ static void do_snapshot(void) {
last.secs = secs;
last.when = time(NULL);
snprintf(last.id, sizeof last.id, "%s", r == 0 ? run.id : "");
- fprintf(stderr, "backup: %s en %.1f s: %llu archivos, %llu copiados (%llu MB), %llu enlazados, %llu errores%s%s\n",
- r == 0 ? "lista" : r > 0 ? "cortada" : "falló", secs, (unsigned long long)run.files, (unsigned long long)run.copied,
+ fprintf(stderr, "backup: %s in %.1f s: %llu files, %llu copied (%llu MB), %llu linked, %llu errors%s%s\n",
+ r == 0 ? "done" : r > 0 ? "interrupted" : "failed", secs, (unsigned long long)run.files, (unsigned long long)run.copied,
(unsigned long long)(run.copied_bytes >> 20), (unsigned long long)run.linked, (unsigned long long)run.errors,
r < 0 ? ": " : "", r < 0 ? last_error : "");
emit();
@@ -362,12 +362,12 @@ static void do_restore(void) {
int replace = rjob.replace;
memset(&rres, 0, sizeof rres);
snprintf(rres.id, sizeof rres.id, "%s", id);
- if (machine_dir(&c, machine, sizeof machine)) { rres.done = 1; snprintf(rres.error, sizeof rres.error, "sin destino"); emit(); return; }
+ if (machine_dir(&c, machine, sizeof machine)) { rres.done = 1; snprintf(rres.error, sizeof rres.error, "no-destination"); emit(); return; }
state = S_RESTORING;
cancel_flag = 0;
emit();
pthread_mutex_unlock(&mu);
- if (dest_enc && !have_key) { state = S_IDLE; rres.done = 1; snprintf(rres.error, sizeof rres.error, "las copias están cifradas: desbloquealas primero"); emit(); return; }
+ if (dest_enc && !have_key) { state = S_IDLE; rres.done = 1; snprintf(rres.error, sizeof rres.error, "locked"); emit(); return; }
BkRestore o = { .cancel = &cancel_flag, .key = dest_enc ? key : NULL };
int r = bk_restore(machine, id, rel, to, replace, suffix, &o);
pthread_mutex_lock(&mu);
@@ -379,8 +379,8 @@ static void do_restore(void) {
rres.replaced = o.replaced;
rres.skipped = o.skipped;
rres.errors = o.errors;
- snprintf(rres.error, sizeof rres.error, "%s", r > 0 ? "interrumpida" : o.error);
- fprintf(stderr, "backup: restaurado %s/%s: %llu archivos, %llu duplicados, %llu reemplazados, %llu errores\n", id, rel,
+ snprintf(rres.error, sizeof rres.error, "%s", r > 0 ? "interrupted" : o.error);
+ fprintf(stderr, "backup: restored %s/%s: %llu files, %llu kept alongside, %llu replaced, %llu errors\n", id, rel,
(unsigned long long)o.files, (unsigned long long)o.kept_both, (unsigned long long)o.replaced, (unsigned long long)o.errors);
emit();
}
@@ -400,7 +400,7 @@ static void do_delete(void) {
emit();
}
-/* Desbloquear (o crear) el cifrado: Argon2 tarda, así que va en el hilo, nunca en el compositor. */
+/* Unlock (or set up) encryption: Argon2 is slow, so it runs in this thread, never in the compositor. */
static void do_unlock(void) {
char machine[PATH_MAX], pass[256];
int create = ujob.create;
@@ -408,7 +408,7 @@ static void do_unlock(void) {
bkc_wipe(ujob.pass, sizeof ujob.pass);
ujob.pending = 0;
memset(&ures, 0, sizeof ures);
- if (machine_dir(&cfg, machine, sizeof machine)) { bkc_wipe(pass, sizeof pass); ures.done = 1; snprintf(ures.error, sizeof ures.error, "sin destino"); emit(); return; }
+ if (machine_dir(&cfg, machine, sizeof machine)) { bkc_wipe(pass, sizeof pass); ures.done = 1; snprintf(ures.error, sizeof ures.error, "no-destination"); emit(); return; }
State before = state;
state = S_UNLOCKING;
emit();
@@ -418,7 +418,7 @@ static void do_unlock(void) {
static char ids[4][BK_ID_LEN];
if (enc) r = bkc_unlock(machine, pass, k);
else if (!create) r = -2;
- else if (bk_list(machine, ids, 4) > 0) r = -3; /* ya hay copias sin cifrar acá */
+ else if (bk_list(machine, ids, 4) > 0) r = -3; /* unencrypted backups already exist here */
else {
char m2[PATH_MAX + 4];
snprintf(m2, sizeof m2, "%s", machine);
@@ -431,8 +431,8 @@ static void do_unlock(void) {
ures.done = 1;
ures.ok = r == 0;
if (r == 0) { memcpy(key, k, sizeof key); have_key = 1; dest_enc = 1; }
- else snprintf(ures.error, sizeof ures.error, "%s", r == -1 ? "frase incorrecta" : r == -2 ? "este destino no está cifrado" :
- r == -3 ? "ya hay copias sin cifrar en este destino: elegí otro" : "no se pudo crear el cifrado");
+ else snprintf(ures.error, sizeof ures.error, "%s", r == -1 ? "wrong-passphrase" : r == -2 ? "not-encrypted" :
+ r == -3 ? "plain-backups-exist" : "setup-failed"); /* codes: the UI translates them */
bkc_wipe(k, sizeof k);
state = before == S_UNLOCKING ? S_IDLE : before;
if (state == S_LOCKED) state = S_IDLE;
@@ -459,7 +459,7 @@ static void *thread_main(void *arg) {
time_t now = time(NULL);
char machine[PATH_MAX], lid[BK_ID_LEN];
if (!cfg.dest[0]) { next_due = 0; state = S_IDLE; want_run = 0; pthread_cond_wait(&cv, &mu); continue; }
- { /* ¿el destino está cifrado? (cifrado.json en la carpeta del equipo) */
+ { /* is the destination encrypted? (encryption.json in the machine folder) */
uint8_t salt[BKC_SALT], chk[16];
dest_enc = !machine_dir(&cfg, machine, sizeof machine) && !bkc_info_read(machine, salt, chk);
}
@@ -474,7 +474,7 @@ static void *thread_main(void *arg) {
}
next_due = due;
if (due && due <= now && (dest_enc || cfg.encrypt) && !have_key) {
- /* cifrado y sin la frase: se espera a que la escriba el usuario (no se copia sin cifrar) */
+ /* encrypted and no passphrase: wait for the user to enter it (never copy unencrypted) */
state = S_LOCKED;
emit();
pthread_cond_wait(&cv, &mu);
@@ -484,7 +484,7 @@ static void *thread_main(void *arg) {
want_run = 0;
last_try = now;
if (cfg.battery_pause && on_battery() && !user_pause) {
- /* con batería: no se empieza; se vuelve a mirar en un minuto */
+ /* on battery: do not start; check again in a minute */
on_batt_pause = 1;
state = S_PAUSED;
emit();
@@ -518,9 +518,9 @@ int backup_start(const char *h, const char *u) {
if (pathf(cfg_path, sizeof cfg_path, "%s/.config/lordos/backup.json", home)) return -1;
pthread_condattr_t ca;
pthread_condattr_init(&ca);
- pthread_cond_init(&cv, &ca); /* CLOCK_REALTIME: las copias van por la hora de la pared */
+ pthread_cond_init(&cv, &ca); /* CLOCK_REALTIME: backups follow wall-clock time */
efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
- mlock(key, sizeof key); /* la clave no va a la swap */
+ mlock(key, sizeof key); /* the key never goes to swap */
load_config();
started_at = time(NULL);
pthread_t t;
@@ -542,7 +542,7 @@ void backup_dispatch(void (*fn)(const char *json)) {
if (j) { fn(j); free(j); }
}
-/* ---- API (hilo principal) ---- */
+/* ---- API (main thread) ---- */
char *backup_status_json(void) {
if (!started) return NULL;
@@ -590,18 +590,18 @@ char *backup_config_json(void) {
}
int backup_configure(const char *json, char *err, size_t n) {
- if (!started) { snprintf(err, n, "sin copias de seguridad"); return -1; }
- if (strlen(json) > 60000) { snprintf(err, n, "configuración demasiado grande"); return -1; }
+ if (!started) { snprintf(err, n, "backups are not running"); return -1; }
+ if (strlen(json) > 60000) { snprintf(err, n, "configuration too large"); return -1; }
Config c;
if (parse_config(json, strlen(json), &c, err, n, 1)) return -1;
- if (save_config(&c)) { snprintf(err, n, "no se pudo guardar la configuración"); return -1; }
+ if (save_config(&c)) { snprintf(err, n, "could not save the configuration"); return -1; }
pthread_mutex_lock(&mu);
int changed_dest = strcmp(c.dest, cfg.dest) != 0;
cfg = c;
if (changed_dest) {
last_ok = 0; last.ok = 1; last_try = 0;
if (state == S_NODEST || state == S_LOCKED) state = S_IDLE;
- bkc_wipe(key, sizeof key); /* la clave era de otro destino */
+ bkc_wipe(key, sizeof key); /* the key belonged to another destination */
have_key = 0;
dest_enc = 0;
}
@@ -612,11 +612,11 @@ int backup_configure(const char *json, char *err, size_t n) {
}
int backup_run_now(char *err, size_t n) {
- if (!started) { snprintf(err, n, "sin copias de seguridad"); return -1; }
+ if (!started) { snprintf(err, n, "backups are not running"); return -1; }
pthread_mutex_lock(&mu);
int r = 0;
- if (!cfg.dest[0]) { snprintf(err, n, "elegí un destino primero"); r = -1; }
- else if (state == S_RUNNING || state == S_RESTORING) { snprintf(err, n, "ya hay una copia en curso"); r = -1; }
+ if (!cfg.dest[0]) { snprintf(err, n, "choose a destination first"); r = -1; }
+ else if (state == S_RUNNING || state == S_RESTORING) { snprintf(err, n, "a backup is already running"); r = -1; }
else { want_run = 1; user_pause = 0; if (state == S_NODEST) state = S_IDLE; last_try = 0; pthread_cond_broadcast(&cv); }
pthread_mutex_unlock(&mu);
return r;
@@ -682,13 +682,13 @@ static int ent_cmp(const void *a, const void *b) {
char *backup_ls_json(const char *id, const char *rel, char *err, size_t en) {
char snap[PATH_MAX], dir[PATH_MAX], real[PATH_MAX];
- if (!bk_rel_valid(rel)) { snprintf(err, en, "ruta inválida"); return NULL; }
- if (backup_snapshot_path(id, snap, sizeof snap)) { snprintf(err, en, "no existe la copia"); return NULL; }
- if (pathf(dir, sizeof dir, "%s%s%s", snap, rel[0] ? "/" : "", rel)) { snprintf(err, en, "ruta inválida"); return NULL; }
+ if (!bk_rel_valid(rel)) { snprintf(err, en, "invalid path"); return NULL; }
+ if (backup_snapshot_path(id, snap, sizeof snap)) { snprintf(err, en, "no such backup"); return NULL; }
+ if (pathf(dir, sizeof dir, "%s%s%s", snap, rel[0] ? "/" : "", rel)) { snprintf(err, en, "invalid path"); return NULL; }
size_t sl = strlen(snap);
- if (!realpath(dir, real) || strncmp(real, snap, sl) || (real[sl] && real[sl] != '/')) { snprintf(err, en, "ruta inválida"); return NULL; }
+ if (!realpath(dir, real) || strncmp(real, snap, sl) || (real[sl] && real[sl] != '/')) { snprintf(err, en, "invalid path"); return NULL; }
DIR *d = opendir(real);
- if (!d) { snprintf(err, en, "no se puede leer"); return NULL; }
+ if (!d) { snprintf(err, en, "cannot read"); return NULL; }
pthread_mutex_lock(&mu);
int enc = dest_enc;
pthread_mutex_unlock(&mu);
@@ -730,17 +730,17 @@ char *backup_ls_json(const char *id, const char *rel, char *err, size_t en) {
}
int backup_restore(const char *id, const char *rel, int replace, const char *suffix, const char *to, char *err, size_t n) {
- if (!started) { snprintf(err, n, "sin copias de seguridad"); return -1; }
- if (!bk_id_valid(id) || !bk_rel_valid(rel) || strlen(rel) >= sizeof rjob.rel) { snprintf(err, n, "ruta inválida"); return -1; }
+ if (!started) { snprintf(err, n, "backups are not running"); return -1; }
+ if (!bk_id_valid(id) || !bk_rel_valid(rel) || strlen(rel) >= sizeof rjob.rel) { snprintf(err, n, "invalid path"); return -1; }
size_t sl = strlen(suffix);
- if (!sl || sl >= sizeof rjob.suffix || strchr(suffix, '/')) { snprintf(err, n, "sufijo inválido"); return -1; }
+ if (!sl || sl >= sizeof rjob.suffix || strchr(suffix, '/')) { snprintf(err, n, "invalid suffix"); return -1; }
char tr[PATH_MAX] = "";
if (to && to[0]) {
- if (!realpath(to, tr) || !fsops_allowed(tr) || fsops_protected(tr)) { snprintf(err, n, "destino no permitido"); return -1; }
+ if (!realpath(to, tr) || !fsops_allowed(tr) || fsops_protected(tr)) { snprintf(err, n, "destination not allowed"); return -1; }
}
pthread_mutex_lock(&mu);
int r = 0;
- if (state == S_RUNNING || state == S_RESTORING || state == S_DELETING || rjob.pending) { snprintf(err, n, "hay otra tarea en curso"); r = -1; }
+ if (state == S_RUNNING || state == S_RESTORING || state == S_DELETING || rjob.pending) { snprintf(err, n, "another task is running"); r = -1; }
else {
snprintf(rjob.id, sizeof rjob.id, "%s", id);
snprintf(rjob.rel, sizeof rjob.rel, "%s", rel);
@@ -756,24 +756,24 @@ int backup_restore(const char *id, const char *rel, int replace, const char *suf
}
int backup_delete(const char *id, char *err, size_t n) {
- if (!started) { snprintf(err, n, "sin copias de seguridad"); return -1; }
- if (!bk_id_valid(id)) { snprintf(err, n, "copia inválida"); return -1; }
+ if (!started) { snprintf(err, n, "backups are not running"); return -1; }
+ if (!bk_id_valid(id)) { snprintf(err, n, "invalid backup"); return -1; }
pthread_mutex_lock(&mu);
int r = 0;
- if (state != S_IDLE && state != S_NODEST) { snprintf(err, n, "hay otra tarea en curso"); r = -1; }
+ if (state != S_IDLE && state != S_NODEST) { snprintf(err, n, "another task is running"); r = -1; }
else { snprintf(djob.id, sizeof djob.id, "%s", id); djob.pending = 1; pthread_cond_broadcast(&cv); }
pthread_mutex_unlock(&mu);
return r;
}
int backup_unlock(const char *pass, int create, char *err, size_t n) {
- if (!started) { snprintf(err, n, "sin copias de seguridad"); return -1; }
+ if (!started) { snprintf(err, n, "backups are not running"); return -1; }
size_t len = strlen(pass);
- if (len < (create ? 8u : 1u) || len >= sizeof ujob.pass) { snprintf(err, n, create ? "la frase tiene que tener al menos 8 caracteres" : "frase inválida"); return -1; }
+ if (len < (create ? 8u : 1u) || len >= sizeof ujob.pass) { snprintf(err, n, create ? "the passphrase must have at least 8 characters" : "invalid passphrase"); return -1; }
pthread_mutex_lock(&mu);
int r = 0;
- if (!cfg.dest[0]) { snprintf(err, n, "elegí un destino primero"); r = -1; }
- else if (state == S_RUNNING || state == S_RESTORING || state == S_UNLOCKING || ujob.pending) { snprintf(err, n, "hay otra tarea en curso"); r = -1; }
+ if (!cfg.dest[0]) { snprintf(err, n, "choose a destination first"); r = -1; }
+ else if (state == S_RUNNING || state == S_RESTORING || state == S_UNLOCKING || ujob.pending) { snprintf(err, n, "another task is running"); r = -1; }
else {
snprintf(ujob.pass, sizeof ujob.pass, "%s", pass);
ujob.create = create != 0;
diff --git a/server/src/backup/backup.h b/server/src/backup/backup.h
index da0ecd2..9e51a43 100644
--- a/server/src/backup/backup.h
+++ b/server/src/backup/backup.h
@@ -1,18 +1,18 @@
-/* backup.h — Copias de seguridad de la sesión (ver backup.c, engine.h y docs/SISTEMA.md).
+/* backup.h — the session's backups (see backup.c, engine.h and docs/SYSTEM.md).
*
- * Un hilo de lord-server, como el usuario y con la prioridad más baja (nice 19, E/S «idle»),
- * hace las instantáneas programadas y las restauraciones. Avisa a JS por un eventfd que el bucle
- * principal mira (backup_fd → backup_dispatch → __lordBackup(estado)). */
+ * A lord-server thread, running as the user at the lowest priority (nice 19, "idle" I/O), takes
+ * the scheduled snapshots and does restores. It notifies JS through an eventfd watched by the main
+ * loop (backup_fd → backup_dispatch → __lordBackup(status)). */
#ifndef LORD_BACKUP_H
#define LORD_BACKUP_H
#include <stddef.h>
-int backup_start(const char *home, const char *user); /* después de soltar root; una vez */
-int backup_fd(void); /* -1 si no corre */
-void backup_dispatch(void (*fn)(const char *json)); /* hay novedades: fn(estado JSON) */
+int backup_start(const char *home, const char *user); /* after dropping root; once */
+int backup_fd(void); /* -1 if not running */
+void backup_dispatch(void (*fn)(const char *json)); /* something changed: fn(status JSON) */
-/* Todo devuelve texto JSON en memoria nueva (free) o NULL; err recibe el motivo. */
+/* Everything returns JSON text in new memory (free it) or NULL; err receives the reason. */
char *backup_status_json(void);
char *backup_config_json(void);
int backup_configure(const char *json, char *err, size_t n);
@@ -23,11 +23,12 @@ char *backup_list_json(void);
char *backup_ls_json(const char *id, const char *rel, char *err, size_t n);
int backup_restore(const char *id, const char *rel, int replace, const char *suffix, const char *to, char *err, size_t n);
int backup_delete(const char *id, char *err, size_t n);
-/* Cifrado: desbloquear (o, con create, crear en un destino sin copias) con la frase; el resultado
- * llega en el estado (unlock). La clave queda solo en memoria. lock() la borra. */
+/* Encryption: unlock (or, with create, set up on a destination without backups) with the
+ * passphrase; the result arrives in the status (unlock). The key stays only in memory; lock()
+ * wipes it. */
int backup_unlock(const char *pass, int create, char *err, size_t n);
void backup_lock(void);
-/* Ruta real de una instantánea (para abrirla en Archivos), o -1. */
+/* Real path of a snapshot (to open it in Files), or -1. */
int backup_snapshot_path(const char *id, char *out, size_t n);
#endif
diff --git a/server/src/backup/crypt.c b/server/src/backup/crypt.c
index cea5160..b46b39a 100644
--- a/server/src/backup/crypt.c
+++ b/server/src/backup/crypt.c
@@ -1,4 +1,4 @@
-/* crypt.c — cifrado de las Copias de seguridad con Monocypher (ver crypt.h). */
+/* crypt.c — backup encryption with Monocypher (see crypt.h). */
#include "crypt.h"
#include "monocypher.h"
@@ -27,7 +27,7 @@ int bkc_plain_size(uint64_t enc, uint64_t *plain) {
uint64_t body = enc - BKC_HDR;
uint64_t full = body / (BKC_CHUNK + BKC_MAC), rest = body % (BKC_CHUNK + BKC_MAC);
uint64_t p;
- if (rest == 0) p = full * BKC_CHUNK; /* el último trozo está lleno */
+ if (rest == 0) p = full * BKC_CHUNK; /* the last chunk is full */
else if (rest >= BKC_MAC) p = full * BKC_CHUNK + (rest - BKC_MAC);
else return -1;
if (bkc_enc_size(p) != enc) return -1;
@@ -87,7 +87,7 @@ int bkc_encrypt_fd(int in, int out, const uint8_t key[BKC_KEY], int (*tick)(void
if (r) return r;
uint8_t *a = malloc(BKC_CHUNK), *b = malloc(BKC_CHUNK), *c = malloc(BKC_CHUNK + BKC_MAC);
if (!a || !b || !c) { free(a); free(b); free(c); return -1; }
- /* se lee un trozo adelantado para saber cuál es el último */
+ /* read one chunk ahead to know which one is the last */
ssize_t n = read_full(in, a, BKC_CHUNK);
uint64_t i = 0;
while (n >= 0) {
@@ -121,7 +121,7 @@ int bkc_decrypt_fd(int in, int out, const uint8_t key[BKC_KEY], int (*tick)(void
ssize_t n = read_full(in, a, BKC_CHUNK + BKC_MAC);
uint64_t i = 0;
for (;;) {
- if (n < (ssize_t)BKC_MAC) { r = n < 0 ? -1 : -3; break; } /* cortado */
+ if (n < (ssize_t)BKC_MAC) { r = n < 0 ? -1 : -3; break; } /* truncated */
ssize_t next = (size_t)n == BKC_CHUNK + BKC_MAC ? read_full(in, b, BKC_CHUNK + BKC_MAC) : 0;
if (next < 0) { r = -1; break; }
int last = next == 0;
@@ -154,7 +154,7 @@ int bkc_derive(const char *pass, const uint8_t salt[BKC_SALT], uint8_t key[BKC_K
}
void bkc_check(const uint8_t key[BKC_KEY], uint8_t out[16]) {
- static const char label[] = "LordOS-Copias verificador v1";
+ static const char label[] = "LordOS-Backups key check v1";
crypto_blake2b_keyed(out, 16, key, BKC_KEY, (const uint8_t *)label, sizeof label - 1);
}
diff --git a/server/src/backup/crypt.h b/server/src/backup/crypt.h
index 3253798..15ae615 100644
--- a/server/src/backup/crypt.h
+++ b/server/src/backup/crypt.h
@@ -1,13 +1,13 @@
-/* crypt.h — cifrado opcional de las Copias de seguridad, con Monocypher (vendorizado en
- * third_party/monocypher; ver docs/SISTEMA.md, «Cifrado»).
+/* crypt.h — optional encryption of backups, with Monocypher (vendored in third_party/monocypher;
+ * see docs/SYSTEM.md, "Encryption").
*
- * Cada archivo de la copia es:
- * "LBK1" | nonce base (24 bytes) | trozos de 64 KiB cifrados con XChaCha20-Poly1305 (+16 de MAC)
- * El nonce de cada trozo es el base con su número mezclado en los últimos 8 bytes, y los datos
- * asociados son ese número y si es el último trozo: no se pueden reordenar, quitar ni cortar
- * trozos sin que falle la verificación. Un archivo vacío es un solo trozo final vacío.
- * La clave sale de la frase con Argon2id (64 MiB, 3 pasadas) y una sal por destino. Los nombres de
- * los archivos y los destinos de los enlaces simbólicos NO se cifran. */
+ * Each file in the backup is:
+ * "LBK1" | base nonce (24 bytes) | 64 KiB chunks encrypted with XChaCha20-Poly1305 (+16 MAC)
+ * Each chunk's nonce is the base nonce with the chunk number mixed into its last 8 bytes, and the
+ * associated data is that number plus whether it is the last chunk: chunks cannot be reordered,
+ * removed or truncated without failing verification. An empty file is a single empty final chunk.
+ * The key comes from the passphrase with Argon2id (64 MiB, 3 passes) and a per-destination salt.
+ * File names and symlink targets are NOT encrypted. */
#ifndef LORD_BACKUP_CRYPT_H
#define LORD_BACKUP_CRYPT_H
@@ -19,26 +19,26 @@
#define BKC_MAC 16u
#define BKC_KEY 32u
#define BKC_SALT 16u
-#define BKC_FILE "cifrado.json" /* en la carpeta del equipo: sal y verificador */
+#define BKC_FILE "encryption.json" /* in the machine folder: salt and key check */
uint64_t bkc_enc_size(uint64_t plain);
-int bkc_plain_size(uint64_t enc, uint64_t *plain); /* -1 si ese tamaño no puede ser de un cifrado */
+int bkc_plain_size(uint64_t enc, uint64_t *plain); /* -1 if no encrypted file can have that size */
-/* tick(ud, bytes) entre trozos: != 0 corta. Devuelven 0 bien, -1 E/S, -2 sin lugar, 1 cortado;
- * descifrar además -3 si un trozo no verifica (archivo alterado o clave incorrecta). */
+/* tick(ud, bytes) between chunks: != 0 stops. Return 0 ok, -1 I/O, -2 out of space, 1 interrupted;
+ * decrypt also returns -3 if a chunk fails verification (tampered file or wrong key). */
int bkc_encrypt_fd(int in, int out, const uint8_t key[BKC_KEY], int (*tick)(void *ud, size_t n), void *ud);
int bkc_decrypt_fd(int in, int out, const uint8_t key[BKC_KEY], int (*tick)(void *ud, size_t n), void *ud);
-int bkc_derive(const char *pass, const uint8_t salt[BKC_SALT], uint8_t key[BKC_KEY]); /* lento: ~0,3 s */
-void bkc_check(const uint8_t key[BKC_KEY], uint8_t out[16]); /* verificador de la clave (no la revela) */
+int bkc_derive(const char *pass, const uint8_t salt[BKC_SALT], uint8_t key[BKC_KEY]); /* slow: ~0.3 s */
+void bkc_check(const uint8_t key[BKC_KEY], uint8_t out[16]); /* key check value (does not reveal the key) */
int bkc_random(uint8_t *buf, size_t n);
-/* <machine>/cifrado.json: crear (sal nueva + verificador) o leer. 0 bien. */
+/* <machine>/encryption.json: write (new salt + key check) or read. 0 ok. */
int bkc_info_write(const char *machine, const uint8_t salt[BKC_SALT], const uint8_t check[16]);
-int bkc_info_read(const char *machine, uint8_t salt[BKC_SALT], uint8_t check[16]); /* -1: no está cifrado */
-/* Deriva y verifica la frase contra cifrado.json: 0 bien (key lleno), -1 frase incorrecta, -2 sin archivo. */
+int bkc_info_read(const char *machine, uint8_t salt[BKC_SALT], uint8_t check[16]); /* -1: not encrypted */
+/* Derives the key and checks it against encryption.json: 0 ok (key filled), -1 wrong passphrase, -2 no file. */
int bkc_unlock(const char *machine, const char *pass, uint8_t key[BKC_KEY]);
-/* Crea el cifrado de un destino nuevo: 0 bien. */
+/* Sets up encryption for a new destination: 0 ok. */
int bkc_setup(const char *machine, const char *pass, uint8_t key[BKC_KEY]);
void bkc_wipe(void *p, size_t n);
diff --git a/server/src/backup/engine.c b/server/src/backup/engine.c
index 3b4728a..3465c65 100644
--- a/server/src/backup/engine.c
+++ b/server/src/backup/engine.c
@@ -1,14 +1,14 @@
-/* engine.c — motor de las copias de seguridad: instantáneas con enlaces duros, retención y
- * restauración (ver engine.h y docs/SISTEMA.md, «Copias de seguridad»).
+/* engine.c — the backup engine: hard-linked snapshots, retention and restore (see engine.h and
+ * docs/SYSTEM.md, "Backups").
*
- * Reglas:
- * - nunca se sigue un enlace simbólico: el recorrido usa lstat y abre con O_NOFOLLOW; los
- * enlaces se guardan como enlaces (se copia el texto, no el destino);
- * - no se cruza a otro sistema de archivos (un disco montado adentro de la carpeta personal);
- * - fifos, sockets y dispositivos se saltean;
- * - un archivo se copia a "<nombre>.bkpart~" y se renombra al terminar, así un nombre final
- * siempre es un archivo completo (lo que permite retomar una copia cortada);
- * - se borra solo adentro de la carpeta del equipo y con nombres validados. */
+ * Rules:
+ * - a symbolic link is never followed: the walk uses lstat and opens with O_NOFOLLOW; links are
+ * stored as links (their text is copied, not their target);
+ * - never crosses into another filesystem (a disk mounted inside the home folder);
+ * - fifos, sockets and devices are skipped;
+ * - a file is copied to "<name>.bkpart~" and renamed when done, so a final name is always a
+ * complete file (which is what makes resuming an interrupted run possible);
+ * - deletion only happens inside the machine folder and with validated names. */
#include "engine.h"
#include "../fsops.h"
#include "crypt.h"
@@ -67,12 +67,12 @@ static int rm_tree(const char *p) {
struct stat st;
if (lstat(p, &st)) return errno == ENOENT ? 0 : -1;
if (!S_ISDIR(st.st_mode)) return unlink(p);
- /* las carpetas sin permiso de escritura (copiadas tal cual) no se podrían vaciar */
+ /* folders without write permission (copied as they were) could not be emptied */
return nftw(p, rm_cb, 32, FTW_DEPTH | FTW_PHYS | FTW_MOUNT);
}
static void rm_cb_chmod_dirs(const char *p) {
- /* antes de borrar: las carpetas guardadas con permisos 0500 no dejan borrar su contenido */
+ /* before deleting: folders stored with mode 0500 do not let their contents be removed */
DIR *d = opendir(p);
if (!d) { chmod(p, 0700); d = opendir(p); if (!d) return; }
chmod(p, 0700);
@@ -94,7 +94,7 @@ static int rm_tree_force(const char *p) {
return rm_tree(p);
}
-/* ---- nombres de las instantáneas ---- */
+/* ---- snapshot names ---- */
int bk_id_valid(const char *id) {
static const char pat[] = "dddd-dd-dd-dddddd";
@@ -158,7 +158,7 @@ int bk_rel_valid(const char *rel) {
return 1;
}
-/* ---- retención ---- */
+/* ---- retention ---- */
static long floordiv(long a, long b) { long q = a / b; return (a % b && (a < 0) != (b < 0)) ? q - 1 : q; }
@@ -175,7 +175,7 @@ void bk_retention(const time_t *t, int n, time_t now, long tz_off, int *keep) {
long day = floordiv(lt, 86400);
if (day != lastday) { keep[i] = 1; lastday = day; }
} else {
- long week = floordiv(lt - 4L * 86400, 7L * 86400); /* semanas de lunes (1970-01-05) */
+ long week = floordiv(lt - 4L * 86400, 7L * 86400); /* weeks start on Monday (1970-01-05) */
if (week != lastweek) { keep[i] = 1; lastweek = week; }
}
}
@@ -191,7 +191,7 @@ int bk_delete(const char *machine, const char *id) {
if (!bk_id_valid(id)) return -1;
char p[PATH_MAX];
if (pathf(p, sizeof p, "%s/%s", machine, id)) return -1;
- /* primero fuera de la lista (renombrar es atómico), después se borra con calma */
+ /* first out of the list (rename is atomic), then deleted at leisure */
char gone[PATH_MAX];
if (pathf(gone, sizeof gone, "%s/.deleting-%s", machine, id) || rename(p, gone)) return -1;
return rm_tree_force(gone);
@@ -207,7 +207,7 @@ int bk_prune(const char *machine, time_t now, uint64_t need) {
localtime_r(&now, &tm);
bk_retention(t, n, now, tm.tm_gmtoff, keep);
for (int i = 0; i < n; i++) if (!keep[i] && !bk_delete(machine, ids[i])) { gone++; ids[i][0] = 0; }
- /* restos de borrados cortados */
+ /* leftovers of interrupted deletions */
DIR *d = opendir(machine);
struct dirent *e;
while (d && (e = readdir(d))) {
@@ -216,7 +216,7 @@ int bk_prune(const char *machine, time_t now, uint64_t need) {
if (!pathf(p, sizeof p, "%s/%s", machine, e->d_name)) rm_tree_force(p);
}
if (d) closedir(d);
- /* falta lugar: las más viejas, nunca la última */
+ /* short on space: the oldest go, never the newest */
if (need) {
int left = 0;
for (int i = 0; i < n; i++) if (ids[i][0]) left++;
@@ -228,12 +228,12 @@ int bk_prune(const char *machine, time_t now, uint64_t need) {
return gone;
}
-/* ---- instantánea ---- */
+/* ---- snapshot ---- */
typedef struct {
BkRun *r;
- char src[PATH_MAX], dst[PATH_MAX]; /* raíces */
- char link1[PATH_MAX], link2[PATH_MAX]; /* fuentes de enlaces: copia a medias, anterior */
+ char src[PATH_MAX], dst[PATH_MAX]; /* roots */
+ char link1[PATH_MAX], link2[PATH_MAX]; /* link sources: interrupted run, previous snapshot */
dev_t home_dev;
dev_t skip_dev;
ino_t skip_ino;
@@ -245,7 +245,7 @@ static int excluded(const Walk *w, const char *rel) {
return 0;
}
-/* a: el original; b: el de la copia (cifrado: su tamaño es el del cifrado de a) */
+/* a: the original; b: the one in the snapshot (encrypted: its size is the encrypted size of a) */
static int same_file(const struct stat *a, const struct stat *b, const uint8_t *key) {
uint64_t want = key ? bkc_enc_size((uint64_t)a->st_size) : (uint64_t)a->st_size;
return S_ISREG(b->st_mode) && (uint64_t)b->st_size == want && a->st_mtim.tv_sec == b->st_mtim.tv_sec &&
@@ -259,7 +259,7 @@ static int check(Walk *w) {
return w->stop;
}
-/* Intenta enlazar dst a base/rel si es el mismo archivo. 1: enlazado. */
+/* Hard-links dst to base/rel if it is the same file. 1: linked. */
static int try_link(const char *base, const char *rel, const struct stat *st, const char *dst, const uint8_t *key) {
if (!base[0]) return 0;
char p[PATH_MAX];
@@ -267,7 +267,7 @@ static int try_link(const char *base, const char *rel, const struct stat *st, co
if (pathf(p, sizeof p, "%s/%s", base, rel) || lstat(p, &o) || !same_file(st, &o, key)) return 0;
if (link(p, dst) == 0) return 1;
if (errno == EEXIST) { unlink(dst); return link(p, dst) == 0; }
- return 0; /* EMLINK, EPERM (FAT/exFAT): se copia */
+ return 0; /* EMLINK, EPERM (FAT/exFAT): copy instead */
}
static int enc_tick(void *ud, size_t n) {
@@ -277,7 +277,7 @@ static int enc_tick(void *ud, size_t n) {
return check(w);
}
-/* -1 error del archivo, -2 sin lugar (fatal), 1 cortado, 0 bien */
+/* -1 file error, -2 out of space (fatal), 1 interrupted, 0 ok */
static int copy_data(Walk *w, int in, int out) {
char *buf = NULL;
int use_cfr = 1;
@@ -325,20 +325,20 @@ static int copy_file(Walk *w, const char *src, const char *dst, const struct sta
int r = w->r->key ? bkc_encrypt_fd(in, out, w->r->key, enc_tick, w) : copy_data(w, in, out);
struct stat b;
int changed = !fstat(in, &b) && (b.st_size != a.st_size || b.st_mtim.tv_sec != a.st_mtim.tv_sec || b.st_mtim.tv_nsec != a.st_mtim.tv_nsec);
- /* no ensuciar la caché de páginas del escritorio con la copia */
+ /* do not pollute the desktop's page cache with the copy */
posix_fadvise(in, 0, 0, POSIX_FADV_DONTNEED);
if (r == 0) {
fchmod(out, a.st_mode & 07777);
struct timespec ts[2] = { a.st_atim, a.st_mtim };
futimens(out, ts);
- /* sin fsync por archivo (sería muy lento con muchos archivos chicos): syncfs al final,
- * antes de renombrar la instantánea */
+ /* no fsync per file (too slow with many small files): syncfs at the end, before the
+ * snapshot is renamed */
posix_fadvise(out, 0, 0, POSIX_FADV_DONTNEED);
}
close(in);
if (close(out) && r == 0) r = -1;
if (r != 0) { unlink(tmp); return r; }
- if (changed && attempt < 2) { w->r->bytes = before; continue; } /* cambió mientras se copiaba */
+ if (changed && attempt < 2) { w->r->bytes = before; continue; } /* changed while being copied */
if (rename(tmp, dst)) { unlink(tmp); return -1; }
(void)st;
return 0;
@@ -360,7 +360,7 @@ static void entry(Walk *w, const char *rel, int depth) {
if (!w->counting && mkdir(dst, 0700) && errno != EEXIST) { w->r->errors++; return; }
walk(w, rel, depth + 1);
if (!w->counting) {
- chmod(dst, (st.st_mode & 07777) | 0700); /* el dueño siempre puede volver a entrar */
+ chmod(dst, (st.st_mode & 07777) | 0700); /* the owner can always get back in */
struct timespec ts[2] = { st.st_atim, st.st_mtim };
utimensat(AT_FDCWD, dst, ts, AT_SYMLINK_NOFOLLOW);
}
@@ -377,10 +377,10 @@ static void entry(Walk *w, const char *rel, int depth) {
}
int r = copy_file(w, src, dst, &st);
if (r == -2) {
- /* sin lugar: se borran instantáneas viejas (nunca la última) y se reintenta una vez */
+ /* out of space: delete old snapshots (never the newest) and retry once */
if (bk_prune(w->r->machine, time(NULL), (uint64_t)st.st_size + (w->r->min_free ? w->r->min_free : (512u << 20))) > 0)
r = copy_file(w, src, dst, &st);
- if (r == -2) { w->fatal = 1; snprintf(w->r->error, sizeof w->r->error, "sin lugar en el destino"); return; }
+ if (r == -2) { w->fatal = 1; snprintf(w->r->error, sizeof w->r->error, "no space left on the destination"); return; }
}
if (r == 0) w->r->copied++;
else if (r < 0) w->r->errors++;
@@ -394,12 +394,12 @@ static void entry(Walk *w, const char *rel, int depth) {
if (k < 0) { w->r->errors++; return; }
target[k] = 0;
unlink(dst);
- if (symlink(target, dst)) { w->r->errors++; return; } /* FAT no tiene enlaces */
+ if (symlink(target, dst)) { w->r->errors++; return; } /* FAT has no symlinks */
struct timespec ts[2] = { st.st_atim, st.st_mtim };
utimensat(AT_FDCWD, dst, ts, AT_SYMLINK_NOFOLLOW);
return;
}
- if (!w->counting) w->r->skipped++; /* fifos, sockets, dispositivos */
+ if (!w->counting) w->r->skipped++; /* fifos, sockets, devices */
}
static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
@@ -410,7 +410,7 @@ static void walk(Walk *w, const char *rel, int depth) {
int fd = open(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
DIR *d = fd >= 0 ? fdopendir(fd) : NULL;
if (!d) { if (fd >= 0) close(fd); w->r->errors++; return; }
- /* los nombres primero (la carpeta se cierra antes de bajar: no se acumulan fds) */
+ /* names first (the folder is closed before descending: fds do not pile up) */
char **names = NULL;
size_t n = 0, cap = 0;
struct dirent *e;
@@ -447,7 +447,7 @@ int bk_snapshot(BkRun *r, time_t now) {
w.r = r;
struct stat hs;
if (pathf(w.src, sizeof w.src, "%s", r->home) || lstat(w.src, &hs) || !S_ISDIR(hs.st_mode)) {
- snprintf(r->error, sizeof r->error, "no se puede leer la carpeta de origen");
+ snprintf(r->error, sizeof r->error, "cannot read the source folder");
return -1;
}
w.home_dev = hs.st_dev;
@@ -455,15 +455,15 @@ int bk_snapshot(BkRun *r, time_t now) {
struct stat ss;
if (!stat(r->skip_real, &ss)) { w.has_skip = 1; w.skip_dev = ss.st_dev; w.skip_ino = ss.st_ino; }
}
- if (mkdir_p(r->machine, 0700)) { snprintf(r->error, sizeof r->error, "no se pudo crear %s: %s", r->machine, strerror(errno)); return -1; }
+ if (mkdir_p(r->machine, 0700)) { snprintf(r->error, sizeof r->error, "could not create %s: %s", r->machine, strerror(errno)); return -1; }
static char ids[BK_MAX_SNAPS][BK_ID_LEN];
int n = bk_list(r->machine, ids, BK_MAX_SNAPS);
bk_id_make(now, r->id);
- while (n && strcmp(r->id, ids[n - 1]) <= 0) bk_id_make(++now, r->id); /* siempre posterior */
+ while (n && strcmp(r->id, ids[n - 1]) <= 0) bk_id_make(++now, r->id); /* always later than the previous one */
if (n) pathf(w.link2, sizeof w.link2, "%s/%s", r->machine, ids[n - 1]);
- /* copias cortadas: la más nueva es fuente de enlaces; las demás sobran */
+ /* interrupted runs: the newest is a link source; the others are dropped */
char old[PATH_MAX] = "", oldname[256] = "";
DIR *d = opendir(r->machine);
struct dirent *e;
@@ -479,12 +479,12 @@ int bk_snapshot(BkRun *r, time_t now) {
}
if (d) closedir(d);
if (oldname[0]) {
- /* se renombra para que no choque con la nueva y para saber que es la de antes */
+ /* renamed so it does not clash with the new one and is known to be the old one */
char p[PATH_MAX];
if (!pathf(p, sizeof p, "%s/%s", r->machine, oldname) && !pathf(old, sizeof old, "%s/.resume-%s", r->machine, oldname + 12))
if (rename(p, old)) old[0] = 0;
}
- { /* también una .resume- que haya quedado de un corte durante una reanudación */
+ { /* also a .resume- left by an interruption during a resume */
d = opendir(r->machine);
while (d && (e = readdir(d))) {
if (strncmp(e->d_name, ".resume-", 8)) continue;
@@ -496,23 +496,23 @@ int bk_snapshot(BkRun *r, time_t now) {
}
if (old[0]) snprintf(w.link1, sizeof w.link1, "%s", old);
- /* lugar mínimo antes de empezar */
+ /* minimum free space before starting */
uint64_t min_free = r->min_free ? r->min_free : (512u << 20);
if (free_bytes(r->machine) < min_free) bk_prune(r->machine, now, min_free);
- /* recuento (para el progreso) */
+ /* count (for progress) */
w.counting = 1;
walk(&w, "", 0);
w.counting = 0;
if (w.stop) return 1;
if (pathf(w.dst, sizeof w.dst, "%s/.inprogress-%s", r->machine, r->id) || mkdir(w.dst, 0700)) {
- snprintf(r->error, sizeof r->error, "no se pudo escribir en el destino: %s", strerror(errno));
+ snprintf(r->error, sizeof r->error, "cannot write to the destination: %s", strerror(errno));
return -1;
}
walk(&w, "", 0);
if (w.fatal) {
- /* queda a medias para retomar cuando haya lugar */
+ /* left half done, to resume when there is space */
return -1;
}
if (w.stop) return 1;
@@ -521,7 +521,7 @@ int bk_snapshot(BkRun *r, time_t now) {
if (dfd >= 0) { syncfs(dfd); close(dfd); }
char final[PATH_MAX];
if (pathf(final, sizeof final, "%s/%s", r->machine, r->id) || rename(w.dst, final)) {
- snprintf(r->error, sizeof r->error, "no se pudo cerrar la copia: %s", strerror(errno));
+ snprintf(r->error, sizeof r->error, "could not finish the snapshot: %s", strerror(errno));
return -1;
}
int mfd = open(r->machine, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
@@ -531,7 +531,7 @@ int bk_snapshot(BkRun *r, time_t now) {
return 0;
}
-/* ---- restaurar ---- */
+/* ---- restore ---- */
typedef struct {
BkRestore *o;
@@ -542,8 +542,8 @@ typedef struct {
static int rcancel(Rest *x) { return x->o->cancel && *x->o->cancel; }
-/* ¿Se puede escribir dst? Su carpeta (resuelta) tiene que estar en las raíces de lord.fs y el
- * nombre final no puede caer en una carpeta protegida. */
+/* May dst be written? Its (resolved) folder must be inside the lord.fs roots and the final name
+ * must not fall inside a protected folder. */
static int writable_target(const char *dst) {
char parent[PATH_MAX], real[PATH_MAX], full[PATH_MAX + 256];
if (pathf(parent, sizeof parent, "%s", dst)) return 0;
@@ -555,7 +555,7 @@ static int writable_target(const char *dst) {
return !fsops_protected(full) && !fsops_protected(real);
}
-/* "foto.jpg" + " (restaurado)" → "foto (restaurado).jpg", y si existe "foto (restaurado) 2.jpg" */
+/* "photo.jpg" + " (restored)" → "photo (restored).jpg", and if that exists "photo (restored) 2.jpg" */
static int alt_name(const char *dst, const char *suffix, char *out, size_t n) {
const char *slash = strrchr(dst, '/');
const char *name = slash ? slash + 1 : dst;
@@ -588,7 +588,7 @@ static int restore_file(Rest *x, const char *src, const char *dst, const struct
int r = 0;
if (x->o->key) {
r = bkc_decrypt_fd(in, out, x->o->key, rest_tick, x);
- if (r == -3) snprintf(x->o->error, sizeof x->o->error, "un archivo de la copia no verifica (alterado o clave incorrecta)");
+ if (r == -3) snprintf(x->o->error, sizeof x->o->error, "a backup file failed verification (tampered with or wrong key)");
if (r < 0) r = -1;
} else {
char *buf = malloc(1 << 20);
@@ -665,7 +665,7 @@ static void restore_entry(Rest *x, const char *src, const char *dst, int depth)
uint64_t plain = (uint64_t)st.st_size;
if (x->o->key && S_ISREG(st.st_mode) && bkc_plain_size((uint64_t)st.st_size, &plain)) plain = UINT64_MAX;
if (S_ISREG(st.st_mode) && S_ISREG(cur.st_mode) && (uint64_t)cur.st_size == plain && cur.st_mtim.tv_sec == st.st_mtim.tv_sec) {
- x->o->skipped++; /* igual: nada que hacer */
+ x->o->skipped++; /* identical: nothing to do */
return;
}
if (S_ISDIR(cur.st_mode) || !x->replace) {
@@ -682,7 +682,7 @@ static void restore_entry(Rest *x, const char *src, const char *dst, int depth)
if (k >= 0 && !pathf(tmp, sizeof tmp, "%s.bkpart~", target)) {
l[k] = 0;
unlink(tmp);
- r = symlink(l, tmp) || rename(tmp, target) ? -1 : 0; /* rename reemplaza el enlace, no lo sigue */
+ r = symlink(l, tmp) || rename(tmp, target) ? -1 : 0; /* rename replaces the link, it does not follow it */
if (r) unlink(tmp);
}
}
@@ -694,27 +694,27 @@ int bk_restore(const char *machine, const char *id, const char *rel, const char
int replace, const char *suffix, BkRestore *out) {
out->files = out->bytes = out->kept_both = out->replaced = out->skipped = out->errors = 0;
out->error[0] = 0;
- if (!bk_id_valid(id) || !bk_rel_valid(rel)) { snprintf(out->error, sizeof out->error, "ruta inválida"); return -1; }
+ if (!bk_id_valid(id) || !bk_rel_valid(rel)) { snprintf(out->error, sizeof out->error, "invalid path"); return -1; }
size_t sl = strlen(suffix);
- if (!sl || sl > 64 || strchr(suffix, '/')) { snprintf(out->error, sizeof out->error, "sufijo inválido"); return -1; }
- for (const char *p = suffix; *p; p++) if ((unsigned char)*p < 0x20) { snprintf(out->error, sizeof out->error, "sufijo inválido"); return -1; }
+ if (!sl || sl > 64 || strchr(suffix, '/')) { snprintf(out->error, sizeof out->error, "invalid suffix"); return -1; }
+ for (const char *p = suffix; *p; p++) if ((unsigned char)*p < 0x20) { snprintf(out->error, sizeof out->error, "invalid suffix"); return -1; }
Rest x = { .o = out, .suffix = suffix, .replace = replace };
char snap[PATH_MAX], src[PATH_MAX], breal[PATH_MAX], dst[PATH_MAX];
if (pathf(snap, sizeof snap, "%s/%s", machine, id) || !realpath(snap, x.snapreal)) {
- snprintf(out->error, sizeof out->error, "no existe la copia %s", id);
+ snprintf(out->error, sizeof out->error, "backup %s does not exist", id);
return -1;
}
if (pathf(src, sizeof src, "%s%s%s", x.snapreal, rel[0] ? "/" : "", rel)) return -1;
- /* nada de enlaces en el camino adentro de la copia: la carpeta resuelta sigue adentro */
+ /* no links along the path inside the snapshot: the resolved folder must stay inside */
if (rel[0]) {
char parent[PATH_MAX], preal[PATH_MAX];
snprintf(parent, sizeof parent, "%s", src);
*strrchr(parent, '/') = 0;
- if (!realpath(parent, preal) || !under(preal, x.snapreal)) { snprintf(out->error, sizeof out->error, "ruta inválida"); return -1; }
+ if (!realpath(parent, preal) || !under(preal, x.snapreal)) { snprintf(out->error, sizeof out->error, "invalid path"); return -1; }
}
- if (!realpath(base, breal) || !fsops_allowed(breal)) { snprintf(out->error, sizeof out->error, "destino no permitido"); return -1; }
+ if (!realpath(base, breal) || !fsops_allowed(breal)) { snprintf(out->error, sizeof out->error, "destination not allowed"); return -1; }
if (!rel[0]) {
- /* todo: el contenido de la copia, adentro de base */
+ /* everything: the snapshot's contents, inside base */
DIR *d = opendir(src);
struct dirent *e;
while (d && (e = readdir(d)) && !rcancel(&x)) {
@@ -725,7 +725,7 @@ int bk_restore(const char *machine, const char *id, const char *rel, const char
}
if (d) closedir(d);
} else {
- /* crear las carpetas que falten hasta el destino, sin seguir enlaces que no estén permitidos */
+ /* create the missing folders up to the target, never through links to forbidden places */
char cur[PATH_MAX];
snprintf(cur, sizeof cur, "%s", breal);
char tmp[PATH_MAX];
@@ -737,9 +737,9 @@ int bk_restore(const char *machine, const char *id, const char *rel, const char
char p[PATH_MAX];
if (pathf(p, sizeof p, "%s/%s", cur, tok)) return -1;
struct stat st;
- if (lstat(p, &st) && mkdir(p, 0700)) { snprintf(out->error, sizeof out->error, "no se pudo crear %.200s", p); return -1; }
+ if (lstat(p, &st) && mkdir(p, 0700)) { snprintf(out->error, sizeof out->error, "could not create %.200s", p); return -1; }
char pr[PATH_MAX];
- if (!realpath(p, pr) || !fsops_allowed(pr) || fsops_protected(pr)) { snprintf(out->error, sizeof out->error, "destino no permitido"); return -1; }
+ if (!realpath(p, pr) || !fsops_allowed(pr) || fsops_protected(pr)) { snprintf(out->error, sizeof out->error, "destination not allowed"); return -1; }
snprintf(cur, sizeof cur, "%s", pr);
tok = next;
}
diff --git a/server/src/backup/engine.h b/server/src/backup/engine.h
index e37ec58..9f030ed 100644
--- a/server/src/backup/engine.h
+++ b/server/src/backup/engine.h
@@ -1,79 +1,79 @@
-/* engine.h — motor de las copias de seguridad (Copias de seguridad, docs/SISTEMA.md).
+/* engine.h — the backup engine (Backups app, docs/SYSTEM.md).
*
- * Código propio, sin rsync: una instantánea es un árbol completo de la carpeta personal en
- * <destino>/LordOS-Copias/<equipo>-<usuario>/<AAAA-MM-DD-HHMMSS>/
- * Los archivos que no cambiaron (tamaño, fecha de modificación y permisos iguales a los de la
- * instantánea anterior) son enlaces duros a la anterior: cada instantánea se ve entera, pero solo
- * ocupa lo que cambió. Mientras se copia, el árbol está en .inprogress-<sello>; al terminar se
- * renombra (atómico). Una copia cortada se retoma: la siguiente usa ese árbol a medias como otra
- * fuente de enlaces y después lo borra.
+ * Our own code, no rsync: a snapshot is a complete tree of the home folder in
+ * <dest>/LordOS-Backups/<host>-<user>/<YYYY-MM-DD-HHMMSS>/
+ * Files that did not change (same size, modification time and mode as in the previous snapshot)
+ * are hard links to the previous one: every snapshot looks complete but only takes the space of
+ * what changed. While copying, the tree lives in .inprogress-<stamp>; it is renamed at the end
+ * (atomic). An interrupted run is resumed: the next one uses that partial tree as another link
+ * source and then deletes it.
*
- * Este archivo no sabe de hilos ni de JS (lo usa backup.c y lo prueba tests/backup_test.c). */
+ * This file knows nothing about threads or JS (backup.c uses it, tests/backup_test.c tests it). */
#ifndef LORD_BACKUP_ENGINE_H
#define LORD_BACKUP_ENGINE_H
#include <stdint.h>
#include <time.h>
-#define BK_DIRNAME "LordOS-Copias"
+#define BK_DIRNAME "LordOS-Backups"
#define BK_MAX_EXCL 64
#define BK_MAX_SNAPS 4096
#define BK_ID_LEN 18 /* "2026-10-17-235959" + 0 */
typedef struct BkRun BkRun;
struct BkRun {
- /* entrada */
- const char *home; /* carpeta de origen (ya resuelta con realpath) */
- const char *machine; /* <destino>/LordOS-Copias/<equipo>-<usuario> (se crea) */
- const char *excl[BK_MAX_EXCL]; /* prefijos relativos a home ("Videos/grandes", ".cache") */
+ /* input */
+ const char *home; /* source folder (already resolved with realpath) */
+ const char *machine; /* <dest>/LordOS-Backups/<host>-<user> (created if missing) */
+ const char *excl[BK_MAX_EXCL]; /* prefixes relative to home ("Videos/large", ".cache") */
int nexcl;
- const char *skip_real; /* ruta real que nunca se copia (el destino, si está en home) */
- volatile int *cancel; /* != 0: cortar lo antes posible (queda para retomar) */
- /* Se llama entre archivos y cada ~8 MB: puede bloquear (pausa) y devuelve != 0 para cortar. */
+ const char *skip_real; /* real path that is never copied (the destination, if inside home) */
+ volatile int *cancel; /* != 0: stop as soon as possible (left to resume) */
+ /* Called between files and every ~8 MB: may block (pause); returns != 0 to stop. */
int (*checkpoint)(BkRun *r);
- void (*progress)(BkRun *r, const char *rel); /* al pasar de archivo (rel a home) */
+ void (*progress)(BkRun *r, const char *rel); /* when moving to a new file (relative to home) */
void *ud;
- uint64_t min_free; /* bytes libres a dejar en el destino (0: 512 MiB) */
- const uint8_t *key; /* clave de 32 bytes si el destino está cifrado (crypt.h), o NULL */
- /* salida */
- uint64_t total_files, total_bytes; /* del recuento previo */
- uint64_t files, bytes; /* procesados */
+ uint64_t min_free; /* free bytes to keep on the destination (0: 512 MiB) */
+ const uint8_t *key; /* 32-byte key if the destination is encrypted (crypt.h), or NULL */
+ /* output */
+ uint64_t total_files, total_bytes; /* from the initial count */
+ uint64_t files, bytes; /* processed */
uint64_t copied, linked, copied_bytes, errors, skipped;
- char id[BK_ID_LEN]; /* instantánea creada */
+ char id[BK_ID_LEN]; /* snapshot created */
char error[256];
};
-/* 0: lista; 1: cortada (queda .inprogress para retomar); -1: error (r->error). */
+/* 0: done; 1: interrupted (.inprogress left to resume); -1: error (r->error). */
int bk_snapshot(BkRun *r, time_t now);
-/* Instantáneas completas del equipo, de la más vieja a la más nueva. Devuelve la cantidad. */
+/* Complete snapshots of this machine, oldest first. Returns the count. */
int bk_list(const char *machine, char (*ids)[BK_ID_LEN], int max);
int bk_id_valid(const char *id);
-time_t bk_id_time(const char *id); /* hora local del nombre, o -1 */
+time_t bk_id_time(const char *id); /* local time encoded in the name, or -1 */
void bk_id_make(time_t t, char out[BK_ID_LEN]);
-/* Retención (función pura): marca en keep[i] qué instantáneas quedan. t[] de la más vieja a la más
- * nueva. Todas las de las últimas 24 h; la última de cada día hasta 30 días; la última de cada
- * semana después. La más nueva siempre queda. tz_off: segundos a sumar para la hora local. */
+/* Retention (pure function): sets keep[i] for the snapshots that stay. t[] is oldest first.
+ * Everything from the last 24 h; the newest of each day up to 30 days; the newest of each week
+ * after that. The newest snapshot always stays. tz_off: seconds to add for local time. */
void bk_retention(const time_t *t, int n, time_t now, long tz_off, int *keep);
-/* Aplica la retención y, si falta lugar (need bytes), borra las más viejas (nunca la última). */
+/* Applies retention and, if space is short (need bytes), deletes the oldest (never the newest). */
int bk_prune(const char *machine, time_t now, uint64_t need);
int bk_delete(const char *machine, const char *id);
-/* Restaurar rel ("" = todo) de una instantánea a base/rel (base: normalmente home).
- * replace = 0: si el destino existe y es distinto, se guarda al lado como "nombre<suffix>"
- * (suffix lo da la interfaz, sin '/'); replace = 1: se reemplaza. Nunca escribe donde lord.fs no
- * deja (fsops_protected) ni fuera de sus raíces (fsops_allowed). */
+/* Restores rel ("" = everything) from a snapshot into base/rel (base: normally home).
+ * replace = 0: if the target exists and differs, the restored copy goes next to it as
+ * "name<suffix>" (suffix comes from the UI, no '/'); replace = 1: it is replaced. Never writes
+ * where lord.fs refuses to (fsops_protected) nor outside its roots (fsops_allowed). */
typedef struct {
uint64_t files, bytes, kept_both, replaced, skipped, errors;
volatile int *cancel;
- const uint8_t *key; /* para descifrar (destino cifrado), o NULL */
+ const uint8_t *key; /* to decrypt (encrypted destination), or NULL */
char error[256];
} BkRestore;
int bk_restore(const char *machine, const char *id, const char *rel, const char *base,
int replace, const char *suffix, BkRestore *out);
-/* rel seguro: relativo, sin "..", ".", "//", ni caracteres de control. "" vale. */
+/* Safe rel: relative, no "..", ".", "//" or control characters. "" is valid. */
int bk_rel_valid(const char *rel);
#endif
diff --git a/server/src/disk/disk.c b/server/src/disk/disk.c
index ed91096..94af91f 100644
--- a/server/src/disk/disk.c
+++ b/server/src/disk/disk.c
@@ -1,12 +1,12 @@
-/* disk.c — discos, particiones y montajes sin root (app Discos; ver disk.h y docs/SISTEMA.md).
+/* disk.c — disks, partitions and mounts without root (Disks app; see disk.h and docs/SYSTEM.md).
*
- * Fuentes:
- * /sys/block/<disco>/… tamaño, extraíble, solo lectura, rotacional, modelo
- * /run/udev/data/b<mayor>:<menor> lo que udev ya probó: sistema de archivos, etiqueta, UUID,
- * tabla de particiones, bus (sin abrir el dispositivo)
- * /proc/self/mountinfo dónde está montado cada uno
- * Nada de esto necesita root: el disco del sistema se reconoce acá mismo y el ayudante lo vuelve
- * a verificar con las mismas funciones antes de tocar nada. */
+ * Sources:
+ * /sys/block/<disk>/… size, removable, read-only, rotational, model
+ * /run/udev/data/b<major>:<minor> what udev already probed: file system, label, UUID,
+ * partition table, bus (without opening the device)
+ * /proc/self/mountinfo where each one is mounted
+ * None of this needs root: the system disk is recognized right here, and the helper checks it
+ * again with the same functions before touching anything. */
#include "disk.h"
#include <ctype.h>
@@ -41,7 +41,7 @@ static int read_small(const char *path, char *out, size_t n) {
close(fd);
if (r < 0) { out[0] = 0; return -1; }
out[r] = 0;
- while (r > 0 && (out[r - 1] == '\n' || out[r - 1] == ' ')) out[--r] = 0; /* el modelo viene con espacios al final */
+ while (r > 0 && (out[r - 1] == '\n' || out[r - 1] == ' ')) out[--r] = 0; /* the model comes with trailing spaces */
return 0;
}
@@ -81,7 +81,7 @@ uint64_t disk_size(const char *name) {
return s > 0 ? (uint64_t)s * 512 : 0;
}
-/* ---- base de udev ---- */
+/* ---- udev database ---- */
int disk_udev_prop(const char *name, const char *key, char *out, size_t n) {
out[0] = 0;
@@ -106,7 +106,7 @@ int disk_udev_prop(const char *name, const char *key, char *out, size_t n) {
return found;
}
-/* ID_FS_LABEL_ENC: los caracteres raros vienen como \xNN */
+/* ID_FS_LABEL_ENC: unusual characters come as \xNN */
static void unescape_udev(const char *in, char *out, size_t n) {
size_t o = 0;
for (size_t i = 0; in[i] && o + 1 < n; i++) {
@@ -141,7 +141,7 @@ static void unescape_octal(char *s) {
*o = 0;
}
-/* Llama fn por cada montaje; si fn devuelve != 0, corta y devuelve eso. */
+/* Calls fn for each mount; if fn returns != 0, stops and returns that. */
static int each_mount(int (*fn)(const Mnt *m, void *u), void *u) {
FILE *f = fopen("/proc/self/mountinfo", "re");
if (!f) return 0;
@@ -162,7 +162,7 @@ static int each_mount(int (*fn)(const Mnt *m, void *u), void *u) {
return ret;
}
-/* Número de dispositivo de un montaje: el de mountinfo, o (btrfs, 0:N) el de su origen /dev/… */
+/* Device number of a mount: the one in mountinfo, or (btrfs, 0:N) the one of its /dev/… source */
static int mount_dev(const Mnt *m, unsigned *ma, unsigned *mi) {
if (m->maj) { *ma = m->maj; *mi = m->min; return 0; }
struct stat st;
@@ -193,10 +193,10 @@ int disk_mounts(const char *name, char *out, size_t n) {
return q.count;
}
-/* ---- disco del sistema ---- */
+/* ---- system disk ---- */
-/* Agrega a set (nombres separados por espacio) los discos que hay debajo de name: si es una
- * partición, su disco; si es dm/md, los discos de sus esclavos (recursivo). */
+/* Adds to set (space-separated names) the disks under name: for a partition, its disk; for
+ * dm/md, the disks of its slaves (recursively). */
static void base_disks(const char *name, char *set, size_t n, int depth) {
if (depth > 8 || !disk_valid_name(name)) return;
char parent[32];
@@ -252,7 +252,7 @@ static void system_set(char *set, size_t n) {
SysQ q;
snprintf(q.set, sizeof q.set, " ");
each_mount(sys_cb, &q);
- /* swaps activas */
+ /* active swaps */
FILE *f = fopen("/proc/swaps", "re");
char line[512];
if (f && fgets(line, sizeof line, f)) {
@@ -321,7 +321,7 @@ static void bstr(Buf *b, const char *key, const char *s) {
bput(b, "\",");
}
-/* Datos de sistema de archivos y montaje de un dispositivo (disco o partición). */
+/* File system and mount fields of a device (disk or partition). */
static void fs_fields(Buf *b, const char *name) {
char v[512], label[256];
disk_udev_prop(name, "ID_FS_TYPE", v, sizeof v);
@@ -347,7 +347,7 @@ static void fs_fields(Buf *b, const char *name) {
static int skip_disk(const char *n) {
static const char *const pre[] = { "ram", "zram", "dm-", "md", "sr", "fd", "nbd", "mtdblock", "zd" };
for (size_t i = 0; i < sizeof pre / sizeof *pre; i++) if (!strncmp(n, pre[i], strlen(pre[i]))) return 1;
- if (!strncmp(n, "loop", 4)) { /* solo los loop con archivo detrás (pruebas, imágenes) */
+ if (!strncmp(n, "loop", 4)) { /* only loops backed by a file (tests, images) */
char p[PATH_MAX];
snprintf(p, sizeof p, "/sys/block/%s/loop/backing_file", n);
return access(p, F_OK) != 0;
@@ -415,7 +415,7 @@ char *disk_list_json(void) {
disk_is_removable(n) ? "true" : "false", !strcmp(ro, "1") ? "true" : "false", !strcmp(rot, "1") ? "true" : "false",
strstr(sys, key) ? "true" : "false");
fs_fields(&b, n);
- /* particiones */
+ /* partitions */
Part parts[128];
int np = 0;
char p[PATH_MAX];
@@ -467,11 +467,11 @@ char *disk_tools_json(void) {
return out;
}
-/* ---- avisos: mountinfo (POLLPRI) + udev (netlink, grupo 2) en un solo epoll ---- */
+/* ---- notifications: mountinfo (POLLPRI) + udev (netlink, group 2) in a single epoll ---- */
-/* Huella de mountinfo. El poll de /proc/self/mountinfo se «consume» al consultarlo: el poll del
- * bucle principal sobre el epoll ya lo gasta y epoll_wait después no lo informa. Por eso, en cada
- * aviso, se compara el contenido (unos pocos KB) con el de la vez anterior. */
+/* Fingerprint of mountinfo. Polling /proc/self/mountinfo "consumes" the event: the main loop's
+ * poll on the epoll already uses it up and epoll_wait then doesn't report it. So on every
+ * notification the content (a few KB) is compared with the previous one. */
static uint64_t mounts_hash(void) {
uint64_t h = 1469598103934665603ull;
int fd = open("/proc/self/mountinfo", O_RDONLY | O_CLOEXEC);
@@ -506,7 +506,7 @@ int disk_watch(int on) {
struct epoll_event ev = { .events = EPOLLPRI | EPOLLERR, .data.fd = mfd };
epoll_ctl(ep, EPOLL_CTL_ADD, mfd, &ev);
}
- /* avisos que manda udevd después de procesar el dispositivo (la base ya está al día) */
+ /* events udevd sends after processing the device (its database is already up to date) */
ufd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
if (ufd >= 0) {
struct sockaddr_nl sa = { .nl_family = AF_NETLINK, .nl_groups = 2 };
diff --git a/server/src/disk/disk.h b/server/src/disk/disk.h
index 5f70798..5bcef8a 100644
--- a/server/src/disk/disk.h
+++ b/server/src/disk/disk.h
@@ -1,10 +1,10 @@
-/* disk.h — discos y particiones para la app Discos (ver docs/SISTEMA.md, «Discos»).
+/* disk.h — disks and partitions for the Disks app (see docs/SYSTEM.md, "Disks").
*
- * disk.c lee sin root: /sys/block, la base de udev (/run/udev/data/b<mayor>:<menor>) y
- * /proc/self/mountinfo. Lo usan lord-server (lord.disks, js_disk.c) y el ayudante de
- * administración (disk_admin.c), que valida con estas mismas funciones del lado root.
- * smart.c son los analizadores (funciones puras) de SMART de ATA y del registro de salud de
- * NVMe; los lee el ayudante con SG_IO / NVME_IOCTL_ADMIN_CMD (acción disk-smart). */
+ * disk.c reads without root: /sys/block, the udev database (/run/udev/data/b<major>:<minor>) and
+ * /proc/self/mountinfo. It is used by lord-server (lord.disks, js_disk.c) and by the admin helper
+ * (disk_admin.c), which validates with these same functions on the root side.
+ * smart.c holds the parsers (pure functions) for ATA SMART and the NVMe health log; the helper
+ * reads them with SG_IO / NVME_IOCTL_ADMIN_CMD (action disk-smart). */
#ifndef LORD_DISK_H
#define LORD_DISK_H
@@ -14,59 +14,59 @@
#include "../admin.h"
-/* Nombre de un dispositivo de bloque como lo da el kernel: sda, sda1, nvme0n1p2, mmcblk0p1,
- * vdb, loop3 (letras minúsculas y dígitos, empieza con letra, hasta 31). */
+/* Block device name as the kernel gives it: sda, sda1, nvme0n1p2, mmcblk0p1, vdb, loop3
+ * (lowercase letters and digits, starts with a letter, up to 31). */
int disk_valid_name(const char *name);
-/* 1 si es una partición (existe /sys/class/block/<n>/partition); su disco en disk. */
+/* 1 if it is a partition (/sys/class/block/<n>/partition exists); its disk goes in disk. */
int disk_parent(const char *name, char *disk, size_t n);
-/* 1 si el disco (entero) aloja algo del sistema: /, /usr, /var, /home, /boot, /boot/efi, el medio
- * del live, una swap activa, o un dm/md que esté sobre él y aloje alguno de esos. */
+/* 1 if the (whole) disk holds something of the system: /, /usr, /var, /home, /boot, /boot/efi, the
+ * live medium, an active swap, or a dm/md on top of it that holds any of those. */
int disk_is_system(const char *disk);
-/* 1 si es extraíble: removable=1 en sysfs, o conectado por USB, o una tarjeta (mmc). */
+/* 1 if removable: removable=1 in sysfs, connected over USB, or a card (mmc). */
int disk_is_removable(const char *disk);
-/* Propiedad de la base de udev para ese dispositivo ("ID_FS_TYPE"…); "" si no está. */
+/* udev database property for that device ("ID_FS_TYPE"…); "" if missing. */
int disk_udev_prop(const char *name, const char *key, char *out, size_t n);
-/* Etiqueta del sistema de archivos tal cual (ID_FS_LABEL_ENC sin los \xNN); "" si no tiene. */
+/* File system label as is (ID_FS_LABEL_ENC with the \xNN decoded); "" if none. */
void disk_fs_label(const char *name, char *out, size_t n);
-/* Tamaño en bytes (/sys/class/block/<n>/size × 512). */
+/* Size in bytes (/sys/class/block/<n>/size × 512). */
uint64_t disk_size(const char *name);
-/* Puntos de montaje del dispositivo (separados por \n) desde mountinfo; devuelve cuántos. */
+/* Mount points of the device (separated by \n) from mountinfo; returns how many. */
int disk_mounts(const char *name, char *out, size_t n);
-/* Lista para JS: [{ name, model, vendor, serial, size, removable, transport, rotational, ro,
+/* List for JS: [{ name, model, vendor, serial, size, removable, transport, rotational, ro,
* system, table, fstype, label, uuid, mountpoint, used, avail, partitions: [{ name, number, size,
- * fstype, label, uuid, partlabel, mountpoint, used, avail, start }] }]. malloc; NULL si falla. */
+ * fstype, label, uuid, partlabel, mountpoint, used, avail, start }] }]. malloc'd; NULL on failure. */
char *disk_list_json(void);
-/* Programas para formatear y renombrar que hay en el equipo: {"fat32":1,"exfat":1,"ext4":1,"ntfs":0} */
+/* Format and rename programs present on this machine: {"fat32":1,"exfat":1,"ext4":1,"ntfs":0} */
char *disk_tools_json(void);
-/* Avisos de cambios para la app abierta: un fd (epoll de mountinfo y de los avisos de udev) para
- * el bucle principal. disk_watch(1) lo abre, disk_watch(0) lo cierra; -1 si no está abierto. */
+/* Change notifications while the app is open: one fd (epoll over mountinfo and udev events) for
+ * the main loop. disk_watch(1) opens it, disk_watch(0) closes it; -1 when not open. */
int disk_watch(int on);
int disk_watch_fd(void);
-/* Lee lo que llegó; 1 si cambió algo de discos o montajes (hay que avisar a JS). */
+/* Reads what arrived; 1 if disks or mounts changed (JS must be told). */
int disk_watch_dispatch(void);
-/* ---- SMART (smart.c, funciones puras: tests/smart_test.c) ---- */
+/* ---- SMART (smart.c, pure functions: tests/smart_test.c) ---- */
enum { SMART_UNKNOWN = 0, SMART_OK = 1, SMART_WARN = 2, SMART_FAIL = 3 };
enum { SMART_ATA = 1, SMART_NVME = 2 };
typedef struct {
uint8_t id, value, worst, thresh;
- uint16_t flags; /* bit 0: pre-falla */
+ uint16_t flags; /* bit 0: pre-fail */
uint64_t raw; /* 48 bits */
- int failing; /* valor <= umbral (umbral != 0) */
+ int failing; /* value <= threshold (threshold != 0) */
} SmartAttr;
typedef struct {
int kind; /* SMART_ATA / SMART_NVME */
int health; /* SMART_OK… */
- int checksum_ok; /* ATA: la suma de los 512 bytes da 0 */
- int status; /* ATA RETURN STATUS: 1 bien, 0 umbral superado, -1 no se sabe */
- int temp_c; /* -1 si no se sabe */
- int64_t power_on_hours, power_cycles; /* -1 si no se sabe */
- int64_t reallocated, pending, uncorrectable; /* ATA 5, 197, 198 (-1 si no están) */
+ int checksum_ok; /* ATA: the 512 bytes sum to 0 */
+ int status; /* ATA RETURN STATUS: 1 good, 0 threshold exceeded, -1 unknown */
+ int temp_c; /* -1 if unknown */
+ int64_t power_on_hours, power_cycles; /* -1 if unknown */
+ int64_t reallocated, pending, uncorrectable; /* ATA 5, 197, 198 (-1 if absent) */
int nattr;
SmartAttr attr[30];
/* NVMe */
@@ -74,16 +74,16 @@ typedef struct {
uint64_t data_read, data_written, media_errors, unsafe_shutdowns; /* data_*: bytes */
} SmartReport;
-/* data = SMART READ DATA (512 bytes); thresh = READ THRESHOLDS (512) o NULL; status = 1/0/-1. */
+/* data = SMART READ DATA (512 bytes); thresh = READ THRESHOLDS (512) or NULL; status = 1/0/-1. */
int smart_ata_parse(const uint8_t data[512], const uint8_t *thresh, int status, SmartReport *r);
-/* log = registro 02h de NVMe (SMART / Health Information, 512 bytes). */
+/* log = NVMe log page 02h (SMART / Health Information, 512 bytes). */
int smart_nvme_parse(const uint8_t log[512], SmartReport *r);
-/* Resumen en JSON (sin los atributos): {kind, health, temp, hours, cycles, ...}. */
+/* Summary as JSON (without the attributes): {kind, health, temp, hours, cycles, ...}. */
int smart_summary_json(const SmartReport *r, char *out, size_t n);
-/* Un atributo ATA en JSON: {id, value, worst, thresh, raw, prefail, failing}. */
+/* One ATA attribute as JSON: {id, value, worst, thresh, raw, prefail, failing}. */
int smart_attr_json(const SmartAttr *a, char *out, size_t n);
-/* ---- acciones del ayudante (disk_admin.c) ---- */
+/* ---- helper actions (disk_admin.c) ---- */
void disk_act_smart(const AdminReq *r, const char *arg, size_t len);
void disk_act_mount(const AdminReq *r, const char *arg, size_t len);
@@ -95,8 +95,8 @@ void disk_act_erase(const AdminReq *r, const char *arg, size_t len);
void disk_act_write_image(const AdminReq *r, const char *arg, size_t len);
void disk_act_cancel(const AdminReq *r, const char *arg, size_t len);
-/* Todas son A_ANYONE: cada una exige adentro administrador para los discos internos (los
- * extraíbles los puede usar cualquiera, como udisks) y rechaza el disco del sistema. */
+/* All are A_ANYONE: each one requires an administrator for internal disks (removable ones are
+ * open to any session user, like udisks) and refuses the system disk. */
#define DISK_ADMIN_ACTIONS \
{ "disk-smart", disk_act_smart, A_FORK | A_ANYONE }, \
{ "disk-mount", disk_act_mount, A_ANYONE }, \
diff --git a/server/src/disk/disk_admin.c b/server/src/disk/disk_admin.c
index f01226d..cdc00db 100644
--- a/server/src/disk/disk_admin.c
+++ b/server/src/disk/disk_admin.c
@@ -1,29 +1,29 @@
-/* disk_admin.c — las acciones «disk-*» del ayudante privilegiado (admin.c), app Discos.
+/* disk_admin.c — the "disk-*" actions of the privileged helper (admin.c), Disks app.
*
- * disk-smart <disco> salud: SMART de ATA (SG_IO, ATA PASS-THROUGH 16) o
- * el registro de salud de NVMe (NVME_IOCTL_ADMIN_CMD)
- * disk-mount <dispositivo> monta en /media/<usuario>/<etiqueta> (nosuid,nodev)
- * disk-unmount <dispositivo> desmonta lo que esté en /media o /run/media
- * disk-eject <disco> desmonta todo, vacía cachés y lo expulsa (USB: lo apaga)
- * disk-format <disp>\n<fs>\n<etiqueta> fat32 | exfat | ext4 | ntfs (si está mkfs.ntfs). Un disco
- * entero recibe una tabla MBR propia con una partición
- * disk-label <partición>\n<etiqueta> renombrar el volumen
- * disk-erase <disp>\nquick|zero borra las firmas (rápido) o escribe ceros en todo
- * disk-write-image <disco>\n<ruta> copia una imagen ISO/IMG al disco y la verifica (SHA-256)
- * disk-cancel <disco> corta un borrado con ceros o una copia de imagen
+ * disk-smart <disk> health: ATA SMART (SG_IO, ATA PASS-THROUGH 16) or the
+ * NVMe health log (NVME_IOCTL_ADMIN_CMD)
+ * disk-mount <device> mounts at /media/<user>/<label> (nosuid,nodev)
+ * disk-unmount <device> unmounts whatever is under /media or /run/media
+ * disk-eject <disk> unmounts everything, flushes caches and ejects it (USB: powers off)
+ * disk-format <dev>\n<fs>\n<label> fat32 | exfat | ext4 | ntfs (if mkfs.ntfs exists). A whole
+ * disk gets our own MBR table with one partition
+ * disk-label <partition>\n<label> rename the volume
+ * disk-erase <dev>\nquick|zero wipes the signatures (quick) or writes zeros everywhere
+ * disk-write-image <disk>\n<path> copies an ISO/IMG image to the disk and verifies it (SHA-256)
+ * disk-cancel <disk> stops a zero erase or an image copy
*
- * Reglas, todas del lado root (no se confía en la app):
- * - el nombre es un dispositivo de bloque real (sd*, vd*, hd*, xvd*, nvme*, mmcblk*, loop*), con
- * /dev/<nombre> de bloque y el mismo número que en sysfs;
- * - nunca el disco del sistema (disk_is_system: /, /usr, /var, /home, /boot, swap, live…), salvo
- * para leer su SMART;
- * - los discos internos solo los toca un administrador; los extraíbles (USB, tarjetas),
- * cualquier usuario de la sesión, como udisks;
- * - solo se desmonta lo montado en /media o /run/media; lo demás se rechaza;
- * - programas de ruta fija (mkfs.*, *label) con argumentos ya validados; montar, desmontar,
- * particionar, borrar y copiar la imagen se hacen con llamadas al sistema, sin programas;
- * - la imagen se abre con los permisos del usuario (setfsuid), solo de su carpeta o de sus
- * montajes, y nunca del mismo disco que se va a escribir. */
+ * Rules, all on the root side (the app is not trusted):
+ * - the name is a real block device (sd*, vd*, hd*, xvd*, nvme*, mmcblk*, loop*), with
+ * /dev/<name> a block device with the same number as in sysfs;
+ * - never the system disk (disk_is_system: /, /usr, /var, /home, /boot, swap, live…), except
+ * to read its SMART;
+ * - internal disks only for an administrator; removable ones (USB, cards) for any session user,
+ * like udisks;
+ * - only what is mounted under /media or /run/media is unmounted; anything else is refused;
+ * - fixed-path programs (mkfs.*, *label) with validated arguments; mount, unmount, partition,
+ * erase and the image copy are system calls, no programs;
+ * - the image is opened with the user's permissions (setfsuid), only from their home or their
+ * mounts, and never from the disk being written. */
#include "disk.h"
#include "../pkg/crypto.h"
@@ -54,10 +54,10 @@
#define MIB (1024u * 1024u)
typedef struct {
- char name[32]; /* lo pedido */
- char disk[32]; /* su disco */
+ char name[32]; /* what was asked for */
+ char disk[32]; /* its disk */
char dev[48]; /* /dev/<name> */
- int part; /* es una partición */
+ int part; /* is a partition */
int removable;
uint64_t size;
} Target;
@@ -85,8 +85,8 @@ static int known_kind(const char *n) {
return 0;
}
-/* want: 0 cualquiera, 1 solo disco entero, 2 solo partición. allow_system: solo para leer (SMART):
- * vale también para el disco del sistema y para cualquier usuario. */
+/* want: 0 any, 1 whole disk only, 2 partition only. allow_system: read-only use (SMART):
+ * also allowed on the system disk and for any user. */
static int target(const AdminReq *r, const char *name, int want, int allow_system, Target *t) {
memset(t, 0, sizeof *t);
if (!disk_valid_name(name) || !known_kind(name)) { admin_say("ERR", "dispositivo inválido"); return -1; }
@@ -115,7 +115,7 @@ static int target(const AdminReq *r, const char *name, int want, int allow_syste
return 0;
}
-/* ---- trabajos largos que se pueden cortar (disk-cancel) ---- */
+/* ---- long jobs that can be cancelled (disk-cancel) ---- */
static volatile sig_atomic_t cancelled;
static void on_cancel(int s) { (void)s; cancelled = 1; }
@@ -130,7 +130,7 @@ static void job_begin(const AdminReq *r, const char *disk) {
if (f) { fprintf(f, "%d %u\n", (int)getpid(), (unsigned)r->uid); fclose(f); }
struct sigaction sa = { .sa_handler = on_cancel };
sigaction(SIGTERM, &sa, NULL);
- /* que el escritorio no se trabe: prioridad baja de CPU y de disco (best effort, nivel 7) */
+ /* keep the desktop smooth: low CPU and disk priority (best effort, level 7) */
setpriority(PRIO_PROCESS, 0, 10);
syscall(SYS_ioprio_set, 1 /* IOPRIO_WHO_PROCESS */, 0, (2 << 13) | 7 /* IOPRIO_CLASS_BE, 7 */);
}
@@ -153,7 +153,7 @@ void disk_act_cancel(const AdminReq *r, const char *arg, size_t len) {
if (f) fclose(f);
if (!ok || pid <= 1) { admin_say("ERR", "no hay nada en curso en %s", arg); return; }
if (uid != r->uid && !r->admin) { admin_say("ERR", "lo empezó otro usuario"); return; }
- /* que sea de verdad un hijo de un ayudante (lord-admin) y no un pid reciclado */
+ /* it must really be a helper child (lord-admin), not a recycled pid */
char cp[64], comm[32] = "";
snprintf(cp, sizeof cp, "/proc/%d/comm", pid);
FILE *c = fopen(cp, "re");
@@ -163,13 +163,13 @@ void disk_act_cancel(const AdminReq *r, const char *arg, size_t len) {
admin_say("OK", "cancelando");
}
-/* ---- montajes ---- */
+/* ---- mounts ---- */
static int in_media(const char *point) {
return !strncmp(point, "/media/", 7) || !strncmp(point, "/run/media/", 11);
}
-/* Desmonta las de /media del dispositivo; con otros montajes (no del sistema) se niega. */
+/* Unmounts the device's mounts under /media; refuses if it is mounted anywhere else. */
static int unmount_dev(const char *name) {
char mounts[4096];
if (!disk_mounts(name, mounts, sizeof mounts)) return 0;
@@ -215,7 +215,7 @@ void disk_act_mount(const AdminReq *r, const char *arg, size_t len) {
if (disk_mounts(t.name, NULL, 0)) { admin_say("ERR", "%s ya está montado", t.name); return; }
char fs[32], label[256], uuid[96];
disk_udev_prop(t.name, "ID_FS_TYPE", fs, sizeof fs);
- disk_fs_label(t.name, label, sizeof label); /* sanitize_dir saca / y control */
+ disk_fs_label(t.name, label, sizeof label); /* sanitize_dir removes / and control characters */
disk_udev_prop(t.name, "ID_FS_UUID", uuid, sizeof uuid);
static const struct { const char *udev, *kernel; int owner, ro; } kinds[] = {
{ "vfat", "vfat", 1, 0 }, { "exfat", "exfat", 1, 0 }, { "ntfs", "ntfs3", 1, 0 }, { "ext4", "ext4", 0, 0 },
@@ -228,12 +228,12 @@ void disk_act_mount(const AdminReq *r, const char *arg, size_t len) {
char base[96], dir[PATH_MAX], leaf[200];
mkdir("/media", 0755);
snprintf(base, sizeof base, "/media/%.64s", r->user);
- if (mkdir(base, 0750) == 0 || errno == EEXIST) { if (chown(base, 0, r->gid)) { /* sigue */ } chmod(base, 0750); }
+ if (mkdir(base, 0750) == 0 || errno == EEXIST) { if (chown(base, 0, r->gid)) { /* keep going */ } chmod(base, 0750); }
sanitize_dir(label[0] ? label : uuid[0] ? uuid : t.name, leaf, sizeof leaf);
snprintf(dir, sizeof dir, "%s/%s", base, leaf);
for (int i = 2; mkdir(dir, 0700) && i < 100; i++) {
struct stat st;
- /* una carpeta vacía que quedó (y no es un montaje) se vuelve a usar */
+ /* an empty leftover folder (not a mount point) is reused */
if (errno == EEXIST && !lstat(dir, &st) && S_ISDIR(st.st_mode) && rmdir(dir) == 0 && mkdir(dir, 0700) == 0) break;
snprintf(dir, sizeof dir, "%s/%s %d", base, leaf, i);
}
@@ -279,8 +279,8 @@ static int sg_cmd(int fd, const uint8_t *cdb, int cdblen, void *buf, unsigned le
h.mx_sb_len = (unsigned char)slen;
h.timeout = 15000;
if (ioctl(fd, SG_IO, &h)) return -1;
- if (h.host_status || (h.driver_status & 0x07)) return -1; /* 0x08 = DRIVER_SENSE: trae sense, no es error */
- return h.status; /* 0 bien, 2 CHECK CONDITION (con sense) */
+ if (h.host_status || (h.driver_status & 0x07)) return -1; /* 0x08 = DRIVER_SENSE: sense data attached, not an error */
+ return h.status; /* 0 good, 2 CHECK CONDITION (with sense) */
}
static int ata_smart_read(int fd, uint8_t feature, uint8_t out[512]) {
@@ -290,7 +290,7 @@ static int ata_smart_read(int fd, uint8_t feature, uint8_t out[512]) {
return sg_cmd(fd, cdb, 16, out, 512, SG_DXFER_FROM_DEV, sense, sizeof sense) == 0 ? 0 : -1;
}
-/* RETURN STATUS: LBA mid/high 4Fh/C2h = bien, F4h/2Ch = umbral superado. */
+/* RETURN STATUS: LBA mid/high 4Fh/C2h = good, F4h/2Ch = threshold exceeded. */
static int ata_smart_status(int fd) {
uint8_t cdb[16] = { 0x85, 3 << 1, 0x20, 0, 0xda, 0, 0, 0, 0, 0, 0x4f, 0, 0xc2, 0, 0xb0, 0 };
uint8_t sense[64] = { 0 };
@@ -310,7 +310,7 @@ static int ata_smart_status(int fd) {
void disk_act_smart(const AdminReq *r, const char *arg, size_t len) {
(void)len;
Target t;
- if (target(r, arg, 1, 1, &t)) return; /* el del sistema también: solo se lee */
+ if (target(r, arg, 1, 1, &t)) return; /* the system disk too: read only */
if (strncmp(t.name, "sd", 2) && strncmp(t.name, "nvme", 4) && strncmp(t.name, "hd", 2)) {
admin_say("ERR", "este disco no informa SMART (%s)", t.name);
return;
@@ -328,7 +328,7 @@ void disk_act_smart(const AdminReq *r, const char *arg, size_t len) {
c.nsid = 0xffffffff;
c.addr = (uint64_t)(uintptr_t)log;
c.data_len = sizeof log;
- c.cdw10 = (127u << 16) | 0x02; /* 128 palabras, registro 02h */
+ c.cdw10 = (127u << 16) | 0x02; /* 128 dwords, log page 02h */
ok = ioctl(fd, NVME_IOCTL_ADMIN_CMD, &c) == 0 && smart_nvme_parse(log, &rep) == 0;
} else {
uint8_t data[512], th[512];
@@ -346,13 +346,13 @@ void disk_act_smart(const AdminReq *r, const char *arg, size_t len) {
admin_say("OK", "%.1f ms", (now_s() - t0) * 1000);
}
-/* ---- escribir en el dispositivo ---- */
+/* ---- writing to the device ---- */
static void uevent_change(const char *name) {
char p[PATH_MAX];
snprintf(p, sizeof p, "/sys/class/block/%s/uevent", name);
int fd = open(p, O_WRONLY | O_CLOEXEC);
- if (fd >= 0) { if (write(fd, "change", 6) < 0) { /* sigue */ } close(fd); }
+ if (fd >= 0) { if (write(fd, "change", 6) < 0) { /* keep going */ } close(fd); }
}
static void settle(void) {
@@ -374,7 +374,7 @@ static int zero_range(int fd, uint64_t off, uint64_t len) {
return 0;
}
-/* Borra firmas: el primer y el último MiB (MBR, GPT y su copia, superbloques del principio). */
+/* Wipes signatures: the first and last MiB (MBR, GPT and its backup, leading superblocks). */
static int wipe_ends(int fd, uint64_t size) {
uint64_t a = size < 2 * MIB ? size : MIB;
if (zero_range(fd, 0, a)) return -1;
@@ -393,7 +393,7 @@ static void part_name(const char *disk, int n, char *out, size_t cap) {
snprintf(out, cap, "%.24s%s%d", disk, l && isdigit((unsigned char)disk[l - 1]) ? "p" : "", n);
}
-/* Tabla MBR con una sola partición desde 1 MiB hasta el final. */
+/* MBR table with a single partition from 1 MiB to the end. */
static int write_mbr(int fd, uint64_t size, uint8_t type) {
uint64_t sectors = size / 512;
if (sectors > 0xffffffffull) return -2;
@@ -406,7 +406,7 @@ static int write_mbr(int fd, uint64_t size, uint8_t type) {
uint8_t *p = mbr + 446;
uint32_t start = 2048, count = (uint32_t)(sectors - start);
p[0] = 0x00;
- p[1] = 0xfe; p[2] = 0xff; p[3] = 0xff; /* CHS fuera de rango: se usa LBA */
+ p[1] = 0xfe; p[2] = 0xff; p[3] = 0xff; /* CHS out of range: LBA is used */
p[4] = type;
p[5] = 0xfe; p[6] = 0xff; p[7] = 0xff;
memcpy(p + 8, &start, 4);
@@ -416,7 +416,7 @@ static int write_mbr(int fd, uint64_t size, uint8_t type) {
return pwrite(fd, mbr, sizeof mbr, 0) == (ssize_t)sizeof mbr ? 0 : -1;
}
-/* Valida la etiqueta para ese sistema de archivos; para FAT la pasa a mayúsculas. */
+/* Validates the label for that file system; for FAT it uppercases it. */
static int valid_label(const char *fs, char *label) {
size_t n = strlen(label), cps = 0;
if (label[0] == '-') return 0;
@@ -440,7 +440,7 @@ static int valid_label(const char *fs, char *label) {
}
void disk_act_format(const AdminReq *r, const char *arg, size_t len) {
- /* <dispositivo>\n<fs>[\n<etiqueta>] */
+ /* <device>\n<fs>[\n<label>] */
char *buf = strndup(arg, len), *f[3] = { NULL, NULL, NULL };
int nf = 0;
for (char *s = buf; s && nf < 3; nf++) {
@@ -448,7 +448,7 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {
char *nl = strchr(s, '\n');
if (nl) *nl = 0;
s = nl ? nl + 1 : NULL;
- if (nf == 2 && nl) { nf = -1; break; } /* más líneas de la cuenta */
+ if (nf == 2 && nl) { nf = -1; break; } /* too many lines */
}
if (!buf || nf < 2) { admin_say("ERR", "argumento inválido"); free(buf); return; }
char *name = f[0], fsname[16], lab[64];
@@ -482,7 +482,7 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {
return;
}
fsync(fd);
- if (!strncmp(t.disk, "loop", 4)) { /* una imagen sin «partscan»: se lo prende */
+ if (!strncmp(t.disk, "loop", 4)) { /* an image without "partscan": turn it on */
struct loop_info64 li;
if (!ioctl(fd, LOOP_GET_STATUS64, &li) && !(li.lo_flags & LO_FLAGS_PARTSCAN)) {
li.lo_flags |= LO_FLAGS_PARTSCAN;
@@ -502,7 +502,7 @@ void disk_act_format(const AdminReq *r, const char *arg, size_t len) {
if (stat(dev, &st) || !S_ISBLK(st.st_mode)) { admin_say("ERR", "no apareció la partición nueva %s", dev); return; }
snprintf(t.name, sizeof t.name, "%s", pn);
} else {
- int e = zero_range(fd, 0, t.size < MIB ? t.size : MIB); /* firmas viejas al principio */
+ int e = zero_range(fd, 0, t.size < MIB ? t.size : MIB); /* old signatures at the start */
fsync(fd);
close(fd);
if (e) { admin_say("ERR", "no se pudo escribir en %s", t.name); return; }
@@ -579,7 +579,7 @@ void disk_act_erase(const AdminReq *r, const char *arg, size_t len) {
off += (uint64_t)w;
if (now_s() - last > 0.5 || off == t.size) {
last = now_s();
- fdatasync(fd); /* que el progreso sea real y no llene la caché */
+ fdatasync(fd); /* real progress, and don't fill the page cache */
admin_say("LOG", "progress phase=erase done=%llu total=%llu", (unsigned long long)off, (unsigned long long)t.size);
}
}
@@ -595,9 +595,9 @@ void disk_act_erase(const AdminReq *r, const char *arg, size_t len) {
else admin_say("OK", "borrado");
}
-/* ---- imagen → disco ---- */
+/* ---- image → disk ---- */
-/* Abre la imagen con los permisos del usuario, solo de su carpeta o de sus montajes. */
+/* Opens the image with the user's permissions, only from their home or their mounts. */
static int open_image(const AdminReq *r, const char *path, struct stat *st) {
if (path[0] != '/') return -1;
char real[PATH_MAX], roots[3][PATH_MAX];
@@ -643,7 +643,7 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {
if (in < 0) { admin_say("ERR", "no se pudo abrir la imagen (tiene que ser un archivo de tu carpeta o de tus discos)"); return; }
uint64_t total = (uint64_t)st.st_size;
if (total > t.size) { close(in); admin_say("ERR", "la imagen (%llu bytes) no entra en %s (%llu bytes)", (unsigned long long)total, t.name, (unsigned long long)t.size); return; }
- { /* la imagen no puede estar en el mismo disco */
+ { /* the image cannot be on the same disk */
char dn[32] = "", base[32] = "";
char p[64], real[PATH_MAX];
snprintf(p, sizeof p, "/sys/dev/block/%u:%u", major(st.st_dev), minor(st.st_dev));
@@ -671,7 +671,7 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {
if (k <= 0) { err = 1; break; }
sha256_update(&hs, b, (size_t)k);
size_t wl = (size_t)k;
- if (wl % (size_t)ssz) { /* el final que no es múltiplo del sector: sin O_DIRECT */
+ if (wl % (size_t)ssz) { /* a tail that is not a sector multiple: without O_DIRECT */
fcntl(out, F_SETFL, fcntl(out, F_GETFL) & ~O_DIRECT);
}
for (size_t o = 0; o < wl;) {
@@ -691,7 +691,7 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {
sha256_final(&hs, want);
if (!err && !cancelled && fsync(out)) err = 2;
double tw = now_s() - t0;
- /* verificación: se relee del disco (sin la caché) y se compara el SHA-256 */
+ /* verification: read the disk back (bypassing the cache) and compare the SHA-256 */
if (!err && !cancelled) {
ioctl(out, BLKFLSBUF);
close(out);
@@ -729,7 +729,7 @@ void disk_act_write_image(const AdminReq *r, const char *arg, size_t len) {
else admin_say("OK", "verificado sha256=%s ms=%.0f mbps=%.1f", hex, tw * 1000, tw > 0 ? total / tw / 1e6 : 0);
}
-/* ---- expulsar ---- */
+/* ---- eject ---- */
void disk_act_eject(const AdminReq *r, const char *arg, size_t len) {
(void)len;
@@ -737,7 +737,7 @@ void disk_act_eject(const AdminReq *r, const char *arg, size_t len) {
if (target(r, arg, 1, 0, &t)) return;
if (unmount_disk(&t)) return;
sync();
- /* nadie más lo tiene abierto en exclusiva (un borrado o una copia en curso) */
+ /* nobody else holds it exclusively (an erase or a copy in progress) */
int ex = open(t.dev, O_RDONLY | O_EXCL | O_NONBLOCK | O_CLOEXEC);
if (ex < 0 && errno == EBUSY) { admin_say("ERR", "%s está en uso: esperá a que termine lo que está haciendo", t.name); return; }
if (ex >= 0) close(ex);
@@ -751,7 +751,7 @@ void disk_act_eject(const AdminReq *r, const char *arg, size_t len) {
}
close(fd);
}
- /* por USB: se apaga el dispositivo (como «Apagar» de GNOME Discos) */
+ /* over USB: power the device off (like "Power Off" in GNOME Disks) */
char tr[16] = "", path[256] = "";
disk_udev_prop(t.name, "ID_BUS", tr, sizeof tr);
disk_udev_prop(t.name, "ID_PATH", path, sizeof path);
@@ -759,7 +759,7 @@ void disk_act_eject(const AdminReq *r, const char *arg, size_t len) {
char p[PATH_MAX];
snprintf(p, sizeof p, "/sys/block/%s/device/delete", t.disk);
int d = open(p, O_WRONLY | O_CLOEXEC);
- if (d >= 0) { if (write(d, "1", 1) < 0) { /* sigue */ } close(d); }
+ if (d >= 0) { if (write(d, "1", 1) < 0) { /* keep going */ } close(d); }
}
admin_say("OK", "expulsado");
}
diff --git a/server/src/disk/smart.c b/server/src/disk/smart.c
index 09b4e63..d5a99bc 100644
--- a/server/src/disk/smart.c
+++ b/server/src/disk/smart.c
@@ -1,16 +1,16 @@
-/* smart.c — analizadores de SMART (funciones puras, sin E/S; prueba: tests/smart_test.c).
+/* smart.c — SMART parsers (pure functions, no I/O; test: tests/smart_test.c).
*
- * ATA (ACS-3, «SMART READ DATA» 0xB0/0xD0 y «READ THRESHOLDS» 0xB0/0xD1, 512 bytes cada uno):
- * bytes 0-1 versión, 2-361: 30 atributos de 12 bytes
- * [0] id, [1-2] banderas (bit 0 = pre-falla), [3] valor normalizado, [4] peor, [5-10] crudo
- * (48 bits, little endian), [11] reservado;
- * byte 511: suma de comprobación (los 512 bytes suman 0 módulo 256).
- * Umbrales: misma posición, [0] id, [1] umbral.
- * NVMe (1.4, registro 02h «SMART / Health Information», 512 bytes):
- * [0] advertencia crítica, [1-2] temperatura (kelvin), [3] repuesto disponible %, [4] umbral del
- * repuesto, [5] % de vida usada, [32-47] unidades leídas, [48-63] escritas (unidades de 512 000
- * bytes), [112-127] ciclos de encendido, [128-143] horas encendido, [144-159] apagados
- * inseguros, [160-175] errores de medio (enteros de 128 bits; acá se usan los 64 de abajo). */
+ * ATA (ACS-3, "SMART READ DATA" 0xB0/0xD0 and "READ THRESHOLDS" 0xB0/0xD1, 512 bytes each):
+ * bytes 0-1 version, 2-361: 30 attributes of 12 bytes
+ * [0] id, [1-2] flags (bit 0 = pre-fail), [3] normalized value, [4] worst, [5-10] raw
+ * (48 bits, little endian), [11] reserved;
+ * byte 511: checksum (the 512 bytes sum to 0 modulo 256).
+ * Thresholds: same layout, [0] id, [1] threshold.
+ * NVMe (1.4, log page 02h "SMART / Health Information", 512 bytes):
+ * [0] critical warning, [1-2] temperature (kelvin), [3] available spare %, [4] spare
+ * threshold, [5] % life used, [32-47] data units read, [48-63] written (units of 512 000
+ * bytes), [112-127] power cycles, [128-143] power-on hours, [144-159] unsafe shutdowns,
+ * [160-175] media errors (128-bit integers; the low 64 bits are used here). */
#include "disk.h"
#include <stdio.h>
@@ -22,7 +22,7 @@ static uint64_t le(const uint8_t *p, int n) {
return v;
}
-/* 128 bits → 64 (si lo de arriba no es cero, se satura) */
+/* 128 bits → 64 (saturates if the high half is not zero) */
static uint64_t le128(const uint8_t *p) {
if (le(p + 8, 8)) return UINT64_MAX;
return le(p, 8);
@@ -60,7 +60,7 @@ int smart_ata_parse(const uint8_t data[512], const uint8_t *thresh, int status,
if (t[0] == x->id) { x->thresh = t[1]; break; }
}
}
- /* valor 0 o 0xFE/0xFF = sin dato (algunos discos); el umbral 0 nunca falla */
+ /* value 0 or 0xFE/0xFF = no data (some disks); threshold 0 never fails */
x->failing = x->thresh && x->value && x->value <= x->thresh && x->value < 0xfe;
if (x->failing && (x->flags & 1)) failing = 1;
switch (x->id) {
@@ -98,8 +98,8 @@ int smart_nvme_parse(const uint8_t log[512], SmartReport *r) {
r->power_on_hours = hrs > INT64_MAX ? INT64_MAX : (int64_t)hrs;
r->unsafe_shutdowns = le128(log + 144);
r->media_errors = le128(log + 160);
- /* bits de la advertencia: 0 repuesto bajo, 1 temperatura, 2 confiabilidad degradada,
- * 3 solo lectura, 4 copia volátil fallida */
+ /* warning bits: 0 low spare, 1 temperature, 2 degraded reliability, 3 read-only,
+ * 4 volatile backup failed */
if (r->crit_warning & 0x0d) r->health = SMART_FAIL;
else if (r->crit_warning || r->used_pct >= 100 || r->spare < r->spare_thresh || r->media_errors) r->health = SMART_WARN;
else r->health = SMART_OK;
diff --git a/server/src/fsops.c b/server/src/fsops.c
index 9f6e22e..8fe41dc 100644
--- a/server/src/fsops.c
+++ b/server/src/fsops.c
@@ -64,7 +64,10 @@ int fsops_protected(const char *real) {
"/.local/share/lordos/apps", "/.config/lordos/settings.json",
"/.config/lordos/permisos.json",
"/.config/lordos/firewall.json", /* permisos de red: una app no escribe sus reglas */
- "/.config/lordos/backup.json", /* Copias de seguridad: a dónde van los datos */
+ "/.config/lordos/backup.json", /* Backups: decides where the data goes */
+ "/.config/lordos/mail", /* Mail accounts and trusted certificates: only lord.mail.saveConfig (docs/MAIL.md) */
+ "/.local/share/lordos/mail", /* Mail cache: only lord-maild writes it */
+ "/.local/share/lordos/vault", /* Passwords vaults: only lord-vault writes them (docs/PASSWORDS.md) */
NULL };
for (int i = 0; protect[i]; i++) {
char p[PATH_MAX + 64];
diff --git a/server/src/hw/bt.c b/server/src/hw/bt.c
new file mode 100644
index 0000000..1fab523
--- /dev/null
+++ b/server/src/hw/bt.c
@@ -0,0 +1,560 @@
+/* bt.c — BlueZ client and pairing agent (see bt.h). */
+#include "bt.h"
+#include "jbuf.h"
+#include "sysbus.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define BLUEZ "org.bluez"
+#define AGENT_PATH "/org/lordos/BluetoothAgent"
+#define AGENT_IFACE "org.bluez.Agent1"
+
+static BtModel model;
+static BtEvent emit;
+static char owner[128]; /* org.bluez's unique name, "" if not running */
+static int dirty, agent_ok;
+
+/* the agent request waiting for the user (one at a time) */
+static struct {
+ int id, active;
+ DMsg call; /* kept to reply later (we own call.raw) */
+ char kind[20], dev[128], value[20];
+} prompt;
+static int next_prompt = 1;
+
+BtModel *bt_model(void) { return &model; }
+int bt_available(void) { return owner[0] != 0; }
+
+/* ---- model ---- */
+
+int bt_path_valid(const char *p) {
+ /* /org/bluez/hci<N>[/dev_XX_XX_XX_XX_XX_XX] */
+ if (!p || strncmp(p, "/org/bluez/hci", 14) || !isdigit((unsigned char)p[14])) return 0;
+ const char *s = p + 14;
+ while (isdigit((unsigned char)*s)) s++;
+ if (!*s) return 1;
+ if (strncmp(s, "/dev_", 5)) return 0;
+ s += 5;
+ for (int i = 0; i < 6; i++) {
+ if (!isxdigit((unsigned char)s[0]) || !isxdigit((unsigned char)s[1])) return 0;
+ s += 2;
+ if (i < 5) { if (*s != '_') return 0; s++; }
+ }
+ return *s == 0;
+}
+
+static int is_device_path(const char *p) { return bt_path_valid(p) && strstr(p, "/dev_"); }
+
+static BtAdapter *adapter(BtModel *m, const char *path, int create) {
+ for (int i = 0; i < m->nadapters; i++) if (!strcmp(m->adapters[i].path, path)) return &m->adapters[i];
+ if (!create || m->nadapters >= BT_MAX_ADAPTERS || strlen(path) >= sizeof m->adapters[0].path) return NULL;
+ BtAdapter *a = &m->adapters[m->nadapters++];
+ memset(a, 0, sizeof *a);
+ snprintf(a->path, sizeof a->path, "%s", path);
+ return a;
+}
+
+static BtDevice *device(BtModel *m, const char *path, int create) {
+ for (int i = 0; i < m->ndevices; i++) if (!strcmp(m->devices[i].path, path)) return &m->devices[i];
+ if (!create || m->ndevices >= BT_MAX_DEVICES || strlen(path) >= sizeof m->devices[0].path) return NULL;
+ BtDevice *d = &m->devices[m->ndevices++];
+ memset(d, 0, sizeof *d);
+ snprintf(d->path, sizeof d->path, "%s", path);
+ const char *slash = strstr(path, "/dev_");
+ size_t al = slash ? (size_t)(slash - path) : 0;
+ if (al < sizeof d->adapter) { memcpy(d->adapter, path, al); d->adapter[al] = 0; }
+ d->battery = -1;
+ return d;
+}
+
+static void copy_str(char *dst, size_t n, const char *src) { snprintf(dst, n, "%s", src ? src : ""); }
+
+/* One variant value: reads strings, booleans and integers; skips the rest. */
+typedef struct { const char *s; long long i; int is_str, is_num; } Val;
+
+static Val read_val(DRd *r, const char *sig) {
+ Val v = { 0 };
+ if (!sig || !sig[0] || sig[1]) { dr_skip(r, sig ? sig : "v"); return v; }
+ switch (sig[0]) {
+ case 's': case 'o': v.s = dr_str(r, NULL); v.is_str = 1; break;
+ case 'b': v.i = dr_bool(r); v.is_num = 1; break;
+ case 'y': v.i = dr_u8(r); v.is_num = 1; break;
+ case 'n': v.i = sb_i16(r); v.is_num = 1; break;
+ case 'q': v.i = sb_u16(r); v.is_num = 1; break;
+ case 'u': v.i = dr_u32(r); v.is_num = 1; break;
+ case 'i': v.i = dr_i32(r); v.is_num = 1; break;
+ default: dr_skip(r, sig); break;
+ }
+ return v;
+}
+
+void bt_apply_props(BtModel *m, const char *path, const char *iface, DRd *r) {
+ int is_adapter = !strcmp(iface, "org.bluez.Adapter1"), is_dev = !strcmp(iface, "org.bluez.Device1");
+ int is_batt = !strcmp(iface, "org.bluez.Battery1");
+ BtAdapter *a = is_adapter && bt_path_valid(path) && !is_device_path(path) ? adapter(m, path, 1) : NULL;
+ BtDevice *d = (is_dev || is_batt) && is_device_path(path) ? device(m, path, 1) : NULL;
+ size_t end = dr_arr(r, 8);
+ while (!r->err && dr_more(r, end)) {
+ dr_struct(r);
+ const char *k = dr_str(r, NULL);
+ const char *sig = dr_variant(r);
+ if (r->err || !k) break;
+ Val v = read_val(r, sig);
+ if (r->err) break;
+ if (a) {
+ if (!strcmp(k, "Address") && v.is_str) copy_str(a->address, sizeof a->address, v.s);
+ else if (!strcmp(k, "Alias") && v.is_str) copy_str(a->alias, sizeof a->alias, v.s);
+ else if (!strcmp(k, "Powered") && v.is_num) a->powered = (int)v.i;
+ else if (!strcmp(k, "Discoverable") && v.is_num) a->discoverable = (int)v.i;
+ else if (!strcmp(k, "Discovering") && v.is_num) a->discovering = (int)v.i;
+ else if (!strcmp(k, "Pairable") && v.is_num) a->pairable = (int)v.i;
+ } else if (d && is_dev) {
+ if (!strcmp(k, "Address") && v.is_str) copy_str(d->address, sizeof d->address, v.s);
+ else if (!strcmp(k, "Name") && v.is_str) copy_str(d->name, sizeof d->name, v.s);
+ else if (!strcmp(k, "Alias") && v.is_str) copy_str(d->alias, sizeof d->alias, v.s);
+ else if (!strcmp(k, "Icon") && v.is_str) copy_str(d->icon, sizeof d->icon, v.s);
+ else if (!strcmp(k, "Adapter") && v.is_str) copy_str(d->adapter, sizeof d->adapter, v.s);
+ else if (!strcmp(k, "Class") && v.is_num) d->cls = (uint32_t)v.i;
+ else if (!strcmp(k, "Appearance") && v.is_num) d->appearance = (uint16_t)v.i;
+ else if (!strcmp(k, "Paired") && v.is_num) d->paired = (int)v.i;
+ else if (!strcmp(k, "Bonded") && v.is_num) d->bonded = (int)v.i;
+ else if (!strcmp(k, "Trusted") && v.is_num) d->trusted = (int)v.i;
+ else if (!strcmp(k, "Connected") && v.is_num) d->connected = (int)v.i;
+ else if (!strcmp(k, "Blocked") && v.is_num) d->blocked = (int)v.i;
+ else if (!strcmp(k, "LegacyPairing") && v.is_num) d->legacy = (int)v.i;
+ else if (!strcmp(k, "RSSI") && v.is_num) { d->rssi = (int)v.i; d->has_rssi = 1; }
+ } else if (d && is_batt) {
+ if (!strcmp(k, "Percentage") && v.is_num) d->battery = (int)v.i;
+ }
+ }
+}
+
+void bt_remove_object(BtModel *m, const char *path, const char *iface) {
+ if (!strcmp(iface, "org.bluez.Device1")) {
+ for (int i = 0; i < m->ndevices; i++)
+ if (!strcmp(m->devices[i].path, path)) { m->devices[i] = m->devices[--m->ndevices]; break; }
+ } else if (!strcmp(iface, "org.bluez.Battery1")) {
+ BtDevice *d = device(m, path, 0);
+ if (d) d->battery = -1;
+ } else if (!strcmp(iface, "org.bluez.Adapter1")) {
+ for (int i = 0; i < m->nadapters; i++)
+ if (!strcmp(m->adapters[i].path, path)) { m->adapters[i] = m->adapters[--m->nadapters]; break; }
+ size_t pl = strlen(path);
+ for (int i = 0; i < m->ndevices;)
+ if (!strncmp(m->devices[i].path, path, pl) && m->devices[i].path[pl] == '/') m->devices[i] = m->devices[--m->ndevices];
+ else i++;
+ }
+}
+
+/* a{sa{sv}} for one object */
+static void parse_ifaces(BtModel *m, const char *path, DRd *r) {
+ size_t end = dr_arr(r, 8);
+ while (!r->err && dr_more(r, end)) {
+ dr_struct(r);
+ const char *iface = dr_str(r, NULL);
+ if (r->err || !iface) break;
+ bt_apply_props(m, path, iface, r);
+ }
+}
+
+int bt_parse_managed(BtModel *m, const DMsg *msg) {
+ if (!msg->sig || strcmp(msg->sig, "a{oa{sa{sv}}}")) return -1;
+ DRd r;
+ dr_init(&r, msg);
+ size_t end = dr_arr(&r, 8);
+ while (!r.err && dr_more(&r, end)) {
+ dr_struct(&r);
+ const char *path = dr_str(&r, NULL);
+ if (r.err || !path) break;
+ parse_ifaces(m, path, &r);
+ }
+ return r.err ? -1 : 0;
+}
+
+/* ---- events ---- */
+
+static void dev_json(HBuf *b, const BtDevice *d) {
+ hb_printf(b, "{\"path\":");
+ hb_str(b, d->path);
+ hb_printf(b, ",\"address\":");
+ hb_str(b, d->address);
+ hb_printf(b, ",\"name\":");
+ hb_str(b, d->alias[0] ? d->alias : d->name[0] ? d->name : d->address);
+ hb_printf(b, ",\"named\":%s,\"icon\":", d->name[0] || (d->alias[0] && strcmp(d->alias, d->address)) ? "true" : "false");
+ hb_str(b, d->icon);
+ hb_printf(b, ",\"class\":%u,\"appearance\":%u,\"paired\":%s,\"trusted\":%s,\"connected\":%s,\"blocked\":%s,\"busy\":%s,\"battery\":%d",
+ d->cls, d->appearance, d->paired || d->bonded ? "true" : "false", d->trusted ? "true" : "false", d->connected ? "true" : "false",
+ d->blocked ? "true" : "false", d->busy ? "true" : "false", d->battery);
+ if (d->has_rssi) hb_printf(b, ",\"rssi\":%d", d->rssi);
+ hb_printf(b, "}");
+}
+
+char *bt_state_json(void) {
+ HBuf b = { 0 };
+ const BtAdapter *a = model.nadapters ? &model.adapters[0] : NULL;
+ hb_printf(&b, "{\"available\":%s,\"agent\":%s,\"adapter\":", owner[0] ? "true" : "false", agent_ok ? "true" : "false");
+ if (a) {
+ hb_printf(&b, "{\"path\":");
+ hb_str(&b, a->path);
+ hb_printf(&b, ",\"address\":");
+ hb_str(&b, a->address);
+ hb_printf(&b, ",\"name\":");
+ hb_str(&b, a->alias);
+ hb_printf(&b, ",\"powered\":%s,\"discoverable\":%s,\"discovering\":%s}", a->powered ? "true" : "false",
+ a->discoverable ? "true" : "false", a->discovering ? "true" : "false");
+ } else hb_printf(&b, "null");
+ hb_printf(&b, ",\"devices\":[");
+ int first = 1;
+ for (int i = 0; i < model.ndevices; i++) {
+ const BtDevice *d = &model.devices[i];
+ if (a && strcmp(d->adapter, a->path)) continue; /* the first adapter's devices */
+ if (!first) hb_printf(&b, ",");
+ first = 0;
+ dev_json(&b, d);
+ }
+ hb_printf(&b, "],\"prompt\":");
+ if (prompt.active) {
+ const BtDevice *d = device(&model, prompt.dev, 0);
+ hb_printf(&b, "{\"id\":%d,\"kind\":", prompt.id);
+ hb_str(&b, prompt.kind);
+ hb_printf(&b, ",\"device\":");
+ hb_str(&b, prompt.dev);
+ hb_printf(&b, ",\"name\":");
+ hb_str(&b, d ? (d->alias[0] ? d->alias : d->name[0] ? d->name : d->address) : "");
+ hb_printf(&b, ",\"value\":");
+ hb_str(&b, prompt.value);
+ hb_printf(&b, "}");
+ } else hb_printf(&b, "null");
+ hb_printf(&b, "}");
+ return hb_take(&b);
+}
+
+void bt_flush_events(void) {
+ if (!dirty || !emit) return;
+ dirty = 0;
+ char *j = bt_state_json();
+ if (j) { emit("bt", j); free(j); }
+}
+
+typedef struct { char op[16], path[128]; } Op;
+
+static void result(const char *op, const char *path, int ok, const char *err) {
+ if (!emit) return;
+ HBuf b = { 0 };
+ hb_printf(&b, "{\"op\":");
+ hb_str(&b, op);
+ hb_printf(&b, ",\"path\":");
+ hb_str(&b, path);
+ hb_printf(&b, ",\"ok\":%s,\"error\":", ok ? "true" : "false");
+ hb_str(&b, err ? err : "");
+ hb_printf(&b, "}");
+ char *j = hb_take(&b);
+ if (j) { emit("bt-result", j); free(j); }
+}
+
+static Op *op_new(const char *op, const char *path) {
+ Op *o = calloc(1, sizeof *o);
+ if (o) { snprintf(o->op, sizeof o->op, "%s", op); snprintf(o->path, sizeof o->path, "%s", path ? path : ""); }
+ return o;
+}
+
+static const char *err_name(const DMsg *m) { return !m ? "org.freedesktop.DBus.Error.Disconnected" : m->type == DBUS_ERROR ? m->error : NULL; }
+
+/* ---- signals ---- */
+
+static void on_signal(const DMsg *m) {
+ if (!owner[0] || !m->sender || strcmp(m->sender, owner) || !m->member || !m->sig) return;
+ DRd r;
+ dr_init(&r, m);
+ if (!strcmp(m->member, "InterfacesAdded") && !strcmp(m->sig, "oa{sa{sv}}")) {
+ const char *path = dr_str(&r, NULL);
+ if (!r.err && path) parse_ifaces(&model, path, &r);
+ dirty = 1;
+ } else if (!strcmp(m->member, "InterfacesRemoved") && !strcmp(m->sig, "oas")) {
+ const char *path = dr_str(&r, NULL);
+ size_t end = dr_arr(&r, 4);
+ while (!r.err && path && dr_more(&r, end)) {
+ const char *iface = dr_str(&r, NULL);
+ if (!r.err && iface) bt_remove_object(&model, path, iface);
+ }
+ dirty = 1;
+ } else if (!strcmp(m->member, "PropertiesChanged") && !strcmp(m->sig, "sa{sv}as") && m->path) {
+ const char *iface = dr_str(&r, NULL);
+ if (!r.err && iface && (!strcmp(iface, "org.bluez.Adapter1") || !strcmp(iface, "org.bluez.Device1") || !strcmp(iface, "org.bluez.Battery1"))) {
+ /* a device's properties change before it is in the model only if we missed it */
+ if (strcmp(iface, "org.bluez.Adapter1") || adapter(&model, m->path, 0)) bt_apply_props(&model, m->path, iface, &r);
+ dirty = 1;
+ }
+ }
+}
+
+/* ---- agent ---- */
+
+static void prompt_drop(void) {
+ if (prompt.active) dbus_msg_free(&prompt.call);
+ prompt.active = 0;
+ dirty = 1;
+}
+
+static void agent_reject(const DMsg *m, const char *why) { dbus_error(sysbus_conn(), m, "org.bluez.Error.Rejected", why); }
+
+static int on_call(DMsg *m) {
+ if (!m->path || strcmp(m->path, AGENT_PATH)) return 0;
+ if (!owner[0] || !m->sender || strcmp(m->sender, owner)) { /* only bluetoothd talks to the agent */
+ dbus_error(sysbus_conn(), m, "org.freedesktop.DBus.Error.AccessDenied", "not bluetoothd");
+ return 1;
+ }
+ if (!m->iface || strcmp(m->iface, AGENT_IFACE) || !m->member) {
+ dbus_error(sysbus_conn(), m, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method");
+ return 1;
+ }
+ const char *mem = m->member, *sig = m->sig ? m->sig : "";
+ DRd r;
+ dr_init(&r, m);
+ if (!strcmp(mem, "Release")) { dbus_reply(sysbus_conn(), m, NULL, NULL); agent_ok = 0; dirty = 1; return 1; }
+ if (!strcmp(mem, "Cancel")) { prompt_drop(); dbus_reply(sysbus_conn(), m, NULL, NULL); return 1; }
+ const char *dev = sig[0] == 'o' ? dr_str(&r, NULL) : NULL;
+ if (r.err || !dev || !is_device_path(dev)) { dbus_error(sysbus_conn(), m, "org.freedesktop.DBus.Error.InvalidArgs", "device"); return 1; }
+ const char *kind = NULL;
+ char value[20] = "";
+ if (!strcmp(mem, "RequestPinCode") && !strcmp(sig, "o")) kind = "pin";
+ else if (!strcmp(mem, "RequestPasskey") && !strcmp(sig, "o")) kind = "passkey";
+ else if (!strcmp(mem, "RequestConfirmation") && !strcmp(sig, "ou")) { kind = "confirm"; snprintf(value, sizeof value, "%06u", dr_u32(&r)); }
+ else if (!strcmp(mem, "RequestAuthorization") && !strcmp(sig, "o")) kind = "authorize";
+ else if (!strcmp(mem, "AuthorizeService") && !strcmp(sig, "os")) {
+ const BtDevice *d = device(&model, dev, 0);
+ if (d && (d->paired || d->bonded) && d->trusted) { dbus_reply(sysbus_conn(), m, NULL, NULL); return 1; }
+ kind = "service";
+ } else if (!strcmp(mem, "DisplayPinCode") && !strcmp(sig, "os")) {
+ const char *pin = dr_str(&r, NULL);
+ kind = "display-pin";
+ snprintf(value, sizeof value, "%s", pin && strlen(pin) <= 16 ? pin : "");
+ } else if (!strcmp(mem, "DisplayPasskey") && !strcmp(sig, "ouq")) {
+ kind = "display-passkey";
+ snprintf(value, sizeof value, "%06u", dr_u32(&r));
+ } else { dbus_error(sysbus_conn(), m, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method"); return 1; }
+ if (r.err) { dbus_error(sysbus_conn(), m, "org.freedesktop.DBus.Error.InvalidArgs", "args"); return 1; }
+ if (prompt.active) { dbus_error(sysbus_conn(), &prompt.call, "org.bluez.Error.Canceled", "replaced"); prompt_drop(); }
+ int display_only = !strncmp(kind, "display-", 8);
+ if (display_only) dbus_reply(sysbus_conn(), m, NULL, NULL); /* informational: answered now */
+ prompt.id = next_prompt++;
+ prompt.active = 1;
+ snprintf(prompt.kind, sizeof prompt.kind, "%s", kind);
+ snprintf(prompt.dev, sizeof prompt.dev, "%s", dev);
+ snprintf(prompt.value, sizeof prompt.value, "%s", value);
+ prompt.call = *m;
+ m->raw = NULL; /* ours now: freed by prompt_drop */
+ if (display_only) prompt.call.flags |= DBUS_NO_REPLY;
+ dirty = 1;
+ bt_flush_events();
+ char *j = bt_state_json();
+ if (j && emit) emit("bt-prompt", j);
+ free(j);
+ return 1;
+}
+
+int bt_answer(int id, int accept, const char *value) {
+ if (!prompt.active || id != prompt.id) return -1;
+ DMsg *m = &prompt.call;
+ DConn *c = sysbus_conn();
+ const char *k = prompt.kind;
+ if (!strncmp(k, "display-", 8)) { prompt_drop(); return 0; }
+ if (!accept) { agent_reject(m, "rejected by the user"); prompt_drop(); return 0; }
+ if (!strcmp(k, "pin")) {
+ size_t n = value ? strlen(value) : 0;
+ int ok = n >= 1 && n <= 16;
+ for (size_t i = 0; ok && i < n; i++) if (!isalnum((unsigned char)value[i])) ok = 0;
+ if (!ok) return -1;
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, value);
+ dbus_reply(c, m, "s", &b);
+ dw_free(&b);
+ } else if (!strcmp(k, "passkey")) {
+ char *e = NULL;
+ unsigned long v = value ? strtoul(value, &e, 10) : 0;
+ if (!value || !*value || *e || v > 999999) return -1;
+ DBuf b;
+ dw_init(&b);
+ dw_u32(&b, (uint32_t)v);
+ dbus_reply(c, m, "u", &b);
+ dw_free(&b);
+ } else dbus_reply(c, m, NULL, NULL);
+ prompt_drop();
+ return 0;
+}
+
+/* ---- startup and owner changes ---- */
+
+static void got_managed(const DMsg *m, void *ctx) {
+ (void)ctx;
+ if (!m || m->type != DBUS_RETURN) return;
+ BtModel fresh;
+ memset(&fresh, 0, sizeof fresh);
+ if (bt_parse_managed(&fresh, m) == 0) {
+ /* keep our "busy" flags */
+ for (int i = 0; i < fresh.ndevices; i++) {
+ BtDevice *old = device(&model, fresh.devices[i].path, 0);
+ if (old) fresh.devices[i].busy = old->busy;
+ }
+ model = fresh;
+ }
+ dirty = 1;
+}
+
+static void got_default(const DMsg *m, void *ctx) {
+ (void)ctx;
+ agent_ok = m && m->type == DBUS_RETURN;
+ if (!agent_ok) fprintf(stderr, "bluetooth: could not become the default agent (%s)\n", err_name(m) ? err_name(m) : "?");
+ dirty = 1;
+}
+
+static void got_register(const DMsg *m, void *ctx) {
+ (void)ctx;
+ if (!m || m->type != DBUS_RETURN) {
+ fprintf(stderr, "bluetooth: RegisterAgent failed (%s)\n", err_name(m) ? err_name(m) : "?");
+ return;
+ }
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, AGENT_PATH);
+ sysbus_call(BLUEZ, "/org/bluez", "org.bluez.AgentManager1", "RequestDefaultAgent", "o", &b, got_default, NULL);
+ dw_free(&b);
+}
+
+static void on_owner(const char *name, const char *now) {
+ (void)name;
+ snprintf(owner, sizeof owner, "%s", now ? now : "");
+ if (!owner[0]) {
+ memset(&model, 0, sizeof model);
+ if (prompt.active) prompt_drop();
+ agent_ok = 0;
+ dirty = 1;
+ return;
+ }
+ sysbus_call(BLUEZ, "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", NULL, NULL, got_managed, NULL);
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, AGENT_PATH);
+ dw_str(&b, "KeyboardDisplay");
+ sysbus_call(BLUEZ, "/org/bluez", "org.bluez.AgentManager1", "RegisterAgent", "os", &b, got_register, NULL);
+ dw_free(&b);
+ dirty = 1;
+}
+
+void bt_start(BtEvent fn) {
+ emit = fn;
+ if (!sysbus_up()) return;
+ sysbus_on_signal(on_signal);
+ sysbus_on_call(on_call);
+ sysbus_add_match("type='signal',sender='org.bluez',interface='org.freedesktop.DBus.ObjectManager'");
+ sysbus_add_match("type='signal',sender='org.bluez',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path_namespace='/org/bluez'");
+ sysbus_watch_name(BLUEZ, on_owner);
+}
+
+/* ---- actions ---- */
+
+static void op_done(const DMsg *m, void *ctx) {
+ Op *o = ctx;
+ const char *err = err_name(m);
+ char full[256]; /* "org.bluez.Error.Failed: br-connection-profile-unavailable" */
+ if (err && m && m->sig && !strcmp(m->sig, "s")) {
+ DRd r;
+ dr_init(&r, m);
+ const char *text = dr_str(&r, NULL);
+ if (!r.err && text && *text) { snprintf(full, sizeof full, "%s: %s", err, text); err = full; }
+ }
+ BtDevice *d = o->path[0] ? device(&model, o->path, 0) : NULL;
+ if (!strcmp(o->op, "pair") && !err && d) {
+ /* paired: trust it (reconnects without asking) and connect, as macOS does */
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, "org.bluez.Device1");
+ dw_str(&b, "Trusted");
+ dw_variant(&b, "b");
+ dw_bool(&b, 1);
+ sysbus_call(BLUEZ, o->path, "org.freedesktop.DBus.Properties", "Set", "ssv", &b, NULL, NULL);
+ dw_free(&b);
+ Op *c = op_new("connect", o->path);
+ if (c && !sysbus_call(BLUEZ, o->path, "org.bluez.Device1", "Connect", NULL, NULL, op_done, c)) free(c);
+ else if (c) { result("pair", o->path, 1, NULL); free(o); dirty = 1; return; }
+ }
+ if (d) d->busy = 0;
+ result(o->op, o->path, !err, err);
+ dirty = 1;
+ free(o);
+}
+
+static int call_op(const char *op, const char *path, const char *iface, const char *member, const char *sig, const DBuf *body) {
+ Op *o = op_new(op, path);
+ if (!o) return -1;
+ if (!sysbus_call(BLUEZ, path, iface, member, sig, body, op_done, o)) { free(o); return -1; }
+ return 0;
+}
+
+static const BtAdapter *first_adapter(void) { return owner[0] && model.nadapters ? &model.adapters[0] : NULL; }
+
+int bt_power(int on) {
+ const BtAdapter *a = first_adapter();
+ if (!a) return -1;
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, "org.bluez.Adapter1");
+ dw_str(&b, "Powered");
+ dw_variant(&b, "b");
+ dw_bool(&b, on);
+ Op *o = op_new("power", "");
+ int ok = o && sysbus_call(BLUEZ, a->path, "org.freedesktop.DBus.Properties", "Set", "ssv", &b, op_done, o);
+ if (!ok) free(o);
+ dw_free(&b);
+ return ok ? 0 : -1;
+}
+
+int bt_discover(int on) {
+ const BtAdapter *a = first_adapter();
+ if (!a || (on && !a->powered)) return -1;
+ Op *o = op_new(on ? "discover" : "stop", "");
+ int ok = o && sysbus_call(BLUEZ, a->path, "org.bluez.Adapter1", on ? "StartDiscovery" : "StopDiscovery", NULL, NULL, op_done, o);
+ if (!ok) free(o);
+ return ok ? 0 : -1;
+}
+
+static BtDevice *known(const char *path) { return owner[0] && is_device_path(path) ? device(&model, path, 0) : NULL; }
+
+int bt_pair(const char *path) {
+ BtDevice *d = known(path);
+ if (!d) return -1;
+ if (call_op("pair", d->path, "org.bluez.Device1", "Pair", NULL, NULL)) return -1;
+ d->busy = 1;
+ dirty = 1;
+ return 0;
+}
+
+int bt_connect(const char *path) {
+ BtDevice *d = known(path);
+ if (!d || call_op("connect", d->path, "org.bluez.Device1", "Connect", NULL, NULL)) return -1;
+ d->busy = 1;
+ dirty = 1;
+ return 0;
+}
+
+int bt_disconnect(const char *path) {
+ BtDevice *d = known(path);
+ return d ? call_op("disconnect", d->path, "org.bluez.Device1", "Disconnect", NULL, NULL) : -1;
+}
+
+int bt_forget(const char *path) {
+ BtDevice *d = known(path);
+ if (!d || !d->adapter[0]) return -1;
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, d->path);
+ Op *o = op_new("forget", d->path);
+ int ok = o && sysbus_call(BLUEZ, d->adapter, "org.bluez.Adapter1", "RemoveDevice", "o", &b, op_done, o);
+ if (!ok) free(o);
+ dw_free(&b);
+ return ok ? 0 : -1;
+}
diff --git a/server/src/hw/bt.h b/server/src/hw/bt.h
new file mode 100644
index 0000000..08b0831
--- /dev/null
+++ b/server/src/hw/bt.h
@@ -0,0 +1,72 @@
+/* bt.h — Bluetooth for Settings → Bluetooth: BlueZ (bluetoothd) over the system bus with our
+ * own D-Bus client (hw/sysbus.c, vault/dbus.c). No libbluetooth, no bluetoothctl.
+ *
+ * - state: adapters and devices from ObjectManager.GetManagedObjects, kept up to date by the
+ * InterfacesAdded / InterfacesRemoved / PropertiesChanged signals (no polling);
+ * - actions: power, discovery, pair (then trust and connect), connect, disconnect, forget;
+ * - pairing agent: lord-server exports org.bluez.Agent1 at /org/lordos/BluetoothAgent
+ * ("KeyboardDisplay") and registers it as the default agent. PIN and passkey requests are
+ * shown by the system (sdk/bluetooth.js) and answered with bt_answer(). Calls to the agent
+ * are only accepted from org.bluez's unique bus name.
+ *
+ * Audio devices (headphones, speakers) show up in Sound through PipeWire's own BlueZ support.
+ * See docs/SETTINGS.md, "Bluetooth". */
+#ifndef LORD_HW_BT_H
+#define LORD_HW_BT_H
+
+#include <stdint.h>
+#include "../vault/dbus.h"
+
+#define BT_MAX_ADAPTERS 4
+#define BT_MAX_DEVICES 64
+
+typedef struct {
+ char path[96], address[20], alias[96];
+ int powered, discoverable, discovering, pairable;
+} BtAdapter;
+
+typedef struct {
+ char path[128], adapter[96], address[20], name[96], alias[96], icon[48];
+ uint32_t cls;
+ uint16_t appearance;
+ int paired, bonded, trusted, connected, blocked, legacy;
+ int rssi, has_rssi;
+ int battery; /* org.bluez.Battery1 percentage, -1 if none */
+ int busy; /* pairing/connecting in progress (ours) */
+} BtDevice;
+
+typedef struct {
+ BtAdapter adapters[BT_MAX_ADAPTERS];
+ int nadapters;
+ BtDevice devices[BT_MAX_DEVICES];
+ int ndevices;
+} BtModel;
+
+/* Called with (kind, json): "bt" (the whole state), "bt-prompt" (agent request), "bt-result"
+ * (an action finished: {op, path, ok, error}). */
+typedef void (*BtEvent)(const char *kind, const char *json);
+
+void bt_start(BtEvent fn); /* after sysbus_start */
+int bt_available(void); /* bluetoothd is on the bus */
+char *bt_state_json(void); /* malloc */
+/* Actions (async; the result arrives as "bt-result"). 0 if sent. */
+int bt_power(int on);
+int bt_discover(int on);
+int bt_pair(const char *dev_path);
+int bt_connect(const char *dev_path);
+int bt_disconnect(const char *dev_path);
+int bt_forget(const char *dev_path);
+/* Answer the pending agent request id: accept, with a PIN (text) or passkey (number) if asked. */
+int bt_answer(int id, int accept, const char *value);
+void bt_flush_events(void); /* once per main-loop turn: sends "bt" if it changed */
+
+/* ---- parsing, exposed for tests/bt_test.c ---- */
+BtModel *bt_model(void);
+/* Applies an interface's a{sv} properties (r positioned at the array) to the object at path. */
+void bt_apply_props(BtModel *mdl, const char *path, const char *iface, DRd *r);
+/* GetManagedObjects reply body (a{oa{sa{sv}}}) into the model. 0 if valid. */
+int bt_parse_managed(BtModel *mdl, const DMsg *m);
+void bt_remove_object(BtModel *mdl, const char *path, const char *iface);
+int bt_path_valid(const char *path); /* /org/bluez/hciN/dev_XX_XX_XX_XX_XX_XX */
+
+#endif
diff --git a/server/src/hw/defaults.c b/server/src/hw/defaults.c
new file mode 100644
index 0000000..4feba26
--- /dev/null
+++ b/server/src/hw/defaults.c
@@ -0,0 +1,127 @@
+/* defaults.c — default applications on disk (see defaults.h). */
+#include "defaults.h"
+#include "mimeapps.h"
+
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define LIST_MAX (256 * 1024)
+
+static char *slurp(const char *path) {
+ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return NULL;
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size > LIST_MAX) { close(fd); return NULL; }
+ char *b = malloc((size_t)st.st_size + 1);
+ ssize_t r = b ? read(fd, b, (size_t)st.st_size) : -1;
+ close(fd);
+ if (r < 0) { free(b); return NULL; }
+ b[r] = 0;
+ return b;
+}
+
+static const char *home(void) { const char *h = getenv("HOME"); return h && h[0] == '/' ? h : NULL; }
+
+static int write_atomic(const char *path, const char *text) {
+ char tmp[PATH_MAX + 8];
+ snprintf(tmp, sizeof tmp, "%s.tmp", path);
+ int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0644);
+ int ok = fd >= 0 && write(fd, text, strlen(text)) == (ssize_t)strlen(text);
+ if (fd >= 0) { ok = fsync(fd) == 0 && ok; close(fd); }
+ if (!ok || rename(tmp, path)) { unlink(tmp); return -1; }
+ return 0;
+}
+
+int defaults_lookup(const char *mime, char *id, size_t n) {
+ if (!mime_valid(mime)) return -1;
+ char paths[6][PATH_MAX];
+ int np = 0;
+ const char *h = home(), *xdg = getenv("XDG_CONFIG_HOME");
+ if (xdg && xdg[0] == '/') snprintf(paths[np++], PATH_MAX, "%s/mimeapps.list", xdg);
+ else if (h) snprintf(paths[np++], PATH_MAX, "%s/.config/mimeapps.list", h);
+ snprintf(paths[np++], PATH_MAX, "/etc/xdg/mimeapps.list");
+ if (h) snprintf(paths[np++], PATH_MAX, "%s/.local/share/applications/mimeapps.list", h);
+ snprintf(paths[np++], PATH_MAX, "/usr/local/share/applications/mimeapps.list");
+ snprintf(paths[np++], PATH_MAX, "/usr/share/applications/mimeapps.list");
+ snprintf(paths[np++], PATH_MAX, "/usr/share/applications/defaults.list");
+ char *removed_in = NULL; /* the user's file: its Removed Associations apply below */
+ for (int i = 0; i < np; i++) {
+ char *t = slurp(paths[i]);
+ if (!t) continue;
+ int found = mimeapps_default(t, mime, id, n) == 0 && !(removed_in && mimeapps_removed(removed_in, mime, id));
+ if (i == 0) removed_in = t;
+ else free(t);
+ if (found) { free(removed_in); return 0; }
+ }
+ free(removed_in);
+ return -1;
+}
+
+int defaults_set(const char *mime, const char *id) {
+ const char *h = home();
+ if (!h || !mime_valid(mime) || !desktop_id_valid(id)) return -1;
+ char dir[PATH_MAX], path[PATH_MAX];
+ snprintf(dir, sizeof dir, "%s/.config", h);
+ mkdir(dir, 0700);
+ snprintf(path, sizeof path, "%s/.config/mimeapps.list", h);
+ char *old = slurp(path);
+ char *now = mimeapps_set_default(old, mime, id);
+ free(old);
+ if (!now) return -1;
+ int r = write_atomic(path, now);
+ free(now);
+ return r;
+}
+
+int defaults_guess(const char *path, char *mime, size_t n) {
+ static char *globs;
+ static int tried;
+ if (!tried) { tried = 1; globs = slurp("/usr/share/mime/globs2"); }
+ return globs ? mime_guess(globs, path, mime, n) : -1;
+}
+
+int defaults_app_for(const char *path, char *id, size_t n) {
+ char mime[MIME_MAX], d[DESKTOP_ID_MAX];
+ if (defaults_guess(path, mime, sizeof mime) || defaults_lookup(mime, d, sizeof d)) return -1;
+ if (!strncmp(d, "lordos-", 7)) return -1; /* one of ours: the theme opens it */
+ size_t l = strlen(d) - 8; /* without ".desktop" */
+ if (l >= n) return -1;
+ memcpy(id, d, l);
+ id[l] = 0;
+ return 0;
+}
+
+int defaults_terminal(char *id, size_t n) {
+ const char *h = home();
+ if (!h) return -1;
+ char path[PATH_MAX];
+ snprintf(path, sizeof path, "%s/.config/xdg-terminals.list", h);
+ char *t = slurp(path);
+ if (!t) return -1;
+ int r = -1;
+ for (char *line = strtok(t, "\n"); line && r; line = strtok(NULL, "\n")) {
+ while (*line == ' ' || *line == '+') line++; /* "+" marks a preferred entry in the spec */
+ if (*line == '#' || !*line) continue;
+ char *sp = strpbrk(line, " :\t");
+ if (sp) *sp = 0;
+ if (desktop_id_valid(line) && strlen(line) < n) { snprintf(id, n, "%s", line); r = 0; }
+ }
+ free(t);
+ return r;
+}
+
+int defaults_set_terminal(const char *id) {
+ const char *h = home();
+ if (!h || !desktop_id_valid(id)) return -1;
+ char path[PATH_MAX], text[DESKTOP_ID_MAX + 96];
+ snprintf(path, sizeof path, "%s/.config", h);
+ mkdir(path, 0700);
+ snprintf(path, sizeof path, "%s/.config/xdg-terminals.list", h);
+ snprintf(text, sizeof text, "# Written by LordOS (Settings → Default Apps)\n%s\n", id);
+ return write_atomic(path, text);
+}
diff --git a/server/src/hw/defaults.h b/server/src/hw/defaults.h
new file mode 100644
index 0000000..0941c43
--- /dev/null
+++ b/server/src/hw/defaults.h
@@ -0,0 +1,23 @@
+/* defaults.h — default applications on disk (Settings → Default Apps): the user's
+ * ~/.config/mimeapps.list and the system ones, shared-mime-info's globs2, and the preferred
+ * terminal in ~/.config/xdg-terminals.list (the xdg-terminal-exec convention). LordOS's own apps
+ * are written as "lordos-<app>.desktop" (no such file exists; other desktops skip them). */
+#ifndef LORD_HW_DEFAULTS_H
+#define LORD_HW_DEFAULTS_H
+
+#include <stddef.h>
+
+/* Default app for a MIME type, following the spec's lookup order. 0 if found ("x.desktop"). */
+int defaults_lookup(const char *mime, char *id, size_t n);
+/* Sets it in ~/.config/mimeapps.list (atomic write, other lines kept). 0 if written. */
+int defaults_set(const char *mime, const char *id);
+/* MIME type of a file name (globs2). 0 if known. */
+int defaults_guess(const char *path, char *mime, size_t n);
+/* Linux app to open path with (its desktop id without ".desktop"): the default for its type,
+ * if that is a Linux app. 0 if there is one. */
+int defaults_app_for(const char *path, char *id, size_t n);
+/* Preferred terminal ("foot.desktop", "lordos-terminal.desktop"). */
+int defaults_terminal(char *id, size_t n);
+int defaults_set_terminal(const char *id);
+
+#endif
diff --git a/server/src/hw/display.c b/server/src/hw/display.c
new file mode 100644
index 0000000..1edaca9
--- /dev/null
+++ b/server/src/hw/display.c
@@ -0,0 +1,539 @@
+/* display.c — Settings → Displays, lord-server side (see display.h). */
+#include "display.h"
+#include "edid.h"
+#include "jbuf.h"
+#include "modes.h"
+#include "night.h"
+#include "../sec/json.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#define MAX_SAVED 16
+#define ID_MAX 96
+
+typedef struct { char id[ID_MAX]; int w, h, refresh, rot; } Saved;
+
+static struct {
+ const DisplayHost *host;
+ char path[PATH_MAX]; /* ~/.config/lordos/displays.json */
+ Saved saved[MAX_SAVED];
+ int nsaved;
+ char main_id[ID_MAX];
+ /* Night Shift */
+ int kelvin, soft;
+ uint8_t lut[3][256];
+ /* idle */
+ int off_s, lock_s, sleep_s;
+ double last;
+ int done_off, done_lock, done_sleep, off;
+ /* queued modeset */
+ int pending, prot, rot, prev_rot;
+ uint32_t pconn;
+ struct drm_mode_modeinfo pmode;
+} D = { .kelvin = NIGHT_K_MAX };
+
+static double now_ms(void) {
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return t.tv_sec * 1e3 + t.tv_nsec / 1e6;
+}
+
+static Kms *kms(void) { return D.host && D.host->kms ? D.host->kms() : NULL; }
+static void event(const char *kind, const char *json) { if (D.host && D.host->event) D.host->event(kind, json); }
+
+/* ---- identity ---- */
+
+static void output_identity(const KmsOutput *o, char *id, size_t n, char *name, size_t nn) {
+ Edid e;
+ if (o->edid && edid_parse(o->edid, o->edid_len, &e) == 0) {
+ edid_identity(&e, id, n);
+ if (name) edid_display_name(&e, name, nn);
+ return;
+ }
+ snprintf(id, n, "%s-%u", kms_connector_type_name(o->type), o->type_id);
+ if (name) snprintf(name, nn, "%s", id);
+}
+
+static Saved *saved_for(const char *id) {
+ for (int i = 0; i < D.nsaved; i++) if (!strcmp(D.saved[i].id, id)) return &D.saved[i];
+ return NULL;
+}
+
+/* ---- displays.json ---- */
+
+static void load(void) {
+ D.nsaved = 0;
+ D.main_id[0] = 0;
+ int fd = open(D.path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return;
+ char buf[16384];
+ ssize_t r = read(fd, buf, sizeof buf - 1);
+ close(fd);
+ if (r <= 0) return;
+ JDoc doc;
+ if (json_parse(buf, (size_t)r, &doc, NULL, 0)) { fprintf(stderr, "displays: invalid displays.json\n"); return; }
+ const char *m = json_str(doc.root, "main");
+ if (m && strlen(m) < ID_MAX) snprintf(D.main_id, sizeof D.main_id, "%s", m);
+ const JVal *ds = json_get(doc.root, "displays");
+ for (const JVal *v = ds && ds->type == J_OBJ ? ds->kid : NULL; v && D.nsaved < MAX_SAVED; v = v->next) {
+ if (v->type != J_OBJ || !v->key || strlen(v->key) >= ID_MAX) continue;
+ Saved *s = &D.saved[D.nsaved++];
+ snprintf(s->id, sizeof s->id, "%s", v->key);
+ s->w = (int)json_num(v, "w", 0);
+ s->h = (int)json_num(v, "h", 0);
+ s->refresh = (int)json_num(v, "refresh", 0);
+ s->rot = (int)json_num(v, "rotation", 0) & 3;
+ if (s->w < 0 || s->w > 16384 || s->h < 0 || s->h > 16384) s->w = s->h = 0;
+ }
+ json_free(&doc);
+}
+
+static int store(void) {
+ if (!D.path[0]) return -1;
+ HBuf b = { 0 };
+ hb_printf(&b, "{\n \"main\": ");
+ hb_str(&b, D.main_id);
+ hb_printf(&b, ",\n \"displays\": {");
+ for (int i = 0; i < D.nsaved; i++) {
+ const Saved *s = &D.saved[i];
+ hb_printf(&b, "%s\n ", i ? "," : "");
+ hb_str(&b, s->id);
+ hb_printf(&b, ": { \"w\": %d, \"h\": %d, \"refresh\": %d, \"rotation\": %d }", s->w, s->h, s->refresh, s->rot);
+ }
+ hb_printf(&b, "\n }\n}\n");
+ char *txt = hb_take(&b);
+ if (!txt) return -1;
+ char tmp[PATH_MAX + 8];
+ snprintf(tmp, sizeof tmp, "%s.tmp", D.path);
+ int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);
+ int ok = fd >= 0 && write(fd, txt, strlen(txt)) == (ssize_t)strlen(txt);
+ if (fd >= 0) { ok = fsync(fd) == 0 && ok; close(fd); }
+ free(txt);
+ if (!ok || rename(tmp, D.path)) { unlink(tmp); return -1; }
+ return 0;
+}
+
+void display_init(const DisplayHost *h) {
+ D.host = h;
+ const char *home = getenv("HOME");
+ if (home && home[0] == '/') {
+ char dir[PATH_MAX];
+ snprintf(dir, sizeof dir, "%s/.config", home);
+ mkdir(dir, 0700);
+ snprintf(dir, sizeof dir, "%s/.config/lordos", home);
+ mkdir(dir, 0700);
+ snprintf(D.path, sizeof D.path, "%s/.config/lordos/displays.json", home);
+ load();
+ }
+ /* lord-server started on its own card as root (development): the picker ran before $HOME was
+ * the user's, so the saved mode is applied now */
+ Kms *k = kms();
+ if (!k) return;
+ KmsOutput outs[KMS_MAX_OUTPUTS];
+ int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), idx = -1;
+ struct drm_mode_modeinfo m;
+ if (display_pick(outs, n, &idx, &m) == 0 && idx >= 0 &&
+ (outs[idx].id != k->conn_id || m.hdisplay != k->mode.hdisplay || m.vdisplay != k->mode.vdisplay || mode_refresh_mhz(&m) != mode_refresh_mhz(&k->mode) || D.prot != D.rot)) {
+ D.pending = 1;
+ D.pconn = outs[idx].id;
+ D.pmode = m;
+ }
+ kms_outputs_free(outs, n);
+}
+
+int display_pick(const KmsOutput *o, int n, int *index, struct drm_mode_modeinfo *mode) {
+ int sel = -1;
+ char id[ID_MAX];
+ for (int i = 0; i < n && sel < 0; i++) {
+ if (!o[i].connected || !o[i].nmodes) continue;
+ output_identity(&o[i], id, sizeof id, NULL, 0);
+ if (D.main_id[0] && !strcmp(id, D.main_id)) sel = i;
+ }
+ for (int i = 0; i < n && sel < 0; i++) if (o[i].connected && o[i].nmodes) sel = i;
+ if (sel < 0) return -1;
+ output_identity(&o[sel], id, sizeof id, NULL, 0);
+ const Saved *s = saved_for(id);
+ int m = s && s->w ? mode_pick(o[sel].modes, o[sel].nmodes, s->w, s->h, s->refresh) : -1;
+ if (m < 0) m = mode_preferred(o[sel].modes, o[sel].nmodes);
+ if (m < 0) return -1;
+ *index = sel;
+ *mode = o[sel].modes[m];
+ D.prot = s ? s->rot : 0;
+ D.rot = D.prot; /* kms_open/kms_attach use this mode right away */
+ return 0;
+}
+
+/* ---- Night Shift ---- */
+
+static void apply_tint(void) {
+ Kms *k = kms();
+ double r, g, b;
+ night_temp_rgb(D.kelvin, &r, &g, &b);
+ int was_soft = D.soft;
+ D.soft = 0;
+ int gs = k && !getenv("LORD_SOFT_GAMMA") ? kms_gamma_size(k) : 0;
+ if (gs > 1 && gs <= 4096) {
+ uint16_t *ramp = malloc((size_t)gs * 3 * sizeof *ramp);
+ if (ramp) {
+ night_ramp(gs, r, g, b, 1, ramp, ramp + gs, ramp + 2 * gs);
+ if (kms_set_gamma(k, gs, ramp, ramp + gs, ramp + 2 * gs)) gs = 0;
+ free(ramp);
+ } else gs = 0;
+ } else gs = 0;
+ if (!gs && D.kelvin != NIGHT_K_MAX) {
+ uint16_t R[256], G[256], B[256];
+ night_ramp(256, r, g, b, 1, R, G, B);
+ for (int i = 0; i < 256; i++) {
+ D.lut[0][i] = (uint8_t)(R[i] >> 8);
+ D.lut[1][i] = (uint8_t)(G[i] >> 8);
+ D.lut[2][i] = (uint8_t)(B[i] >> 8);
+ }
+ D.soft = 1;
+ }
+ if ((D.soft || was_soft) && D.host && D.host->redraw) D.host->redraw();
+ if (D.soft != was_soft) { /* Settings shows when the tint is by software */
+ char *j = display_list_json();
+ if (j) { event("display", j); free(j); }
+ }
+}
+
+void display_set_temperature(int kelvin) {
+ if (kelvin < NIGHT_K_MIN) kelvin = NIGHT_K_MIN;
+ if (kelvin > NIGHT_K_MAX) kelvin = NIGHT_K_MAX;
+ if (kelvin == D.kelvin) return;
+ D.kelvin = kelvin;
+ apply_tint();
+}
+
+int display_temperature(void) { return D.kelvin; }
+const uint8_t *display_soft_lut(void) { return D.soft ? &D.lut[0][0] : NULL; }
+
+void display_tint(Canvas *c, Rect r) {
+ if (!D.soft) return;
+ if (r.x0 < 0) r.x0 = 0;
+ if (r.y0 < 0) r.y0 = 0;
+ if (r.x1 > c->w) r.x1 = c->w;
+ if (r.y1 > c->h) r.y1 = c->h;
+ const uint8_t *lr = D.lut[0], *lg = D.lut[1], *lb = D.lut[2];
+ for (int y = r.y0; y < r.y1; y++) {
+ uint32_t *p = c->px + (size_t)y * c->stride;
+ for (int x = r.x0; x < r.x1; x++) {
+ uint32_t v = p[x];
+ p[x] = (v & 0xff000000u) | (uint32_t)lr[v >> 16 & 255] << 16 | (uint32_t)lg[v >> 8 & 255] << 8 | lb[v & 255];
+ }
+ }
+}
+
+int display_sun(const char *zone, int y, int m, int d, double *rise, double *set) {
+ static char *tab;
+ if (!tab) {
+ const char *paths[] = { "/usr/share/zoneinfo/zone1970.tab", "/usr/share/zoneinfo/zone.tab" };
+ for (int i = 0; i < 2 && !tab; i++) {
+ FILE *f = fopen(paths[i], "re");
+ if (!f) continue;
+ tab = calloc(1, 65536);
+ if (tab && fread(tab, 1, 65535, f) == 0) { free(tab); tab = NULL; }
+ fclose(f);
+ }
+ if (!tab) return -1;
+ }
+ double lat, lon;
+ if (!zone || night_zone_coords(tab, zone, &lat, &lon)) return -1;
+ return night_sun_times(y, m, d, lat, lon, rise, set);
+}
+
+/* ---- outputs, modes ---- */
+
+static void out_json(HBuf *b, const KmsOutput *o, const Kms *k) {
+ char id[ID_MAX], name[64], conn[48];
+ output_identity(o, id, sizeof id, name, sizeof name);
+ snprintf(conn, sizeof conn, "%s-%u", kms_connector_type_name(o->type), o->type_id);
+ Edid e;
+ int has_edid = o->edid && edid_parse(o->edid, o->edid_len, &e) == 0;
+ int current = k && o->id == k->conn_id;
+ hb_printf(b, "{\"id\":%u,\"connector\":", o->id);
+ hb_str(b, conn);
+ hb_printf(b, ",\"identity\":");
+ hb_str(b, id);
+ hb_printf(b, ",\"name\":");
+ hb_str(b, name);
+ hb_printf(b, ",\"builtin\":%s,\"connected\":%s,\"current\":%s,\"mmWidth\":%u,\"mmHeight\":%u,\"diagonal\":%d,\"vendor\":",
+ o->type == DRM_MODE_CONNECTOR_eDP || o->type == DRM_MODE_CONNECTOR_LVDS || o->type == DRM_MODE_CONNECTOR_DSI ? "true" : "false",
+ o->connected ? "true" : "false", current ? "true" : "false", o->mm_w, o->mm_h, has_edid ? edid_diagonal_tenths(&e) : 0);
+ hb_str(b, has_edid ? e.vendor : "");
+ int pref = mode_preferred(o->modes, o->nmodes);
+ hb_printf(b, ",\"preferred\":{\"w\":%d,\"h\":%d}", pref >= 0 ? o->modes[pref].hdisplay : 0, pref >= 0 ? o->modes[pref].vdisplay : 0);
+ if (current) hb_printf(b, ",\"mode\":{\"w\":%u,\"h\":%u,\"refresh\":%d}", k->mode.hdisplay, k->mode.vdisplay, mode_refresh_mhz(&k->mode));
+ const Saved *s = saved_for(id);
+ if (s) hb_printf(b, ",\"saved\":{\"w\":%d,\"h\":%d,\"refresh\":%d,\"rotation\":%d}", s->w, s->h, s->refresh, s->rot);
+ hb_printf(b, ",\"resolutions\":[");
+ int res[64];
+ int nr = mode_resolutions(o->modes, o->nmodes, res, 64);
+ for (int i = 0; i < nr; i++) {
+ int w = o->modes[res[i]].hdisplay, h = o->modes[res[i]].vdisplay, rates[16];
+ int nrt = mode_rates(o->modes, o->nmodes, w, h, rates, 16);
+ hb_printf(b, "%s{\"w\":%d,\"h\":%d,\"rates\":[", i ? "," : "", w, h);
+ for (int j = 0; j < nrt; j++) hb_printf(b, "%s%d", j ? "," : "", rates[j]);
+ hb_printf(b, "]}");
+ }
+ hb_printf(b, "]}");
+}
+
+char *display_list_json(void) {
+ Kms *k = kms();
+ HBuf b = { 0 };
+ hb_printf(&b, "{\"onMonitor\":%s,\"rotation\":%d,\"temperature\":%d,\"gammaSize\":%d,\"softTint\":%s,\"maxOutputs\":1,\"outputs\":[",
+ k ? "true" : "false", D.rot, D.kelvin, k ? kms_gamma_size(k) : 0, D.soft ? "true" : "false");
+ if (k) {
+ KmsOutput outs[KMS_MAX_OUTPUTS];
+ int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), first = 1;
+ for (int i = 0; i < n; i++) {
+ if (!outs[i].connected) continue;
+ if (!first) hb_printf(&b, ",");
+ first = 0;
+ out_json(&b, &outs[i], k);
+ }
+ kms_outputs_free(outs, n);
+ }
+ hb_printf(&b, "],\"backlight\":[");
+ /* backlight: readable by anyone; writing goes through the display-brightness admin action */
+ DIR *d = opendir("/sys/class/backlight");
+ int first = 1;
+ for (struct dirent *e; d && (e = readdir(d));) {
+ if (e->d_name[0] == '.' || strlen(e->d_name) > 64) continue;
+ char p[160], v[32] = "", mx[32] = "", ty[32] = "";
+ const char *names[3] = { "brightness", "max_brightness", "type" };
+ char *outs[3] = { v, mx, ty };
+ for (int i = 0; i < 3; i++) {
+ snprintf(p, sizeof p, "/sys/class/backlight/%s/%s", e->d_name, names[i]);
+ int fd = open(p, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) continue;
+ ssize_t r = read(fd, outs[i], 31);
+ close(fd);
+ if (r > 0) { outs[i][r] = 0; outs[i][strcspn(outs[i], "\n")] = 0; }
+ }
+ hb_printf(&b, "%s{\"name\":", first ? "" : ",");
+ hb_str(&b, e->d_name);
+ hb_printf(&b, ",\"value\":%ld,\"max\":%ld,\"type\":", atol(v), atol(mx));
+ hb_str(&b, ty);
+ hb_printf(&b, "}");
+ first = 0;
+ }
+ if (d) closedir(d);
+ hb_printf(&b, "]}");
+ return hb_take(&b);
+}
+
+int display_request(uint32_t conn, int w, int h, int refresh_mhz, int rotation) {
+ Kms *k = kms();
+ if (!k || rotation < 0 || rotation > 3) return -1;
+ KmsOutput outs[KMS_MAX_OUTPUTS];
+ int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), ret = -1;
+ for (int i = 0; i < n; i++) {
+ if (outs[i].id != conn || !outs[i].connected) continue;
+ int m = mode_pick(outs[i].modes, outs[i].nmodes, w, h, refresh_mhz);
+ if (m < 0) break;
+ D.pending = 1;
+ D.pconn = conn;
+ D.pmode = outs[i].modes[m];
+ D.prot = rotation;
+ ret = 0;
+ }
+ kms_outputs_free(outs, n);
+ return ret;
+}
+
+int display_take_modeset(uint32_t *conn, struct drm_mode_modeinfo *mode) {
+ if (!D.pending || !kms()) return 0;
+ D.pending = 0;
+ *conn = D.pconn;
+ *mode = D.pmode;
+ D.prev_rot = D.rot;
+ D.rot = D.prot;
+ return 1;
+}
+
+void display_modeset_done(int ok) {
+ if (!ok) D.rot = D.prev_rot;
+ apply_tint(); /* a new CRTC (or a modeset) can reset its LUT */
+ char *j = display_list_json();
+ if (j) { event("display", j); free(j); }
+}
+
+int display_rotation(void) { return D.rot; }
+
+void display_logical_size(int pw, int ph, int *lw, int *lh) {
+ int swap = D.rot & 1;
+ *lw = swap ? ph : pw;
+ *lh = swap ? pw : ph;
+}
+
+int display_save(uint32_t conn) {
+ Kms *k = kms();
+ if (!k || conn != k->conn_id) return -1;
+ KmsOutput outs[KMS_MAX_OUTPUTS];
+ int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), ret = -1;
+ for (int i = 0; i < n; i++) {
+ if (outs[i].id != conn) continue;
+ char id[ID_MAX];
+ output_identity(&outs[i], id, sizeof id, NULL, 0);
+ Saved *s = saved_for(id);
+ if (!s && D.nsaved < MAX_SAVED) s = &D.saved[D.nsaved++];
+ if (!s) s = &D.saved[MAX_SAVED - 1];
+ snprintf(s->id, sizeof s->id, "%s", id);
+ s->w = k->mode.hdisplay;
+ s->h = k->mode.vdisplay;
+ s->refresh = mode_refresh_mhz(&k->mode);
+ s->rot = D.rot;
+ snprintf(D.main_id, sizeof D.main_id, "%s", id);
+ ret = store();
+ }
+ kms_outputs_free(outs, n);
+ return ret;
+}
+
+void display_attached(void) {
+ D.off = 0;
+ D.last = now_ms();
+ D.done_off = D.done_lock = D.done_sleep = 0;
+ apply_tint();
+ char *j = display_list_json();
+ if (j) { event("display", j); free(j); }
+}
+
+void display_detached(void) { D.off = 0; D.soft = D.soft && D.kelvin != NIGHT_K_MAX; }
+
+void display_hotplug(void) {
+ Kms *k = kms();
+ if (k) {
+ KmsOutput outs[KMS_MAX_OUTPUTS];
+ int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), still = 0;
+ for (int i = 0; i < n; i++) if (outs[i].id == k->conn_id && outs[i].connected) still = 1;
+ int idx = -1;
+ struct drm_mode_modeinfo m;
+ /* the display in use was unplugged: move to another one (as the picker would) */
+ if (!still && display_pick(outs, n, &idx, &m) == 0 && idx >= 0) {
+ D.pending = 1;
+ D.pconn = outs[idx].id;
+ D.pmode = m;
+ fprintf(stderr, "displays: the display in use was unplugged; moving to %u\n", outs[idx].id);
+ }
+ kms_outputs_free(outs, n);
+ }
+ char *j = display_list_json();
+ if (j) { event("display", j); free(j); }
+}
+
+/* ---- idle ---- */
+
+void display_set_idle(int off_s, int lock_s, int sleep_s) {
+ D.off_s = off_s > 0 ? off_s : 0;
+ D.lock_s = lock_s > 0 ? lock_s : 0;
+ D.sleep_s = sleep_s > 0 ? sleep_s : 0;
+ D.last = now_ms();
+ D.done_off = D.done_lock = D.done_sleep = 0;
+}
+
+void display_wake(void) {
+ if (!D.off) return;
+ Kms *k = kms();
+ D.off = 0;
+ if (k) kms_dpms(k, 1);
+ if (D.host && D.host->redraw) D.host->redraw();
+ event("idle", "{\"stage\":\"wake\"}");
+}
+
+void display_activity(double now) {
+ D.last = now;
+ D.done_off = D.done_lock = D.done_sleep = 0;
+ if (D.off) display_wake();
+}
+
+static double deadline(int secs, int done) { return secs && !done ? D.last + secs * 1000.0 : -1; }
+
+double display_timeout(double now) {
+ if (!kms()) return -1;
+ double best = -1, ds[3] = { deadline(D.off_s, D.done_off), deadline(D.lock_s, D.done_lock), deadline(D.sleep_s, D.done_sleep) };
+ for (int i = 0; i < 3; i++) {
+ if (ds[i] < 0) continue;
+ double left = ds[i] - now;
+ if (left < 0) left = 0;
+ if (best < 0 || left < best) best = left;
+ }
+ return best;
+}
+
+void display_tick(double now) {
+ Kms *k = kms();
+ if (!k) return;
+ double off = deadline(D.off_s, D.done_off), lock = deadline(D.lock_s, D.done_lock), slp = deadline(D.sleep_s, D.done_sleep);
+ if (off >= 0 && now >= off) {
+ D.done_off = 1;
+ if (kms_dpms(k, 0) == 0) D.off = 1;
+ else fprintf(stderr, "displays: the card did not take DPMS off\n");
+ event("idle", "{\"stage\":\"off\"}");
+ }
+ if (lock >= 0 && now >= lock) { D.done_lock = 1; event("idle", "{\"stage\":\"lock\"}"); }
+ if (slp >= 0 && now >= slp) { D.done_sleep = 1; event("idle", "{\"stage\":\"sleep\"}"); }
+}
+
+int display_is_off(void) { return D.off; }
+
+/* ---- software rotation ---- */
+
+Rect display_rotate_rect(Rect r, int lw, int lh, int rot) {
+ switch (rot & 3) {
+ case 1: return (Rect){ lh - r.y1, r.x0, lh - r.y0, r.x1 }; /* (x, y) → (lh-1-y, x) */
+ case 2: return (Rect){ lw - r.x1, lh - r.y1, lw - r.x0, lh - r.y0 };
+ case 3: return (Rect){ r.y0, lw - r.x1, r.y1, lw - r.x0 }; /* (x, y) → (y, lw-1-x) */
+ default: return r;
+ }
+}
+
+/* Copies rect r (logical coordinates, inside lw×lh) to dst rotated; the logical pixel (x, y) is
+ * px[(y - oy) * stride + (x - ox)]. */
+void display_rotate_copy_at(const uint32_t *px, int stride, int ox, int oy, Rect r, int lw, int lh, Canvas *dst, int rot) {
+ if (r.x0 < 0) r.x0 = 0;
+ if (r.y0 < 0) r.y0 = 0;
+ if (r.x1 > lw) r.x1 = lw;
+ if (r.y1 > lh) r.y1 = lh;
+ if (r.x1 <= r.x0 || r.y1 <= r.y0) return;
+ rot &= 3;
+ for (int y = r.y0; y < r.y1; y++) {
+ const uint32_t *s = px + (size_t)(y - oy) * stride;
+ switch (rot) {
+ case 0: memcpy(dst->px + (size_t)y * dst->stride + r.x0, s + (r.x0 - ox), (size_t)(r.x1 - r.x0) * 4); break;
+ case 1: { uint32_t *col = dst->px + (lh - 1 - y); /* column lh-1-y, rows x */
+ for (int x = r.x0; x < r.x1; x++) col[(size_t)x * dst->stride] = s[x - ox];
+ break; }
+ case 2: { uint32_t *row = dst->px + (size_t)(lh - 1 - y) * dst->stride;
+ for (int x = r.x0; x < r.x1; x++) row[lw - 1 - x] = s[x - ox];
+ break; }
+ case 3: { uint32_t *col = dst->px + y; /* column y, rows lw-1-x */
+ for (int x = r.x0; x < r.x1; x++) col[(size_t)(lw - 1 - x) * dst->stride] = s[x - ox];
+ break; }
+ }
+ }
+}
+
+void display_rotate_copy(const Canvas *src, Rect r, Canvas *dst, int rot) {
+ display_rotate_copy_at(src->px, src->stride, 0, 0, r, src->w, src->h, dst, rot);
+}
+
+void display_unrotate_point(double px, double py, double *lx, double *ly) {
+ switch (D.rot & 3) {
+ case 1: *lx = py; *ly = 1 - px; break;
+ case 2: *lx = 1 - px; *ly = 1 - py; break;
+ case 3: *lx = 1 - py; *ly = px; break;
+ default: *lx = px; *ly = py; break;
+ }
+}
diff --git a/server/src/hw/display.h b/server/src/hw/display.h
new file mode 100644
index 0000000..9a710c3
--- /dev/null
+++ b/server/src/hw/display.h
@@ -0,0 +1,76 @@
+/* display.h — Settings → Displays on the lord-server side (docs/SETTINGS.md, "Displays").
+ *
+ * - lists the card's outputs with their EDID name, modes and the current one;
+ * - applies a resolution/refresh/output live (the modeset itself runs in main.c, between
+ * frames, through DisplayHost) and saves it per display (EDID identity) in
+ * ~/.config/lordos/displays.json, which the picker uses the next time the monitor is lent;
+ * - Night Shift: a color temperature on the CRTC gamma LUT, or a software LUT applied while
+ * copying the frame when the card has no gamma (virtio-gpu, some ARM boards);
+ * - idle: screen off (DPMS) after N seconds without input, plus "lock" and "sleep" notices for
+ * the theme. Deadlines go into the main loop's poll timeout: no polling;
+ * - hotplug: hw/uevent.c calls display_hotplug() on a DRM "change" uevent.
+ *
+ * One output at a time: kms.c drives a single CRTC. Mirroring and extending are not
+ * implemented (see docs/SETTINGS.md). */
+#ifndef LORD_HW_DISPLAY_H
+#define LORD_HW_DISPLAY_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include "../kms.h"
+#include "../canvas.h"
+
+typedef struct {
+ Kms *(*kms)(void); /* the card while the session is on the monitor, else NULL */
+ void (*redraw)(void); /* full damage (the software tint changed, screen back on) */
+ void (*event)(const char *kind, const char *json); /* → __lordHw(kind, data) */
+} DisplayHost;
+
+void display_init(const DisplayHost *h); /* after dropping root (needs $HOME) */
+/* For kms_set_picker: the saved mode and main display, by EDID identity. */
+int display_pick(const KmsOutput *o, int n, int *index, struct drm_mode_modeinfo *mode);
+void display_attached(void); /* the session got the monitor (or started on it) */
+void display_detached(void);
+void display_hotplug(void); /* DRM uevent: connectors may have changed */
+
+/* JSON for lord.display.list(). Returns a malloc'd string. */
+char *display_list_json(void);
+/* Apply live (not saved): output id, w×h, refresh in mHz (0 = best), rotation 0..3 (×90°).
+ * Queued; main.c runs it between frames (display_take_modeset). 0 if accepted. */
+int display_request(uint32_t conn, int w, int h, int refresh_mhz, int rotation);
+/* Save the current configuration of that output as its display's default (and as the main
+ * display). 0 if written. */
+int display_save(uint32_t conn);
+/* main.c: a queued modeset to run now (no flip pending). 1 if there is one. */
+int display_take_modeset(uint32_t *conn, struct drm_mode_modeinfo *mode);
+void display_modeset_done(int ok); /* main.c after kms_modeset (+ set_size, GPU restart) */
+int display_rotation(void); /* 0..3: the frame is rotated by software (CPU path) */
+/* Logical size for a physical one with the current rotation (90°/270° swap). */
+void display_logical_size(int pw, int ph, int *lw, int *lh);
+
+/* Software rotation (CPU path): rect r of the logical frame (lw×lh) in physical coordinates, and
+ * the copy of that rect from the logical canvas into the physical one. rot 1 = 90° clockwise. */
+Rect display_rotate_rect(Rect r, int lw, int lh, int rot);
+void display_rotate_copy(const Canvas *src, Rect r, Canvas *dst, int rot);
+/* Same, from a buffer whose first pixel is logical (ox, oy) (a cursor composited apart). */
+void display_rotate_copy_at(const uint32_t *px, int stride, int ox, int oy, Rect r, int lw, int lh, Canvas *dst, int rot);
+/* Physical normalized position (0..1, as a tablet reports it) → logical normalized position. */
+void display_unrotate_point(double px, double py, double *lx, double *ly);
+
+/* Night Shift: kelvin (6500 = off). Hardware gamma when the CRTC has one, else software. */
+void display_set_temperature(int kelvin);
+int display_temperature(void);
+const uint8_t *display_soft_lut(void); /* 3×256 (r, g, b) when the software tint is on, else NULL */
+void display_tint(Canvas *c, Rect r); /* apply the software LUT in place */
+/* Sunrise/sunset for a date at the time zone's coordinates (zone1970.tab), minutes UTC. */
+int display_sun(const char *zone, int y, int m, int d, double *rise, double *set);
+
+/* Idle (seconds; 0 = never): screen off, lock notice, sleep notice. */
+void display_set_idle(int off_s, int lock_s, int sleep_s);
+void display_activity(double now_ms); /* any input */
+double display_timeout(double now_ms); /* ms to the next idle deadline, or -1 */
+void display_tick(double now_ms);
+int display_is_off(void); /* DPMS off: main.c does not render */
+void display_wake(void); /* turn the screen back on now */
+
+#endif
diff --git a/server/src/hw/edid.c b/server/src/hw/edid.c
new file mode 100644
index 0000000..de5978c
--- /dev/null
+++ b/server/src/hw/edid.c
@@ -0,0 +1,75 @@
+/* edid.c — EDID reader (see edid.h). */
+#include "edid.h"
+
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+/* Text of a display descriptor: up to 13 bytes, ends with 0x0A and is padded with spaces.
+ * Printable ASCII only; anything else is dropped. */
+static void desc_text(const uint8_t *d, char *out) {
+ int n = 0;
+ for (int i = 5; i < 18; i++) {
+ uint8_t c = d[i];
+ if (c == 0x0a || c == 0) break;
+ if (c >= 0x20 && c < 0x7f) out[n++] = (char)c;
+ }
+ while (n > 0 && out[n - 1] == ' ') n--;
+ out[n] = 0;
+}
+
+int edid_parse(const uint8_t *d, size_t len, Edid *e) {
+ static const uint8_t hdr[8] = { 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 };
+ memset(e, 0, sizeof *e);
+ if (!d || len < 128 || memcmp(d, hdr, 8)) return -1;
+ uint8_t sum = 0;
+ for (int i = 0; i < 128; i++) sum = (uint8_t)(sum + d[i]);
+ if (sum) return -1;
+ unsigned m = (unsigned)d[8] << 8 | d[9];
+ for (int i = 0; i < 3; i++) {
+ unsigned c = (m >> (10 - 5 * i)) & 31;
+ e->vendor[i] = c >= 1 && c <= 26 ? (char)('A' + c - 1) : '?';
+ }
+ e->product = (uint16_t)(d[10] | d[11] << 8);
+ e->serial = (uint32_t)d[12] | (uint32_t)d[13] << 8 | (uint32_t)d[14] << 16 | (uint32_t)d[15] << 24;
+ e->week = d[16];
+ e->year = d[17] ? 1990 + d[17] : 0;
+ e->version = d[18];
+ e->revision = d[19];
+ e->digital = d[20] >> 7;
+ e->width_cm = d[21];
+ e->height_cm = d[22];
+ for (int k = 0; k < 4; k++) {
+ const uint8_t *x = d + 54 + 18 * k;
+ if (x[0] || x[1]) { /* detailed timing */
+ if (!e->pref_w) {
+ e->pref_w = x[2] | (x[4] & 0xf0) << 4;
+ e->pref_h = x[5] | (x[7] & 0xf0) << 4;
+ }
+ continue;
+ }
+ if (x[3] == 0xfc) desc_text(x, e->name);
+ else if (x[3] == 0xff) desc_text(x, e->serial_text);
+ }
+ return 0;
+}
+
+void edid_identity(const Edid *e, char *out, size_t n) {
+ if (e->serial_text[0]) snprintf(out, n, "%s-%04x-%s", e->vendor, e->product, e->serial_text);
+ else if (e->serial) snprintf(out, n, "%s-%04x-%08x", e->vendor, e->product, e->serial);
+ else snprintf(out, n, "%s-%04x-%s", e->vendor, e->product, e->name[0] ? e->name : "0");
+ /* only [A-Za-z0-9.-]: used as a displays.json key */
+ for (char *p = out; *p; p++)
+ if (!((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '-' || *p == '.')) *p = '_';
+}
+
+void edid_display_name(const Edid *e, char *out, size_t n) {
+ if (e->name[0]) snprintf(out, n, "%s", e->name);
+ else snprintf(out, n, "%s %04X", e->vendor, e->product);
+}
+
+int edid_diagonal_tenths(const Edid *e) {
+ if (e->width_cm <= 0 || e->height_cm <= 0) return 0;
+ double in = sqrt((double)e->width_cm * e->width_cm + (double)e->height_cm * e->height_cm) / 2.54;
+ return (int)(in * 10 + 0.5);
+}
diff --git a/server/src/hw/edid.h b/server/src/hw/edid.h
new file mode 100644
index 0000000..5bd8e85
--- /dev/null
+++ b/server/src/hw/edid.h
@@ -0,0 +1,34 @@
+/* edid.h — our own EDID 1.3/1.4 reader (the 128-byte base block a monitor sends).
+ * Used to name displays in Settings → Displays and to store each display's configuration by
+ * its identity (vendor, product and serial number) rather than by connector. See
+ * docs/SETTINGS.md, "Displays". */
+#ifndef LORD_HW_EDID_H
+#define LORD_HW_EDID_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+typedef struct {
+ char vendor[4]; /* 3-letter PNP code ("DEL", "SAM"...) */
+ uint16_t product;
+ uint32_t serial; /* binary serial number (0 if not reported) */
+ char name[14]; /* 0xFC descriptor: monitor name ("DELL U2720Q") */
+ char serial_text[14]; /* 0xFF descriptor: serial number as text */
+ int year, week; /* manufacture date */
+ int width_cm, height_cm; /* physical size (0 = unknown, e.g. a projector) */
+ int pref_w, pref_h; /* first detailed timing (the native mode) */
+ int version, revision; /* 1.3, 1.4 */
+ int digital;
+} Edid;
+
+/* 0 if the base block is a valid EDID (header and checksum). Reads only validated bytes. */
+int edid_parse(const uint8_t *data, size_t len, Edid *e);
+/* Stable identity used as the settings key: "DEL-a0c4-12345678" or, without a serial, with the
+ * name. Two identical monitors without serial numbers share an identity (see docs/SETTINGS.md). */
+void edid_identity(const Edid *e, char *out, size_t n);
+/* Display name: the descriptor's, or "<vendor> <product>". */
+void edid_display_name(const Edid *e, char *out, size_t n);
+/* Diagonal in tenths of an inch (240 = 24.0"), 0 if unknown. */
+int edid_diagonal_tenths(const Edid *e);
+
+#endif
diff --git a/server/src/hw/hw.c b/server/src/hw/hw.c
new file mode 100644
index 0000000..4ca7fea
--- /dev/null
+++ b/server/src/hw/hw.c
@@ -0,0 +1,116 @@
+/* hw.c — main-loop glue for Settings' hardware modules (see hw.h). */
+#include "hw.h"
+#include "bt.h"
+#include "jbuf.h"
+#include "notifyd.h"
+#include "ppd.h"
+#include "sysbus.h"
+#include "uevent.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static const DisplayHost *host;
+static PowerState power;
+
+void hw_emit(const char *kind, const char *json) { if (host && host->event) host->event(kind, json); }
+const PowerState *hw_power(void) { return &power; }
+
+static void power_changed(void) {
+ power_read("/sys/class/power_supply", &power);
+ char j[4096];
+ power_json(&power, j, sizeof j);
+ hw_emit("power", j);
+}
+
+static void td_signal(const DMsg *m) {
+ if (m->path && !strcmp(m->path, "/org/freedesktop/timedate1") && m->member && !strcmp(m->member, "PropertiesChanged")) hw_timedate_refresh();
+}
+
+void hw_start(const DisplayHost *h, int with_bus) {
+ host = h;
+ display_init(h);
+ power_read("/sys/class/power_supply", &power);
+ if (uevent_open()) fprintf(stderr, "hw: no kernel uevents (hotplugged displays and batteries are not followed)\n");
+ if (with_bus && notifyd_start(hw_emit)) fprintf(stderr, "hw: no notification server for Linux apps\n");
+ if (with_bus && sysbus_start() == 0) {
+ bt_start(hw_emit);
+ ppd_start(hw_emit);
+ sysbus_on_signal(td_signal);
+ sysbus_add_match("type='signal',sender='org.freedesktop.timedate1',interface='org.freedesktop.DBus.Properties',path='/org/freedesktop/timedate1'");
+ }
+}
+
+int hw_pollfds(struct pollfd *p, int max) {
+ int n = 0;
+ if (n < max && uevent_fd() >= 0) p[n++] = (struct pollfd){ uevent_fd(), POLLIN, 0 };
+ if (n < max && notifyd_fd() >= 0) p[n++] = (struct pollfd){ notifyd_fd(), (short)(POLLIN | (notifyd_wants_write() ? POLLOUT : 0)), 0 };
+ if (n < max && sysbus_fd() >= 0) p[n++] = (struct pollfd){ sysbus_fd(), (short)(POLLIN | (sysbus_wants_write() ? POLLOUT : 0)), 0 };
+ return n;
+}
+
+void hw_dispatch(const struct pollfd *p, int n) {
+ for (int i = 0; i < n; i++) {
+ if (!p[i].revents) continue;
+ if (p[i].fd == uevent_fd()) {
+ int m = uevent_dispatch();
+ if (m & UEV_DRM) display_hotplug();
+ if (m & UEV_POWER) power_changed();
+ if (m & UEV_BACKLIGHT) display_hotplug(); /* the list carries the backlight */
+ } else if (p[i].fd == sysbus_fd()) sysbus_dispatch();
+ else if (p[i].fd == notifyd_fd()) notifyd_dispatch();
+ }
+}
+
+void hw_events(void) {
+ bt_flush_events();
+ if (sysbus_up() && sysbus_wants_write()) dbus_flush(sysbus_conn());
+}
+
+/* ---- timedated (read-only: NTP, synchronized, can NTP) ---- */
+
+static void got_timedate(const DMsg *m, void *ctx) {
+ (void)ctx;
+ int ntp = 0, synced = 0, can = 0, rtc = 0;
+ char zone[96] = "";
+ if (m && m->type == DBUS_RETURN && m->sig && !strcmp(m->sig, "a{sv}")) {
+ DRd r;
+ dr_init(&r, m);
+ size_t end = dr_arr(&r, 8);
+ while (!r.err && dr_more(&r, end)) {
+ dr_struct(&r);
+ const char *k = dr_str(&r, NULL), *sig = dr_variant(&r);
+ if (r.err || !k || !sig) break;
+ if (!strcmp(sig, "b")) {
+ int v = dr_bool(&r);
+ if (!strcmp(k, "NTP")) ntp = v;
+ else if (!strcmp(k, "NTPSynchronized")) synced = v;
+ else if (!strcmp(k, "CanNTP")) can = v;
+ else if (!strcmp(k, "LocalRTC")) rtc = v;
+ } else if (!strcmp(sig, "s") && !strcmp(k, "Timezone")) {
+ const char *z = dr_str(&r, NULL);
+ snprintf(zone, sizeof zone, "%s", z ? z : "");
+ } else dr_skip(&r, sig);
+ }
+ }
+ HBuf b = { 0 };
+ hb_printf(&b, "{\"available\":%s,\"ntp\":%s,\"synced\":%s,\"canNTP\":%s,\"localRTC\":%s,\"zone\":",
+ m && m->type == DBUS_RETURN ? "true" : "false", ntp ? "true" : "false", synced ? "true" : "false",
+ can ? "true" : "false", rtc ? "true" : "false");
+ hb_str(&b, zone);
+ hb_printf(&b, "}");
+ char *j = hb_take(&b);
+ if (j) hw_emit("timedate", j);
+ free(j);
+}
+
+void hw_timedate_refresh(void) {
+ if (!sysbus_up()) { got_timedate(NULL, NULL); return; }
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, "org.freedesktop.timedate1");
+ if (!sysbus_call("org.freedesktop.timedate1", "/org/freedesktop/timedate1", "org.freedesktop.DBus.Properties", "GetAll", "s", &b, got_timedate, NULL))
+ got_timedate(NULL, NULL);
+ dw_free(&b);
+}
diff --git a/server/src/hw/hw.h b/server/src/hw/hw.h
new file mode 100644
index 0000000..75e9818
--- /dev/null
+++ b/server/src/hw/hw.h
@@ -0,0 +1,20 @@
+/* hw.h — glue for Settings' hardware modules in lord-server's main loop: displays, uevents,
+ * the system bus (Bluetooth, power profiles, timedated) and batteries. See docs/SETTINGS.md. */
+#ifndef LORD_HW_H
+#define LORD_HW_H
+
+#include <poll.h>
+#include "display.h"
+#include "power.h"
+
+/* After dropping root. host->event receives every notice ("display", "idle", "power", "bt",
+ * "bt-prompt", "bt-result", "ppd", "ppd-result", "timedate"). */
+void hw_start(const DisplayHost *host, int with_bus);
+int hw_pollfds(struct pollfd *p, int max);
+void hw_dispatch(const struct pollfd *p, int n);
+void hw_events(void); /* once per loop turn (coalesced Bluetooth state) */
+const PowerState *hw_power(void);
+void hw_emit(const char *kind, const char *json);
+void hw_timedate_refresh(void); /* asks timedated; answer as "timedate" */
+
+#endif
diff --git a/server/src/hw/hw_admin.c b/server/src/hw/hw_admin.c
new file mode 100644
index 0000000..36add73
--- /dev/null
+++ b/server/src/hw/hw_admin.c
@@ -0,0 +1,219 @@
+/* hw_admin.c — Settings' admin actions (see hw_admin.h). Runs as root in the admin helper. */
+#include "hw_admin.h"
+
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <linux/rfkill.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+/* One argument line, trimmed, into out. 0 if it fits. */
+static int arg_copy(const char *arg, size_t len, char *out, size_t n) {
+ while (len && (arg[len - 1] == '\n' || arg[len - 1] == ' ')) len--;
+ if (len >= n || memchr(arg, '\n', len) || memchr(arg, 0, len)) return -1;
+ memcpy(out, arg, len);
+ out[len] = 0;
+ return 0;
+}
+
+static int write_file(const char *path, const char *text) {
+ int fd = open(path, O_WRONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return -1;
+ ssize_t w = write(fd, text, strlen(text));
+ int e = errno;
+ close(fd);
+ errno = e;
+ return w == (ssize_t)strlen(text) ? 0 : -1;
+}
+
+static long read_long(const char *path) {
+ char b[32];
+ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return -1;
+ ssize_t r = read(fd, b, sizeof b - 1);
+ close(fd);
+ if (r <= 0) return -1;
+ b[r] = 0;
+ char *e;
+ long v = strtol(b, &e, 10);
+ return (*e == 0 || *e == '\n') ? v : -1;
+}
+
+/* ---- backlight ---- */
+
+int hw_backlight_name_valid(const char *n) {
+ size_t l = n ? strlen(n) : 0;
+ if (!l || l > 64 || n[0] == '.') return 0;
+ for (const char *p = n; *p; p++) if (!(isalnum((unsigned char)*p) || strchr("_-.:", *p))) return 0;
+ return 1;
+}
+
+void hw_act_brightness(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ char a[128], name[72];
+ long v;
+ if (arg_copy(arg, len, a, sizeof a) || sscanf(a, "%71s %ld", name, &v) != 2 || !hw_backlight_name_valid(name)) {
+ admin_say("ERR", "invalid argument");
+ return;
+ }
+ /* the entry has to be a real backlight device under /sys/devices */
+ char link[PATH_MAX], real[PATH_MAX];
+ snprintf(link, sizeof link, "/sys/class/backlight/%s", name);
+ if (!realpath(link, real) || strncmp(real, "/sys/devices/", 13)) { admin_say("ERR", "no such backlight"); return; }
+ char p[PATH_MAX + 32];
+ snprintf(p, sizeof p, "%s/max_brightness", real);
+ long max = read_long(p);
+ if (max <= 0 || v < 0 || v > max) { admin_say("ERR", "value out of range (0..%ld)", max); return; }
+ char val[32];
+ snprintf(val, sizeof val, "%ld\n", v);
+ snprintf(p, sizeof p, "%s/brightness", real);
+ if (write_file(p, val)) admin_say("ERR", "could not set the brightness: %s", strerror(errno));
+ else admin_say("OK", "%ld", v);
+}
+
+/* ---- power profile ---- */
+
+static int file_ok(const char *path) {
+ struct stat st;
+ return stat(path, &st) == 0 && S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 022);
+}
+
+void hw_act_power_profile(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ char p[24];
+ if (arg_copy(arg, len, p, sizeof p) || (strcmp(p, "performance") && strcmp(p, "balanced") && strcmp(p, "power-saver"))) {
+ admin_say("ERR", "invalid profile");
+ return;
+ }
+ if (file_ok("/usr/bin/powerprofilesctl")) {
+ const char *const argv[] = { "/usr/bin/powerprofilesctl", "set", p, NULL };
+ int code = admin_run(argv);
+ if (code) admin_say("ERR", "powerprofilesctl failed (%d)", code);
+ else admin_say("OK", "%s", p);
+ return;
+ }
+ /* no daemon: the cpufreq governor of every policy (and the energy/performance preference) */
+ DIR *d = opendir("/sys/devices/system/cpu/cpufreq");
+ if (!d) { admin_say("ERR", "this computer has no CPU frequency scaling"); return; }
+ int done = 0, failed = 0;
+ for (struct dirent *e; (e = readdir(d));) {
+ if (strncmp(e->d_name, "policy", 6) || !isdigit((unsigned char)e->d_name[6])) continue;
+ char path[400], avail[512] = "";
+ snprintf(path, sizeof path, "/sys/devices/system/cpu/cpufreq/%s/scaling_available_governors", e->d_name);
+ int fd = open(path, O_RDONLY | O_CLOEXEC);
+ if (fd >= 0) { ssize_t n = read(fd, avail, sizeof avail - 1); if (n > 0) avail[n] = 0; close(fd); }
+ const char *want = !strcmp(p, "performance") ? "performance" : !strcmp(p, "power-saver") ? "powersave"
+ : strstr(avail, "schedutil") ? "schedutil" : strstr(avail, "ondemand") ? "ondemand" : "powersave";
+ if (!strstr(avail, want)) { failed++; continue; }
+ snprintf(path, sizeof path, "/sys/devices/system/cpu/cpufreq/%s/scaling_governor", e->d_name);
+ char line[32];
+ snprintf(line, sizeof line, "%s\n", want);
+ if (write_file(path, line)) { failed++; continue; }
+ snprintf(path, sizeof path, "/sys/devices/system/cpu/cpufreq/%s/energy_performance_preference", e->d_name);
+ const char *epp = !strcmp(p, "performance") ? "performance\n" : !strcmp(p, "power-saver") ? "power\n" : "balance_performance\n";
+ if (access(path, F_OK) == 0) write_file(path, epp); /* only on intel_pstate/amd-pstate */
+ done++;
+ }
+ closedir(d);
+ if (!done) admin_say("ERR", "no CPU policy accepted the profile");
+ else admin_say("OK", "%s (%d policies%s)", p, done, failed ? ", some refused" : "");
+}
+
+void hw_act_suspend(const AdminReq *r, const char *arg, size_t len) {
+ (void)r; (void)arg; (void)len;
+ const char *const argv[] = { "/usr/bin/systemctl", "suspend", NULL };
+ int code = admin_run(argv);
+ if (code) admin_say("ERR", "systemctl suspend failed (%d)", code);
+ else admin_say("OK", "suspend");
+}
+
+/* ---- power button and lid (logind) ---- */
+
+/* The same short list for the power button and the lid (lid = 1): what logind can do without a
+ * session lock of its own (LordOS locks from the theme). */
+int hw_button_action_valid(const char *a, int lid) {
+ static const char *const ok[] = { "poweroff", "suspend", "hibernate", "ignore", NULL };
+ (void)lid;
+ for (int i = 0; a && ok[i]; i++) if (!strcmp(a, ok[i])) return 1;
+ return 0;
+}
+
+void hw_act_buttons(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ char a[128], power[16], lid[16], lidac[16];
+ if (arg_copy(arg, len, a, sizeof a) || sscanf(a, "%15s %15s %15s", power, lid, lidac) != 3 ||
+ !hw_button_action_valid(power, 0) || !hw_button_action_valid(lid, 1) || !hw_button_action_valid(lidac, 1)) {
+ admin_say("ERR", "invalid argument");
+ return;
+ }
+ mkdir("/etc/systemd/logind.conf.d", 0755);
+ char text[400];
+ snprintf(text, sizeof text,
+ "# Written by LordOS (Settings → Battery). Changes here are overwritten.\n"
+ "[Login]\nHandlePowerKey=%s\nHandleLidSwitch=%s\nHandleLidSwitchExternalPower=%s\n", power, lid, lidac);
+ const char *tmp = "/etc/systemd/logind.conf.d/.lordos.conf.tmp", *dst = "/etc/systemd/logind.conf.d/lordos.conf";
+ int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0644);
+ int ok = fd >= 0 && write(fd, text, strlen(text)) == (ssize_t)strlen(text);
+ if (fd >= 0) { ok = fsync(fd) == 0 && ok; close(fd); }
+ if (!ok || rename(tmp, dst)) { unlink(tmp); admin_say("ERR", "could not write %s", dst); return; }
+ const char *const argv[] = { "/usr/bin/systemctl", "reload", "systemd-logind", NULL };
+ int code = admin_run(argv);
+ if (code) admin_say("ERR", "logind did not reload (%d)", code);
+ else admin_say("OK", "%s %s %s", power, lid, lidac);
+}
+
+/* ---- date and time ---- */
+
+void hw_act_ntp(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ char a[8];
+ if (arg_copy(arg, len, a, sizeof a) || (strcmp(a, "on") && strcmp(a, "off"))) { admin_say("ERR", "invalid argument"); return; }
+ const char *const argv[] = { "/usr/bin/timedatectl", "set-ntp", !strcmp(a, "on") ? "true" : "false", NULL };
+ int code = admin_run(argv);
+ if (code) admin_say("ERR", "timedatectl set-ntp failed (%d)", code);
+ else admin_say("OK", "%s", a);
+}
+
+int hw_time_valid(const char *t) {
+ if (!t || strlen(t) != 19) return 0;
+ for (int i = 0; i < 19; i++) {
+ char c = t[i];
+ int sep = i == 4 || i == 7 ? '-' : i == 10 ? ' ' : i == 13 || i == 16 ? ':' : 0;
+ if (sep ? c != sep : !isdigit((unsigned char)c)) return 0;
+ }
+ int y, mo, d, h, mi, s;
+ if (sscanf(t, "%4d-%2d-%2d %2d:%2d:%2d", &y, &mo, &d, &h, &mi, &s) != 6) return 0;
+ static const int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+ int leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
+ if (y < 2000 || y > 2099 || mo < 1 || mo > 12 || d < 1 || d > days[mo - 1] + (mo == 2 && leap)) return 0;
+ return h <= 23 && mi <= 59 && s <= 59;
+}
+
+void hw_act_time_set(const AdminReq *r, const char *arg, size_t len) {
+ (void)r;
+ char t[32];
+ if (arg_copy(arg, len, t, sizeof t) || !hw_time_valid(t)) { admin_say("ERR", "invalid date and time"); return; }
+ const char *const argv[] = { "/usr/bin/timedatectl", "set-time", t, NULL };
+ int code = admin_run(argv);
+ if (code) admin_say("ERR", "timedatectl set-time failed (%d): turn off automatic time first", code);
+ else admin_say("OK", "%s", t);
+}
+
+/* ---- Bluetooth rfkill ---- */
+
+void hw_act_bt_unblock(const AdminReq *r, const char *arg, size_t len) {
+ (void)r; (void)arg; (void)len;
+ int fd = open("/dev/rfkill", O_WRONLY | O_CLOEXEC);
+ if (fd < 0) { admin_say("ERR", "no /dev/rfkill"); return; }
+ struct rfkill_event ev = { .type = RFKILL_TYPE_BLUETOOTH, .op = RFKILL_OP_CHANGE_ALL, .soft = 0 };
+ ssize_t w = write(fd, &ev, RFKILL_EVENT_SIZE_V1);
+ close(fd);
+ if (w != RFKILL_EVENT_SIZE_V1) admin_say("ERR", "rfkill: %s", strerror(errno));
+ else admin_say("OK", "unblocked");
+}
diff --git a/server/src/hw/hw_admin.h b/server/src/hw/hw_admin.h
new file mode 100644
index 0000000..2e7074e
--- /dev/null
+++ b/server/src/hw/hw_admin.h
@@ -0,0 +1,41 @@
+/* hw_admin.h — the admin helper's actions for Settings (displays, battery, date and time,
+ * Bluetooth). Every action is closed: validated arguments, fixed program paths and config files
+ * generated here, never user text passed to a shell. Listed in AGENTS.md and docs/SETTINGS.md.
+ *
+ * display-brightness <name> <value> /sys/class/backlight/<name>/brightness (0..max) anyone
+ * power-profile <p> performance|balanced|power-saver: powerprofilesctl if
+ * installed, else the cpufreq governor (and EPP) anyone
+ * power-suspend systemctl suspend anyone
+ * power-buttons <power> <lid> <lidac> /etc/systemd/logind.conf.d/lordos.conf + reload logind admin
+ * time-ntp on|off timedatectl set-ntp admin
+ * time-set YYYY-MM-DD HH:MM:SS timedatectl set-time (automatic time must be off) admin
+ * bt-unblock rfkill: unblock Bluetooth (/dev/rfkill) anyone
+ */
+#ifndef LORD_HW_ADMIN_H
+#define LORD_HW_ADMIN_H
+
+#include "../admin.h"
+
+void hw_act_brightness(const AdminReq *r, const char *arg, size_t len);
+void hw_act_power_profile(const AdminReq *r, const char *arg, size_t len);
+void hw_act_suspend(const AdminReq *r, const char *arg, size_t len);
+void hw_act_buttons(const AdminReq *r, const char *arg, size_t len);
+void hw_act_ntp(const AdminReq *r, const char *arg, size_t len);
+void hw_act_time_set(const AdminReq *r, const char *arg, size_t len);
+void hw_act_bt_unblock(const AdminReq *r, const char *arg, size_t len);
+
+/* Validators, exposed for tests. */
+int hw_button_action_valid(const char *a, int lid);
+int hw_time_valid(const char *t); /* "YYYY-MM-DD HH:MM:SS", a real date from 2000 to 2099 */
+int hw_backlight_name_valid(const char *n);
+
+#define HW_ADMIN_ACTIONS \
+ { "display-brightness", hw_act_brightness, A_ANYONE }, \
+ { "power-profile", hw_act_power_profile, A_ANYONE }, \
+ { "power-suspend", hw_act_suspend, A_ANYONE }, \
+ { "power-buttons", hw_act_buttons, 0 }, \
+ { "time-ntp", hw_act_ntp, 0 }, \
+ { "time-set", hw_act_time_set, 0 }, \
+ { "bt-unblock", hw_act_bt_unblock, A_ANYONE },
+
+#endif
diff --git a/server/src/hw/jbuf.c b/server/src/hw/jbuf.c
new file mode 100644
index 0000000..7b087dd
--- /dev/null
+++ b/server/src/hw/jbuf.c
@@ -0,0 +1,48 @@
+/* jbuf.c — growable JSON buffer (see jbuf.h). */
+#include "jbuf.h"
+#include "../sec/json.h"
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int reserve(HBuf *b, size_t more) {
+ if (b->oom) return -1;
+ if (b->n + more + 1 <= b->cap) return 0;
+ size_t cap = b->cap ? b->cap : 256;
+ while (cap < b->n + more + 1) cap *= 2;
+ char *p = realloc(b->p, cap);
+ if (!p) { b->oom = 1; return -1; }
+ b->p = p;
+ b->cap = cap;
+ return 0;
+}
+
+void hb_printf(HBuf *b, const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ int n = vsnprintf(NULL, 0, fmt, ap);
+ va_end(ap);
+ if (n < 0 || reserve(b, (size_t)n)) return;
+ va_start(ap, fmt);
+ vsnprintf(b->p + b->n, b->cap - b->n, fmt, ap);
+ va_end(ap);
+ b->n += (size_t)n;
+}
+
+void hb_str(HBuf *b, const char *s) {
+ size_t worst = strlen(s) * 6 + 12; /* json_quote keeps 8 bytes of slack */
+ if (reserve(b, worst)) return;
+ b->n += json_quote(b->p + b->n, b->cap - b->n, s);
+}
+
+char *hb_take(HBuf *b) {
+ if (b->oom) { free(b->p); b->p = NULL; return NULL; }
+ if (!b->p && reserve(b, 0)) return NULL;
+ b->p[b->n] = 0;
+ char *p = b->p;
+ b->p = NULL;
+ b->n = b->cap = 0;
+ return p;
+}
diff --git a/server/src/hw/jbuf.h b/server/src/hw/jbuf.h
new file mode 100644
index 0000000..94dfc65
--- /dev/null
+++ b/server/src/hw/jbuf.h
@@ -0,0 +1,14 @@
+/* jbuf.h — growable buffer for building JSON in src/hw (strings are escaped with
+ * sec/json.c's json_quote). On out-of-memory the buffer is marked and later writes are dropped. */
+#ifndef LORD_HW_JBUF_H
+#define LORD_HW_JBUF_H
+
+#include <stddef.h>
+
+typedef struct { char *p; size_t n, cap; int oom; } HBuf;
+
+void hb_printf(HBuf *b, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
+void hb_str(HBuf *b, const char *s); /* "escaped" */
+char *hb_take(HBuf *b); /* the string (malloc), or NULL on OOM */
+
+#endif
diff --git a/server/src/hw/mimeapps.c b/server/src/hw/mimeapps.c
new file mode 100644
index 0000000..2535e96
--- /dev/null
+++ b/server/src/hw/mimeapps.c
@@ -0,0 +1,245 @@
+/* mimeapps.c — mimeapps.list and globs2 (see mimeapps.h). */
+#include "mimeapps.h"
+
+#include <ctype.h>
+#include <fnmatch.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int mime_valid(const char *m) {
+ size_t n = m ? strlen(m) : 0;
+ if (n < 3 || n >= MIME_MAX) return 0;
+ const char *slash = strchr(m, '/');
+ if (!slash || slash == m || !slash[1] || strchr(slash + 1, '/')) return 0;
+ for (const char *p = m; *p; p++) {
+ if (p == slash) continue;
+ int first = p == m || p == slash + 1;
+ if (first ? !(islower((unsigned char)*p) || isdigit((unsigned char)*p))
+ : !(isalnum((unsigned char)*p) || strchr(".+_-", *p))) return 0;
+ }
+ return 1;
+}
+
+int desktop_id_valid(const char *id) {
+ size_t n = id ? strlen(id) : 0;
+ if (n < 9 || n >= DESKTOP_ID_MAX || strcmp(id + n - 8, ".desktop")) return 0;
+ if (strstr(id, "..") || id[0] == '.' || id[0] == '-') return 0;
+ for (const char *p = id; *p; p++)
+ if (!(isalnum((unsigned char)*p) || strchr("._-", *p))) return 0;
+ return 1;
+}
+
+/* ---- line scanner ---- */
+
+typedef struct { const char *p, *end; } Line;
+
+static int next_line(const char **cur, Line *l) {
+ if (!*cur || !**cur) return 0;
+ l->p = *cur;
+ const char *e = strchr(*cur, '\n');
+ l->end = e ? e : *cur + strlen(*cur);
+ *cur = e ? e + 1 : l->end;
+ return 1;
+}
+
+static const char *skip_ws(const char *p, const char *end) { while (p < end && (*p == ' ' || *p == '\t')) p++; return p; }
+
+/* Group header "[Name]": 1 and the name range, else 0. */
+static int group_of(const Line *l, const char **name, size_t *len) {
+ const char *p = skip_ws(l->p, l->end), *e = l->end;
+ while (e > p && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r')) e--;
+ if (p >= e || *p != '[' || e[-1] != ']') return 0;
+ *name = p + 1;
+ *len = (size_t)(e - p - 2);
+ return 1;
+}
+
+/* "key = value": 1 if the key is `key`; *val = start of the value (trimmed range). */
+static int key_is(const Line *l, const char *key, const char **val, const char **vend) {
+ const char *p = skip_ws(l->p, l->end);
+ size_t kl = strlen(key);
+ if ((size_t)(l->end - p) < kl || memcmp(p, key, kl)) return 0;
+ p = skip_ws(p + kl, l->end);
+ if (p >= l->end || *p != '=') return 0;
+ p = skip_ws(p + 1, l->end);
+ const char *e = l->end;
+ while (e > p && (e[-1] == ' ' || e[-1] == '\t' || e[-1] == '\r')) e--;
+ *val = p;
+ *vend = e;
+ return 1;
+}
+
+static int in_group(const char *name, size_t len, const char *want) { return strlen(want) == len && !memcmp(name, want, len); }
+
+/* Finds `mime=` in group `grp`; returns 1 with the value range. */
+static int find_value(const char *text, const char *grp, const char *mime, const char **v, const char **ve) {
+ const char *cur = text, *gn;
+ size_t gl;
+ int inside = 0;
+ Line l;
+ while (next_line(&cur, &l)) {
+ if (group_of(&l, &gn, &gl)) { inside = in_group(gn, gl, grp); continue; }
+ if (inside && key_is(&l, mime, v, ve)) return 1;
+ }
+ return 0;
+}
+
+int mimeapps_default(const char *text, const char *mime, char *out, size_t n) {
+ const char *v, *ve;
+ if (!text || !find_value(text, "Default Applications", mime, &v, &ve)) return -1;
+ for (const char *p = v; p < ve;) {
+ const char *s = memchr(p, ';', (size_t)(ve - p));
+ if (!s) s = ve;
+ size_t len = (size_t)(s - p);
+ if (len && len < n) {
+ memcpy(out, p, len);
+ out[len] = 0;
+ if (desktop_id_valid(out)) return 0;
+ }
+ p = s + 1;
+ }
+ return -1;
+}
+
+static int list_has(const char *v, const char *ve, const char *id) {
+ size_t il = strlen(id);
+ for (const char *p = v; p < ve;) {
+ const char *s = memchr(p, ';', (size_t)(ve - p));
+ if (!s) s = ve;
+ if ((size_t)(s - p) == il && !memcmp(p, id, il)) return 1;
+ p = s + 1;
+ }
+ return 0;
+}
+
+int mimeapps_removed(const char *text, const char *mime, const char *id) {
+ const char *v, *ve;
+ return text && find_value(text, "Removed Associations", mime, &v, &ve) && list_has(v, ve, id);
+}
+
+/* ---- editing ---- */
+
+typedef struct { char *p; size_t n, cap; int oom; } Buf;
+
+static void put(Buf *b, const char *s, size_t n) {
+ if (b->oom) return;
+ if (b->n + n + 1 > b->cap) {
+ size_t cap = (b->cap ? b->cap * 2 : 256) + n;
+ char *np = realloc(b->p, cap);
+ if (!np) { b->oom = 1; return; }
+ b->p = np;
+ b->cap = cap;
+ }
+ memcpy(b->p + b->n, s, n);
+ b->n += n;
+ b->p[b->n] = 0;
+}
+static void puts_(Buf *b, const char *s) { put(b, s, strlen(s)); }
+
+static void put_key(Buf *b, const char *mime, const char *id, const char *v, const char *ve, int keep_rest) {
+ puts_(b, mime);
+ puts_(b, "=");
+ puts_(b, id);
+ puts_(b, ";");
+ size_t il = strlen(id);
+ for (const char *p = v; keep_rest && p < ve;) {
+ const char *s = memchr(p, ';', (size_t)(ve - p));
+ if (!s) s = ve;
+ size_t len = (size_t)(s - p);
+ if (len && !(len == il && !memcmp(p, id, len))) { put(b, p, len); puts_(b, ";"); }
+ p = s + 1;
+ }
+ puts_(b, "\n");
+}
+
+static int blank(const Line *l) { const char *p = skip_ws(l->p, l->end); return p >= l->end || *p == '\r'; }
+
+/* Rewrites `text` so that in group grp, mime's list is: id first, then (if keep_rest) the old
+ * entries without id. The key goes at the end of the group (before its trailing blank lines) if
+ * missing, and the group at the end of the file if missing. Other lines are copied unchanged. */
+static char *set_list(const char *text, const char *grp, const char *mime, const char *id, int keep_rest) {
+ Buf b = { 0 };
+ const char *cur = text ? text : "", *gn;
+ size_t gl;
+ int inside = 0, done = 0, held = 0; /* held: blank lines kept back inside the group */
+ Line l;
+ while (next_line(&cur, &l)) {
+ const char *v, *ve;
+ int hdr = group_of(&l, &gn, &gl);
+ if (hdr && inside && !done) { put_key(&b, mime, id, NULL, NULL, 0); done = 1; }
+ if (hdr) inside = in_group(gn, gl, grp);
+ if (!hdr && inside && !done && blank(&l)) { held++; continue; }
+ for (; held; held--) puts_(&b, "\n");
+ if (!hdr && inside && !done && key_is(&l, mime, &v, &ve)) { put_key(&b, mime, id, v, ve, keep_rest); done = 1; continue; }
+ put(&b, l.p, (size_t)(l.end - l.p));
+ puts_(&b, "\n");
+ }
+ if (inside && !done) { put_key(&b, mime, id, NULL, NULL, 0); done = 1; }
+ for (; held; held--) puts_(&b, "\n");
+ if (!done) {
+ if (b.n) puts_(&b, "\n");
+ puts_(&b, "[");
+ puts_(&b, grp);
+ puts_(&b, "]\n");
+ put_key(&b, mime, id, NULL, NULL, 0);
+ }
+ if (b.oom) { free(b.p); return NULL; }
+ return b.p;
+}
+
+char *mimeapps_set_default(const char *text, const char *mime, const char *id) {
+ if (!mime_valid(mime) || !desktop_id_valid(id)) return NULL;
+ char *a = set_list(text, "Default Applications", mime, id, 0);
+ if (!a) return NULL;
+ char *b = set_list(a, "Added Associations", mime, id, 1);
+ free(a);
+ return b;
+}
+
+/* ---- globs2 ---- */
+
+int mime_guess(const char *globs2, const char *name, char *out, size_t n) {
+ if (!globs2 || !name || !*name) return -1;
+ const char *base = strrchr(name, '/');
+ base = base ? base + 1 : name;
+ char lower[256];
+ size_t bl = strlen(base);
+ if (bl >= sizeof lower) return -1;
+ for (size_t i = 0; i <= bl; i++) lower[i] = (char)tolower((unsigned char)base[i]);
+ int best_w = -1;
+ size_t best_len = 0;
+ int best_cs = 0; /* on a tie, a case-sensitive match wins */
+ const char *cur = globs2;
+ Line l;
+ while (next_line(&cur, &l)) {
+ if (l.p == l.end || *l.p == '#') continue;
+ char line[512];
+ size_t ll = (size_t)(l.end - l.p);
+ if (ll >= sizeof line) continue;
+ memcpy(line, l.p, ll);
+ line[ll] = 0;
+ char *f[4] = { line, NULL, NULL, NULL };
+ for (int k = 1; k < 4; k++) { char *c = f[k - 1] ? strchr(f[k - 1], ':') : NULL; if (c) { *c = 0; f[k] = c + 1; } }
+ if (!f[1] || !f[2]) continue;
+ int w = atoi(f[0]);
+ int cs = f[3] && strstr(f[3], "cs");
+ const char *glob = f[2];
+ size_t gl = strlen(glob);
+ if (w < best_w || (w == best_w && (gl < best_len || (gl == best_len && (best_cs || !cs))))) continue;
+ int ok;
+ if (cs) ok = fnmatch(glob, base, 0) == 0;
+ else {
+ char g[256];
+ if (gl >= sizeof g) continue;
+ for (size_t i = 0; i <= gl; i++) g[i] = (char)tolower((unsigned char)glob[i]);
+ ok = fnmatch(g, lower, 0) == 0;
+ }
+ if (!ok || !mime_valid(f[1]) || strlen(f[1]) >= n) continue;
+ snprintf(out, n, "%s", f[1]);
+ best_w = w;
+ best_len = gl;
+ best_cs = cs;
+ }
+ return best_w >= 0 ? 0 : -1;
+}
diff --git a/server/src/hw/mimeapps.h b/server/src/hw/mimeapps.h
new file mode 100644
index 0000000..53978d9
--- /dev/null
+++ b/server/src/hw/mimeapps.h
@@ -0,0 +1,33 @@
+/* mimeapps.h — default applications (freedesktop "MIME Applications Associations" spec):
+ * reading and editing mimeapps.list text and guessing a file's MIME type from shared-mime-info's
+ * globs2. Pure functions over text; the files are read and written by ui/js_hw.c. Used by
+ * Settings → Default Apps, Files' "Open With" and lord.apps.launchWith. See docs/SETTINGS.md.
+ * Unit-tested in tests/mimeapps_test.c. */
+#ifndef LORD_HW_MIMEAPPS_H
+#define LORD_HW_MIMEAPPS_H
+
+#include <stddef.h>
+
+#define MIME_MAX 128
+#define DESKTOP_ID_MAX 160
+
+/* "type/subtype" (also x-scheme-handler/https): [a-z0-9] start, then [A-Za-z0-9.+_-]. */
+int mime_valid(const char *mime);
+/* A desktop file id: "org.gnome.Evince.desktop", "lordos-photos.desktop". No '/', no "..". */
+int desktop_id_valid(const char *id);
+
+/* First application in [Default Applications] for mime (the "mime=a.desktop;b.desktop;" list).
+ * 0 if found (out gets the id). */
+int mimeapps_default(const char *text, const char *mime, char *out, size_t n);
+/* Is id listed in [Removed Associations] for mime? */
+int mimeapps_removed(const char *text, const char *mime, const char *id);
+/* New text with id as the default for mime: the [Default Applications] line is replaced (or
+ * added, creating the group if needed) and id goes first in [Added Associations] (as GLib does).
+ * Every other line is kept byte for byte. Returns a malloc'd string, or NULL. */
+char *mimeapps_set_default(const char *text, const char *mime, const char *id);
+
+/* MIME type of a file name from a globs2 text ("weight:type:glob[:flags]"): highest weight,
+ * then longest pattern; case-insensitive unless the "cs" flag is set. 0 if found. */
+int mime_guess(const char *globs2, const char *name, char *out, size_t n);
+
+#endif
diff --git a/server/src/hw/modes.c b/server/src/hw/modes.c
new file mode 100644
index 0000000..f6e60b2
--- /dev/null
+++ b/server/src/hw/modes.c
@@ -0,0 +1,85 @@
+/* modes.c — KMS mode helpers (see modes.h). */
+#include "modes.h"
+
+#include <stdlib.h>
+
+int mode_refresh_mhz(const struct drm_mode_modeinfo *m) {
+ if (!m->htotal || !m->vtotal || !m->clock) return 0;
+ long long num = (long long)m->clock * 1000000LL; /* kHz → mHz numerator */
+ long long den = (long long)m->htotal * m->vtotal;
+ if (m->flags & DRM_MODE_FLAG_INTERLACE) num *= 2;
+ if (m->flags & DRM_MODE_FLAG_DBLSCAN) den *= 2;
+ if (m->vscan > 1) den *= m->vscan;
+ return (int)((num + den / 2) / den);
+}
+
+static int interlaced(const struct drm_mode_modeinfo *m) { return (m->flags & DRM_MODE_FLAG_INTERLACE) != 0; }
+
+int mode_preferred(const struct drm_mode_modeinfo *modes, int n) {
+ if (n <= 0) return -1;
+ for (int i = 0; i < n; i++) if (modes[i].type & DRM_MODE_TYPE_PREFERRED) return i;
+ int best = 0;
+ for (int i = 1; i < n; i++)
+ if ((long)modes[i].hdisplay * modes[i].vdisplay > (long)modes[best].hdisplay * modes[best].vdisplay) best = i;
+ return best;
+}
+
+int mode_pick(const struct drm_mode_modeinfo *modes, int n, int w, int h, int refresh_mhz) {
+ if (w <= 0 || h <= 0) {
+ int p = mode_preferred(modes, n);
+ if (p < 0) return -1;
+ w = modes[p].hdisplay;
+ h = modes[p].vdisplay;
+ if (refresh_mhz <= 0) return p;
+ }
+ int best = -1;
+ long best_score = 0;
+ for (int i = 0; i < n; i++) {
+ if (modes[i].hdisplay != w || modes[i].vdisplay != h) continue;
+ int r = mode_refresh_mhz(&modes[i]);
+ /* lower is better: interlace penalty, then distance from the wanted rate (or highest) */
+ long score = interlaced(&modes[i]) ? 100000000L : 0;
+ score += refresh_mhz > 0 ? labs((long)r - refresh_mhz) : 10000000L - r;
+ if (modes[i].type & DRM_MODE_TYPE_PREFERRED) score -= 1; /* tie → the preferred one */
+ if (best < 0 || score < best_score) { best = i; best_score = score; }
+ }
+ return best;
+}
+
+int mode_resolutions(const struct drm_mode_modeinfo *modes, int n, int *out, int max) {
+ int k = 0;
+ for (int i = 0; i < n; i++) {
+ if (interlaced(&modes[i])) continue;
+ int j = 0;
+ while (j < k && (modes[out[j]].hdisplay != modes[i].hdisplay || modes[out[j]].vdisplay != modes[i].vdisplay)) j++;
+ if (j < k) {
+ if (mode_refresh_mhz(&modes[i]) > mode_refresh_mhz(&modes[out[j]])) out[j] = i;
+ continue;
+ }
+ if (k < max) out[k++] = i;
+ }
+ /* largest area first (insertion sort: k is small) */
+ for (int a = 1; a < k; a++) {
+ int v = out[a], b = a;
+ long av = (long)modes[v].hdisplay * modes[v].vdisplay;
+ while (b > 0 && (long)modes[out[b - 1]].hdisplay * modes[out[b - 1]].vdisplay < av) { out[b] = out[b - 1]; b--; }
+ out[b] = v;
+ }
+ return k;
+}
+
+int mode_rates(const struct drm_mode_modeinfo *modes, int n, int w, int h, int *out, int max) {
+ int k = 0;
+ for (int i = 0; i < n; i++) {
+ if (modes[i].hdisplay != w || modes[i].vdisplay != h || interlaced(&modes[i])) continue;
+ int r = mode_refresh_mhz(&modes[i]), j = 0;
+ while (j < k && abs(out[j] - r) > 5) j++; /* same rate within 0.005 Hz */
+ if (j == k && k < max) out[k++] = r;
+ }
+ for (int a = 1; a < k; a++) {
+ int v = out[a], b = a;
+ while (b > 0 && out[b - 1] < v) { out[b] = out[b - 1]; b--; }
+ out[b] = v;
+ }
+ return k;
+}
diff --git a/server/src/hw/modes.h b/server/src/hw/modes.h
new file mode 100644
index 0000000..d362216
--- /dev/null
+++ b/server/src/hw/modes.h
@@ -0,0 +1,24 @@
+/* modes.h — KMS mode helpers for Settings → Displays: exact refresh rate, picking a mode by
+ * resolution and refresh, and the list of resolutions a connector offers. Pure functions over
+ * struct drm_mode_modeinfo (kernel uapi), unit-tested in tests/modes_test.c. */
+#ifndef LORD_HW_MODES_H
+#define LORD_HW_MODES_H
+
+#include <stdint.h>
+#include <drm/drm.h>
+#include <drm/drm_mode.h>
+
+/* Refresh in millihertz (59940 = 59.94 Hz), from the pixel clock and totals. 0 if invalid. */
+int mode_refresh_mhz(const struct drm_mode_modeinfo *m);
+/* Index of the best mode: exact w×h (0×0 = the preferred mode), refresh closest to
+ * refresh_mhz (0 = highest), progressive before interlaced. -1 if no mode has that size. */
+int mode_pick(const struct drm_mode_modeinfo *modes, int n, int w, int h, int refresh_mhz);
+/* Index of the preferred mode (DRM_MODE_TYPE_PREFERRED), or the largest one. -1 if n == 0. */
+int mode_preferred(const struct drm_mode_modeinfo *modes, int n);
+/* Distinct resolutions, largest area first: out[i] = index of the highest-refresh mode of
+ * that size. Returns how many (≤ max). */
+int mode_resolutions(const struct drm_mode_modeinfo *modes, int n, int *out, int max);
+/* Distinct refresh rates (mHz, highest first) offered for w×h. Returns how many (≤ max). */
+int mode_rates(const struct drm_mode_modeinfo *modes, int n, int w, int h, int *out, int max);
+
+#endif
diff --git a/server/src/hw/night.c b/server/src/hw/night.c
new file mode 100644
index 0000000..3f9bc50
--- /dev/null
+++ b/server/src/hw/night.c
@@ -0,0 +1,144 @@
+/* night.c — Night Shift math (see night.h). */
+#include "night.h"
+
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#define PI 3.14159265358979323846
+
+/* Tanner Helland's fit of the blackbody curve (sRGB 0..255), good to a few percent between
+ * 1000 K and 40000 K; only its ratios are used here. */
+static void helland(double kelvin, double *r, double *g, double *b) {
+ double t = kelvin / 100.0;
+ *r = t <= 66 ? 255 : 329.698727446 * pow(t - 60, -0.1332047592);
+ *g = t <= 66 ? 99.4708025861 * log(t) - 161.1195681661 : 288.1221695283 * pow(t - 60, -0.0755148492);
+ *b = t >= 66 ? 255 : t <= 19 ? 0 : 138.5177312231 * log(t - 10) - 305.0447927307;
+}
+
+static double clamp01(double v) { return v < 0 ? 0 : v > 1 ? 1 : v; }
+
+void night_temp_rgb(int kelvin, double *r, double *g, double *b) {
+ if (kelvin < 1000) kelvin = 1000;
+ if (kelvin > 10000) kelvin = 10000;
+ double r0, g0, b0, r1, g1, b1;
+ helland(NIGHT_K_MAX, &r0, &g0, &b0);
+ helland(kelvin, &r1, &g1, &b1);
+ *r = clamp01(r1 / r0);
+ *g = clamp01(g1 / g0);
+ *b = clamp01(b1 / b0);
+ if (kelvin == NIGHT_K_MAX) *r = *g = *b = 1;
+}
+
+void night_ramp(int n, double r, double g, double b, double bright, uint16_t *red, uint16_t *green, uint16_t *blue) {
+ bright = clamp01(bright);
+ for (int i = 0; i < n; i++) {
+ double v = n > 1 ? (double)i / (n - 1) : 1;
+ red[i] = (uint16_t)(clamp01(v * r * bright) * 65535 + 0.5);
+ green[i] = (uint16_t)(clamp01(v * g * bright) * 65535 + 0.5);
+ blue[i] = (uint16_t)(clamp01(v * b * bright) * 65535 + 0.5);
+ }
+}
+
+static int day_of_year(int y, int m, int d) {
+ static const int cum[12] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
+ int leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
+ return cum[(m - 1) % 12] + d + (leap && m > 2);
+}
+
+static double fmod360(double v) { v = fmod(v, 360); return v < 0 ? v + 360 : v; }
+static double rad(double d) { return d * PI / 180; }
+static double deg(double r) { return r * 180 / PI; }
+
+/* "Almanac for Computers" (US Naval Observatory, 1990) sunrise algorithm, official zenith
+ * 90°50'. Accurate to about two minutes away from the poles. */
+static int sun_event(int n, double lat, double lon, int rising, double *ut_min) {
+ double lng_hour = lon / 15;
+ double t = n + ((rising ? 6 : 18) - lng_hour) / 24;
+ double m = 0.9856 * t - 3.289;
+ double l = fmod360(m + 1.916 * sin(rad(m)) + 0.020 * sin(rad(2 * m)) + 282.634);
+ double ra = fmod360(deg(atan(0.91764 * tan(rad(l)))));
+ ra += floor(l / 90) * 90 - floor(ra / 90) * 90;
+ ra /= 15;
+ double sin_dec = 0.39782 * sin(rad(l));
+ double cos_dec = cos(asin(sin_dec));
+ double cos_h = (cos(rad(90.833)) - sin_dec * sin(rad(lat))) / (cos_dec * cos(rad(lat)));
+ if (cos_h > 1 || cos_h < -1) return -1;
+ double h = rising ? 360 - deg(acos(cos_h)) : deg(acos(cos_h));
+ h /= 15;
+ double local = h + ra - 0.06571 * t - 6.622;
+ double ut = fmod(local - lng_hour, 24);
+ if (ut < 0) ut += 24;
+ *ut_min = ut * 60;
+ return 0;
+}
+
+int night_sun_times(int y, int m, int d, double lat, double lon, double *rise_utc, double *set_utc) {
+ int n = day_of_year(y, m, d);
+ if (sun_event(n, lat, lon, 1, rise_utc) || sun_event(n, lat, lon, 0, set_utc)) return -1;
+ return 0;
+}
+
+double night_amount(int now, int from, int to, int fade) {
+ int len = ((to - from) % 1440 + 1440) % 1440;
+ if (!len) return 0;
+ int d = ((now - from) % 1440 + 1440) % 1440;
+ if (d >= len) return 0;
+ if (fade <= 0) return 1;
+ double a = (double)d / fade, b = (double)(len - d) / fade;
+ return clamp01(a < b ? a : b);
+}
+
+/* ±DDMM[SS] (lat) or ±DDDMM[SS] (lon): deg_digits = 2 or 3 */
+static int coord(const char *s, int len, int deg_digits, double *out) {
+ if (len != 1 + deg_digits + 2 && len != 1 + deg_digits + 4) return -1;
+ if (s[0] != '+' && s[0] != '-') return -1;
+ int v[7] = { 0 };
+ for (int i = 1; i < len; i++) { if (s[i] < '0' || s[i] > '9') return -1; v[i] = s[i] - '0'; }
+ int dg = 0;
+ for (int i = 1; i <= deg_digits; i++) dg = dg * 10 + v[i];
+ int mn = v[deg_digits + 1] * 10 + v[deg_digits + 2];
+ int sc = len > 1 + deg_digits + 2 ? v[deg_digits + 3] * 10 + v[deg_digits + 4] : 0;
+ if (mn > 59 || sc > 59) return -1;
+ double r = dg + mn / 60.0 + sc / 3600.0;
+ *out = s[0] == '-' ? -r : r;
+ return 0;
+}
+
+int night_parse_coords(const char *s, double *lat, double *lon) {
+ size_t n = strlen(s);
+ size_t split = 1;
+ while (split < n && s[split] != '+' && s[split] != '-') split++;
+ if (split >= n) return -1;
+ if (coord(s, (int)split, 2, lat) || coord(s + split, (int)(n - split), 3, lon)) return -1;
+ if (*lat < -90 || *lat > 90 || *lon < -180 || *lon > 180) return -1;
+ return 0;
+}
+
+int night_zone_coords(const char *tab, const char *zone, double *lat, double *lon) {
+ size_t zl = strlen(zone);
+ if (!zl) return -1;
+ for (const char *line = tab; line && *line;) {
+ const char *end = strchr(line, '\n');
+ size_t ll = end ? (size_t)(end - line) : strlen(line);
+ if (ll && line[0] != '#') {
+ /* codes \t coordinates \t TZ [\t comments] */
+ const char *t1 = memchr(line, '\t', ll);
+ const char *t2 = t1 ? memchr(t1 + 1, '\t', (size_t)(line + ll - t1 - 1)) : NULL;
+ if (t2) {
+ const char *z = t2 + 1, *ze = memchr(z, '\t', (size_t)(line + ll - z));
+ if (!ze) ze = line + ll;
+ if ((size_t)(ze - z) == zl && !memcmp(z, zone, zl)) {
+ char c[24];
+ size_t cl = (size_t)(t2 - t1 - 1);
+ if (cl >= sizeof c) return -1;
+ memcpy(c, t1 + 1, cl);
+ c[cl] = 0;
+ return night_parse_coords(c, lat, lon);
+ }
+ }
+ }
+ line = end ? end + 1 : NULL;
+ }
+ return -1;
+}
diff --git a/server/src/hw/night.h b/server/src/hw/night.h
new file mode 100644
index 0000000..c63a59e
--- /dev/null
+++ b/server/src/hw/night.h
@@ -0,0 +1,33 @@
+/* night.h — Night Shift math for Settings → Displays: color temperature → RGB gains, the gamma
+ * ramp (KMS gamma LUT, or the software LUT when the card has none), sunrise/sunset and the
+ * schedule blend. No location services: the coordinates come from the chosen time zone
+ * (zone1970.tab), never from the network. Unit-tested in tests/night_test.c. */
+#ifndef LORD_HW_NIGHT_H
+#define LORD_HW_NIGHT_H
+
+#include <stdint.h>
+
+#define NIGHT_K_MIN 1900
+#define NIGHT_K_MAX 6500 /* neutral: gains (1, 1, 1) */
+
+/* White point of a blackbody at kelvin, normalized so 6500 K is (1, 1, 1). Clamped to
+ * [1000, 10000] K. Gains are in [0, 1]. */
+void night_temp_rgb(int kelvin, double *r, double *g, double *b);
+/* Gamma ramp of n entries per channel (0..65535) for these gains and brightness (0..1). */
+void night_ramp(int n, double r, double g, double b, double bright, uint16_t *red, uint16_t *green, uint16_t *blue);
+
+/* Sunrise and sunset for a date (y, m 1-12, d) at lat/lon (degrees, east positive), in
+ * minutes after midnight UTC (may be < 0 or ≥ 1440). Returns 0, or -1 for polar day/night. */
+int night_sun_times(int y, int m, int d, double lat, double lon, double *rise_utc, double *set_utc);
+
+/* How much of the night tint applies at minute `now` of the local day (0..1439) for a night
+ * that starts at `from` and ends at `to` (local minutes; may cross midnight), fading over
+ * `fade` minutes on each side. 0 = day, 1 = full night. */
+double night_amount(int now, int from, int to, int fade);
+
+/* ISO 6709 coordinates as in zone1970.tab ("+4230+00131" or "+404251-0740023"). 0 if valid. */
+int night_parse_coords(const char *s, double *lat, double *lon);
+/* Looks up a zone ("America/Argentina/Buenos_Aires") in a zone1970.tab text. 0 if found. */
+int night_zone_coords(const char *tab, const char *zone, double *lat, double *lon);
+
+#endif
diff --git a/server/src/hw/notifyd.c b/server/src/hw/notifyd.c
new file mode 100644
index 0000000..757d68e
--- /dev/null
+++ b/server/src/hw/notifyd.c
@@ -0,0 +1,219 @@
+/* notifyd.c — org.freedesktop.Notifications server (see notifyd.h). */
+#include "notifyd.h"
+#include "jbuf.h"
+#include "../vault/dbus.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define BUS_NAME "org.freedesktop.Notifications"
+#define OBJ "/org/freedesktop/Notifications"
+
+static DConn conn = { .fd = -1 };
+static int up;
+static uint32_t next_id = 1;
+static NotifydEvent emit;
+
+int notifyd_fd(void) { return up ? conn.fd : -1; }
+int notifyd_wants_write(void) { return up && dbus_pending_out(&conn); }
+
+void notifyd_plain(const char *in, char *out, size_t n) {
+ size_t o = 0;
+ if (!n) return;
+ for (const char *p = in; *p && o + 1 < n;) {
+ if (*p == '<') { /* a tag: dropped (a <br> becomes a newline) */
+ const char *e = strchr(p, '>');
+ if (!e) break;
+ if (!strncmp(p, "<br", 3) && o + 1 < n) out[o++] = '\n';
+ p = e + 1;
+ continue;
+ }
+ if (*p == '&') {
+ static const struct { const char *ent; char c; } ents[] = { { "&amp;", '&' }, { "&lt;", '<' }, { "&gt;", '>' }, { "&quot;", '"' }, { "&apos;", '\'' } };
+ int done = 0;
+ for (size_t i = 0; i < sizeof ents / sizeof ents[0]; i++)
+ if (!strncmp(p, ents[i].ent, strlen(ents[i].ent))) { out[o++] = ents[i].c; p += strlen(ents[i].ent); done = 1; break; }
+ if (done) continue;
+ }
+ out[o++] = *p++;
+ }
+ out[o] = 0;
+}
+
+static void reply_caps(const DMsg *m) {
+ DBuf b;
+ dw_init(&b);
+ size_t a = dw_arr_begin(&b, 4);
+ dw_str(&b, "body");
+ dw_str(&b, "body-markup");
+ dw_str(&b, "actions");
+ dw_arr_end(&b, a);
+ dbus_reply(&conn, m, "as", &b);
+ dw_free(&b);
+}
+
+static void reply_info(const DMsg *m) {
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, "LordOS");
+ dw_str(&b, "LordOS");
+ dw_str(&b, "0.7");
+ dw_str(&b, "1.2");
+ dbus_reply(&conn, m, "ssss", &b);
+ dw_free(&b);
+}
+
+static void on_notify(const DMsg *m) {
+ DRd r;
+ dr_init(&r, m);
+ const char *app = dr_str(&r, NULL);
+ uint32_t replaces = dr_u32(&r);
+ const char *icon = dr_str(&r, NULL), *summary = dr_str(&r, NULL), *body = dr_str(&r, NULL);
+ (void)icon;
+ HBuf j = { 0 };
+ char plain[2048];
+ hb_printf(&j, "{\"actions\":[");
+ size_t end = dr_arr(&r, 4);
+ int na = 0;
+ while (!r.err && dr_more(&r, end)) {
+ const char *key = dr_str(&r, NULL);
+ const char *label = dr_more(&r, end) ? dr_str(&r, NULL) : NULL;
+ if (r.err || !key || !label || na >= 3) continue;
+ notifyd_plain(label, plain, 96);
+ hb_printf(&j, "%s[", na++ ? "," : "");
+ hb_str(&j, key);
+ hb_printf(&j, ",");
+ hb_str(&j, plain);
+ hb_printf(&j, "]");
+ }
+ char desktop[160] = "";
+ int urgency = 1;
+ end = dr_arr(&r, 8);
+ while (!r.err && dr_more(&r, end)) {
+ dr_struct(&r);
+ const char *k = dr_str(&r, NULL), *sig = dr_variant(&r);
+ if (r.err || !k || !sig) break;
+ if (!strcmp(k, "desktop-entry") && !strcmp(sig, "s")) { const char *v = dr_str(&r, NULL); snprintf(desktop, sizeof desktop, "%s", v ? v : ""); }
+ else if (!strcmp(k, "urgency") && !strcmp(sig, "y")) urgency = dr_u8(&r);
+ else dr_skip(&r, sig);
+ }
+ int32_t timeout = dr_i32(&r);
+ if (r.err || !app || !summary || !body) {
+ free(hb_take(&j));
+ dbus_error(&conn, m, "org.freedesktop.DBus.Error.InvalidArgs", "Notify(susssasa{sv}i)");
+ return;
+ }
+ uint32_t id = replaces ? replaces : next_id++;
+ if (!next_id) next_id = 1;
+ hb_printf(&j, "],\"id\":%u,\"replaces\":%s,\"urgency\":%d,\"timeout\":%d,\"app\":", id, replaces ? "true" : "false", urgency, timeout);
+ notifyd_plain(app, plain, 128);
+ hb_str(&j, plain);
+ hb_printf(&j, ",\"desktop\":");
+ hb_str(&j, desktop);
+ hb_printf(&j, ",\"title\":");
+ notifyd_plain(summary, plain, 256);
+ hb_str(&j, plain);
+ hb_printf(&j, ",\"body\":");
+ notifyd_plain(body, plain, sizeof plain);
+ hb_str(&j, plain);
+ hb_printf(&j, "}");
+ DBuf b;
+ dw_init(&b);
+ dw_u32(&b, id);
+ dbus_reply(&conn, m, "u", &b);
+ dw_free(&b);
+ char *js = hb_take(&j);
+ if (js && emit) emit("notify", js);
+ free(js);
+}
+
+static void handle(const DMsg *m) {
+ if (m->type != DBUS_CALL || !m->member) return;
+ if (m->iface && !strcmp(m->iface, "org.freedesktop.DBus.Introspectable")) {
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, "<node><interface name=\"org.freedesktop.Notifications\">"
+ "<method name=\"Notify\"/><method name=\"CloseNotification\"/><method name=\"GetCapabilities\"/>"
+ "<method name=\"GetServerInformation\"/><signal name=\"NotificationClosed\"/><signal name=\"ActionInvoked\"/>"
+ "</interface></node>");
+ dbus_reply(&conn, m, "s", &b);
+ dw_free(&b);
+ return;
+ }
+ if (!m->path || strcmp(m->path, OBJ) || (m->iface && strcmp(m->iface, BUS_NAME))) {
+ dbus_error(&conn, m, "org.freedesktop.DBus.Error.UnknownObject", "no such object");
+ return;
+ }
+ const char *sig = m->sig ? m->sig : "";
+ if (!strcmp(m->member, "GetCapabilities")) reply_caps(m);
+ else if (!strcmp(m->member, "GetServerInformation")) reply_info(m);
+ else if (!strcmp(m->member, "Notify") && !strcmp(sig, "susssasa{sv}i")) on_notify(m);
+ else if (!strcmp(m->member, "CloseNotification") && !strcmp(sig, "u")) {
+ DRd r;
+ dr_init(&r, m);
+ uint32_t id = dr_u32(&r);
+ dbus_reply(&conn, m, NULL, NULL);
+ char j[48];
+ snprintf(j, sizeof j, "{\"id\":%u}", id);
+ if (emit) emit("notify-close", j);
+ notifyd_closed(id, 3);
+ } else dbus_error(&conn, m, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method");
+}
+
+int notifyd_start(NotifydEvent fn) {
+ emit = fn;
+ int fd = dbus_connect_session();
+ if (fd < 0 || dbus_open(&conn, fd, 2000)) { if (fd >= 0) dbus_close(&conn); return -1; }
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, BUS_NAME);
+ dw_u32(&b, 4); /* DBUS_NAME_FLAG_DO_NOT_QUEUE */
+ DHdr h = { .type = DBUS_CALL, .path = "/org/freedesktop/DBus", .iface = "org.freedesktop.DBus", .member = "RequestName",
+ .dest = "org.freedesktop.DBus", .sig = "su" };
+ uint32_t s = dbus_send(&conn, &h, &b);
+ dw_free(&b);
+ DMsg m;
+ int ok = s && dbus_wait_reply(&conn, s, &m, 2000) == 1;
+ uint32_t res = 0;
+ if (ok) { DRd r; dr_init(&r, &m); res = dr_u32(&r); }
+ if (s) dbus_msg_free(&m);
+ if (!ok || (res != 1 && res != 4)) {
+ fprintf(stderr, "notifyd: another program already serves %s\n", BUS_NAME);
+ dbus_close(&conn);
+ return -1;
+ }
+ up = 1;
+ return 0;
+}
+
+void notifyd_dispatch(void) {
+ if (!up) return;
+ DMsg m;
+ int r;
+ while ((r = dbus_next(&conn, &m)) == 1) { handle(&m); dbus_msg_free(&m); }
+ if (r < 0 || dbus_flush(&conn) < 0) { fprintf(stderr, "notifyd: lost the session bus\n"); dbus_close(&conn); up = 0; }
+}
+
+void notifyd_closed(uint32_t id, uint32_t reason) {
+ if (!up || !id) return;
+ if (reason < 1 || reason > 4) reason = 4;
+ DBuf b;
+ dw_init(&b);
+ dw_u32(&b, id);
+ dw_u32(&b, reason);
+ dbus_signal(&conn, OBJ, BUS_NAME, "NotificationClosed", "uu", &b);
+ dw_free(&b);
+ dbus_flush(&conn);
+}
+
+void notifyd_action(uint32_t id, const char *key) {
+ if (!up || !id || !key || strlen(key) > 128) return;
+ DBuf b;
+ dw_init(&b);
+ dw_u32(&b, id);
+ dw_str(&b, key);
+ dbus_signal(&conn, OBJ, BUS_NAME, "ActionInvoked", "us", &b);
+ dw_free(&b);
+ notifyd_closed(id, 2);
+}
diff --git a/server/src/hw/notifyd.h b/server/src/hw/notifyd.h
new file mode 100644
index 0000000..de7b119
--- /dev/null
+++ b/server/src/hw/notifyd.h
@@ -0,0 +1,26 @@
+/* notifyd.h — org.freedesktop.Notifications on the session bus, so notifications from Linux apps
+ * (GTK, Qt, Electron, notify-send) appear as LordOS banners and follow Settings → Notifications
+ * (per-app style, sound, Do Not Disturb). The banner is drawn by the theme (sdk/notify.js); this
+ * only translates the protocol (spec 1.2): Notify, CloseNotification, GetCapabilities,
+ * GetServerInformation, and the NotificationClosed / ActionInvoked signals. Body markup is reduced
+ * to plain text. Uses our own D-Bus client (vault/dbus.c). */
+#ifndef LORD_HW_NOTIFYD_H
+#define LORD_HW_NOTIFYD_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+typedef void (*NotifydEvent)(const char *kind, const char *json); /* "notify", "notify-close" */
+
+int notifyd_start(NotifydEvent fn); /* 0 if we own the name */
+int notifyd_fd(void);
+int notifyd_wants_write(void);
+void notifyd_dispatch(void);
+/* From the theme: the banner went away (reason: 1 expired, 2 dismissed, 3 closed by a call) or
+ * an action was clicked. */
+void notifyd_closed(uint32_t id, uint32_t reason);
+void notifyd_action(uint32_t id, const char *key);
+/* Strips markup (<b>, <i>, <a href>, <img>...) and decodes &amp; &lt; &gt; &quot; &apos;. */
+void notifyd_plain(const char *in, char *out, size_t n);
+
+#endif
diff --git a/server/src/hw/power.c b/server/src/hw/power.c
new file mode 100644
index 0000000..ac13600
--- /dev/null
+++ b/server/src/hw/power.c
@@ -0,0 +1,156 @@
+/* power.c — /sys/class/power_supply reader (see power.h). */
+#include "power.h"
+#include "../sec/json.h"
+
+#include <dirent.h>
+#include <stdarg.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+/* One attribute file, trimmed. 0 if read. */
+static int attr(const char *root, const char *dev, const char *name, char *out, size_t n) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s/%s", root, dev, name);
+ int fd = open(p, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return -1;
+ ssize_t r = read(fd, out, n - 1);
+ close(fd);
+ if (r < 0) return -1;
+ out[r] = 0;
+ while (r > 0 && (out[r - 1] == '\n' || out[r - 1] == ' ')) out[--r] = 0;
+ return 0;
+}
+
+static long long num(const char *root, const char *dev, const char *name) {
+ char b[32];
+ if (attr(root, dev, name, b, sizeof b) || !b[0]) return -1;
+ char *e;
+ long long v = strtoll(b, &e, 10);
+ return *e ? -1 : v;
+}
+
+static void read_one(const char *root, const char *dev, PowerSupply *s) {
+ char type[32] = "", scope[32] = "";
+ memset(s, 0, sizeof *s);
+ snprintf(s->name, sizeof s->name, "%s", dev);
+ attr(root, dev, "type", type, sizeof type);
+ attr(root, dev, "scope", scope, sizeof scope);
+ s->battery = !strcmp(type, "Battery");
+ s->device_scope = !strcmp(scope, "Device");
+ long long online = num(root, dev, "online"), present = num(root, dev, "present");
+ s->online = online > 0;
+ s->present = present != 0; /* missing file = present */
+ s->percent = -1;
+ s->minutes_left = s->health = s->cycles = -1;
+ s->watts = -1;
+ if (!s->battery) return;
+ if (attr(root, dev, "status", s->status, sizeof s->status)) snprintf(s->status, sizeof s->status, "Unknown");
+ attr(root, dev, "model_name", s->model, sizeof s->model);
+ attr(root, dev, "manufacturer", s->vendor, sizeof s->vendor);
+ attr(root, dev, "technology", s->technology, sizeof s->technology);
+ long long cap = num(root, dev, "capacity");
+ /* energy_* in µWh with power_now in µW, or charge_* in µAh with current_now in µA */
+ long long now = num(root, dev, "energy_now"), full = num(root, dev, "energy_full"), design = num(root, dev, "energy_full_design");
+ long long rate = num(root, dev, "power_now");
+ if (now < 0) {
+ now = num(root, dev, "charge_now");
+ full = num(root, dev, "charge_full");
+ design = num(root, dev, "charge_full_design");
+ rate = num(root, dev, "current_now");
+ long long uv = num(root, dev, "voltage_now");
+ if (rate >= 0 && uv > 0) s->watts = (double)rate * (double)uv / 1e12;
+ } else if (rate >= 0) s->watts = (double)rate / 1e6;
+ if (cap >= 0 && cap <= 100) s->percent = (int)cap;
+ else if (now >= 0 && full > 0) s->percent = (int)(now * 100 / full);
+ if (s->percent > 100) s->percent = 100;
+ if (full > 0 && design > 0) s->health = (int)(full * 100 / design);
+ if (s->health > 100) s->health = 100;
+ s->cycles = (int)num(root, dev, "cycle_count");
+ if (s->cycles == 0) s->cycles = -1; /* many firmwares report 0 for "unknown" */
+ long long tte = num(root, dev, "time_to_empty_now"), ttf = num(root, dev, "time_to_full_now");
+ if (!strcmp(s->status, "Discharging")) {
+ if (tte > 0) s->minutes_left = (int)(tte / 60);
+ else if (rate > 0 && now >= 0) s->minutes_left = (int)(now * 60 / rate);
+ } else if (!strcmp(s->status, "Charging")) {
+ if (ttf > 0) s->minutes_left = (int)(ttf / 60);
+ else if (rate > 0 && full > now && now >= 0) s->minutes_left = (int)((full - now) * 60 / rate);
+ }
+}
+
+static int by_name(const void *a, const void *b) { return strcmp(((const PowerSupply *)a)->name, ((const PowerSupply *)b)->name); }
+
+int power_read(const char *root, PowerState *ps) {
+ memset(ps, 0, sizeof *ps);
+ ps->percent = ps->minutes_left = -1;
+ DIR *d = opendir(root);
+ if (d) {
+ struct dirent *e;
+ while ((e = readdir(d)) && ps->n < POWER_MAX) {
+ if (e->d_name[0] == '.' || strlen(e->d_name) >= sizeof ps->s[0].name) continue;
+ read_one(root, e->d_name, &ps->s[ps->n]);
+ ps->n++;
+ }
+ closedir(d);
+ }
+ qsort(ps->s, (size_t)ps->n, sizeof ps->s[0], by_name);
+ long long sum = 0, cnt = 0, mins = 0, have_mins = 0;
+ int any_charger = 0;
+ for (int i = 0; i < ps->n; i++) {
+ const PowerSupply *s = &ps->s[i];
+ if (!s->battery) { any_charger = 1; if (s->online) ps->on_ac = 1; continue; }
+ if (s->device_scope || !s->present) continue;
+ ps->has_battery = 1;
+ if (s->percent >= 0) { sum += s->percent; cnt++; }
+ if (s->minutes_left >= 0) { mins += s->minutes_left; have_mins = 1; }
+ if (!strcmp(s->status, "Charging")) ps->charging = 1;
+ }
+ if (!ps->has_battery) ps->on_ac = 1;
+ else if (!any_charger) ps->on_ac = ps->charging;
+ if (cnt) ps->percent = (int)(sum / cnt);
+ if (have_mins) ps->minutes_left = (int)mins;
+ return ps->n;
+}
+
+typedef struct { char *p; size_t n, cap; } Out;
+static void w(Out *o, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
+static void w(Out *o, const char *fmt, ...) {
+ if (o->n + 1 >= o->cap) return;
+ va_list ap;
+ va_start(ap, fmt);
+ int r = vsnprintf(o->p + o->n, o->cap - o->n, fmt, ap);
+ va_end(ap);
+ if (r > 0) o->n += (size_t)r < o->cap - o->n ? (size_t)r : o->cap - o->n - 1;
+}
+static void wq(Out *o, const char *s) {
+ if (o->n + 1 >= o->cap) return;
+ o->n += json_quote(o->p + o->n, o->cap - o->n, s);
+ if (o->n >= o->cap) o->n = o->cap - 1;
+}
+
+size_t power_json(const PowerState *ps, char *out, size_t n) {
+ Out o = { out, 0, n };
+ if (!n) return 0;
+ out[0] = 0;
+ w(&o, "{\"onAC\":%s,\"hasBattery\":%s,\"percent\":%d,\"minutesLeft\":%d,\"charging\":%s,\"supplies\":[",
+ ps->on_ac ? "true" : "false", ps->has_battery ? "true" : "false", ps->percent, ps->minutes_left, ps->charging ? "true" : "false");
+ for (int i = 0; i < ps->n; i++) {
+ const PowerSupply *s = &ps->s[i];
+ w(&o, "%s{\"name\":", i ? "," : "");
+ wq(&o, s->name);
+ w(&o, ",\"battery\":%s,\"device\":%s,\"online\":%s,\"present\":%s,\"percent\":%d,\"status\":",
+ s->battery ? "true" : "false", s->device_scope ? "true" : "false", s->online ? "true" : "false", s->present ? "true" : "false", s->percent);
+ wq(&o, s->status);
+ w(&o, ",\"minutesLeft\":%d,\"health\":%d,\"cycles\":%d,\"watts\":%.2f,\"model\":", s->minutes_left, s->health, s->cycles, s->watts);
+ wq(&o, s->model);
+ w(&o, ",\"vendor\":");
+ wq(&o, s->vendor);
+ w(&o, ",\"technology\":");
+ wq(&o, s->technology);
+ w(&o, "}");
+ }
+ w(&o, "]}");
+ return o.n;
+}
diff --git a/server/src/hw/power.h b/server/src/hw/power.h
new file mode 100644
index 0000000..cfc6a43
--- /dev/null
+++ b/server/src/hw/power.h
@@ -0,0 +1,43 @@
+/* power.h — batteries and chargers from /sys/class/power_supply (Settings → Battery, the menu
+ * bar percentage and the low-battery notice). Read-only and unprivileged; refreshed on
+ * power_supply uevents (hw/uevent.c), never polled. The root directory is a parameter so
+ * tests/power_test.c can use a fake sysfs tree. */
+#ifndef LORD_HW_POWER_H
+#define LORD_HW_POWER_H
+
+#include <stddef.h>
+
+#define POWER_MAX 8
+
+typedef struct {
+ char name[32]; /* "BAT0", "AC", "hidpp_battery_0" */
+ int battery; /* type Battery (else a charger: Mains, USB...) */
+ int device_scope; /* scope Device: a mouse or keyboard battery, not the system's */
+ int online; /* chargers: plugged in */
+ int present;
+ int percent; /* 0..100, -1 unknown */
+ char status[16]; /* Charging, Discharging, Full, Not charging, Unknown */
+ int minutes_left; /* to empty (discharging) or to full (charging); -1 unknown */
+ int health; /* full / design capacity, percent; -1 unknown */
+ int cycles; /* -1 unknown */
+ double watts; /* current draw, -1 unknown */
+ char model[48], vendor[48], technology[16];
+} PowerSupply;
+
+typedef struct {
+ PowerSupply s[POWER_MAX];
+ int n;
+ int on_ac; /* any charger online (or no system battery) */
+ int has_battery; /* a system battery (scope != Device) */
+ int percent; /* system batteries combined, -1 without one */
+ int minutes_left; /* combined, -1 unknown */
+ int charging;
+} PowerState;
+
+/* Reads every supply under root ("/sys/class/power_supply"). Returns ps->n. */
+int power_read(const char *root, PowerState *ps);
+/* JSON for lord.power.state(). Returns bytes written (truncated output is still valid JSON
+ * only if n is large enough; 4 KB always is). */
+size_t power_json(const PowerState *ps, char *out, size_t n);
+
+#endif
diff --git a/server/src/hw/ppd.c b/server/src/hw/ppd.c
new file mode 100644
index 0000000..55e8ca7
--- /dev/null
+++ b/server/src/hw/ppd.c
@@ -0,0 +1,150 @@
+/* ppd.c — power profiles (see ppd.h). */
+#include "ppd.h"
+#include "jbuf.h"
+#include "sysbus.h"
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static const char *const names[2] = { "org.freedesktop.UPower.PowerProfiles", "net.hadess.PowerProfiles" };
+static const char *const paths[2] = { "/org/freedesktop/UPower/PowerProfiles", "/net/hadess/PowerProfiles" };
+static PpdEvent emit;
+static int which = -1; /* index in names of the daemon on the bus */
+static char active[24], degraded[48];
+static char profiles[3][24];
+static int nprofiles;
+
+int ppd_profile_valid(const char *p) { return p && (!strcmp(p, "performance") || !strcmp(p, "balanced") || !strcmp(p, "power-saver")); }
+
+static void changed(void) {
+ char *j = ppd_state_json();
+ if (j && emit) emit("ppd", j);
+ free(j);
+}
+
+static void read_props(DRd *r) {
+ size_t end = dr_arr(r, 8);
+ while (!r->err && dr_more(r, end)) {
+ dr_struct(r);
+ const char *k = dr_str(r, NULL), *sig = dr_variant(r);
+ if (r->err || !k || !sig) break;
+ if (!strcmp(k, "ActiveProfile") && !strcmp(sig, "s")) { const char *v = dr_str(r, NULL); if (v && ppd_profile_valid(v)) snprintf(active, sizeof active, "%s", v); }
+ else if (!strcmp(k, "PerformanceDegraded") && !strcmp(sig, "s")) { const char *v = dr_str(r, NULL); snprintf(degraded, sizeof degraded, "%s", v ? v : ""); }
+ else if (!strcmp(k, "Profiles") && !strcmp(sig, "aa{sv}")) {
+ nprofiles = 0;
+ size_t e1 = dr_arr(r, 4); /* elements are arrays: 4-aligned */
+ while (!r->err && dr_more(r, e1)) {
+ size_t e2 = dr_arr(r, 8);
+ while (!r->err && dr_more(r, e2)) {
+ dr_struct(r);
+ const char *pk = dr_str(r, NULL), *ps = dr_variant(r);
+ if (r->err || !pk || !ps) break;
+ if (!strcmp(pk, "Profile") && !strcmp(ps, "s")) {
+ const char *v = dr_str(r, NULL);
+ if (v && ppd_profile_valid(v) && nprofiles < 3) snprintf(profiles[nprofiles++], sizeof profiles[0], "%s", v);
+ } else dr_skip(r, ps);
+ }
+ }
+ } else dr_skip(r, sig);
+ }
+}
+
+static void got_all(const DMsg *m, void *ctx) {
+ (void)ctx;
+ if (m && m->type == DBUS_RETURN && m->sig && !strcmp(m->sig, "a{sv}")) {
+ DRd r;
+ dr_init(&r, m);
+ read_props(&r);
+ }
+ changed();
+}
+
+static void get_all(void) {
+ if (which < 0) return;
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, names[which]);
+ sysbus_call(names[which], paths[which], "org.freedesktop.DBus.Properties", "GetAll", "s", &b, got_all, NULL);
+ dw_free(&b);
+}
+
+static void on_owner(const char *name, const char *owner) {
+ int i = !strcmp(name, names[0]) ? 0 : 1;
+ if (owner && owner[0]) { if (which < 0 || i < which) which = i; get_all(); return; }
+ if (which == i) { which = -1; nprofiles = 0; active[0] = degraded[0] = 0; changed(); }
+}
+
+static void on_signal(const DMsg *m) {
+ if (which < 0 || !m->member || strcmp(m->member, "PropertiesChanged") || !m->path || strcmp(m->path, paths[which])) return;
+ get_all();
+}
+
+void ppd_start(PpdEvent fn) {
+ emit = fn;
+ if (!sysbus_up()) return;
+ sysbus_on_signal(on_signal);
+ for (int i = 0; i < 2; i++) {
+ char rule[200];
+ snprintf(rule, sizeof rule, "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path='%s'", paths[i]);
+ sysbus_add_match(rule);
+ sysbus_watch_name(names[i], on_owner);
+ }
+}
+
+static void governor(char *out, size_t n) {
+ out[0] = 0;
+ int fd = open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", O_RDONLY | O_CLOEXEC);
+ if (fd < 0) return;
+ ssize_t r = read(fd, out, n - 1);
+ close(fd);
+ if (r > 0) { out[r] = 0; out[strcspn(out, "\n")] = 0; } else out[0] = 0;
+}
+
+char *ppd_state_json(void) {
+ char gov[32];
+ governor(gov, sizeof gov);
+ HBuf b = { 0 };
+ hb_printf(&b, "{\"daemon\":%s,\"active\":", which >= 0 ? "true" : "false");
+ const char *act = active;
+ if (which < 0) act = !strcmp(gov, "performance") ? "performance" : !strcmp(gov, "powersave") ? "power-saver" : gov[0] ? "balanced" : "";
+ hb_str(&b, act);
+ hb_printf(&b, ",\"degraded\":");
+ hb_str(&b, degraded);
+ hb_printf(&b, ",\"governor\":");
+ hb_str(&b, gov);
+ hb_printf(&b, ",\"profiles\":[");
+ if (which >= 0) {
+ for (int i = 0; i < nprofiles; i++) { if (i) hb_printf(&b, ","); hb_str(&b, profiles[i]); }
+ } else if (gov[0]) hb_printf(&b, "\"power-saver\",\"balanced\",\"performance\"");
+ hb_printf(&b, "]}");
+ return hb_take(&b);
+}
+
+static void set_done(const DMsg *m, void *ctx) {
+ (void)ctx;
+ HBuf b = { 0 };
+ int ok = m && m->type == DBUS_RETURN;
+ hb_printf(&b, "{\"ok\":%s,\"error\":", ok ? "true" : "false");
+ hb_str(&b, ok ? "" : m ? (m->error ? m->error : "error") : "disconnected");
+ hb_printf(&b, "}");
+ char *j = hb_take(&b);
+ if (j && emit) emit("ppd-result", j);
+ free(j);
+ if (ok) get_all();
+}
+
+int ppd_set(const char *p) {
+ if (!ppd_profile_valid(p) || which < 0) return -1;
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, names[which]);
+ dw_str(&b, "ActiveProfile");
+ dw_variant(&b, "s");
+ dw_str(&b, p);
+ uint32_t s = sysbus_call(names[which], paths[which], "org.freedesktop.DBus.Properties", "Set", "ssv", &b, set_done, NULL);
+ dw_free(&b);
+ return s ? 0 : -1;
+}
diff --git a/server/src/hw/ppd.h b/server/src/hw/ppd.h
new file mode 100644
index 0000000..7c217b4
--- /dev/null
+++ b/server/src/hw/ppd.h
@@ -0,0 +1,17 @@
+/* ppd.h — power profiles for Settings → Battery: power-profiles-daemon over the system bus when
+ * it runs (org.freedesktop.UPower.PowerProfiles, or the older net.hadess.PowerProfiles), else
+ * the cpufreq governor read from sysfs. Changing it as the user goes through the daemon (its
+ * polkit policy allows active sessions); if that is refused the theme falls back to the closed
+ * admin action power-profile (hw/hw_admin.c). */
+#ifndef LORD_HW_PPD_H
+#define LORD_HW_PPD_H
+
+typedef void (*PpdEvent)(const char *kind, const char *json);
+
+void ppd_start(PpdEvent fn); /* after sysbus_start (works without it: sysfs only) */
+char *ppd_state_json(void); /* {daemon, active, profiles:[...], degraded, governor} */
+/* "performance", "balanced" or "power-saver". The result comes as "ppd-result" {ok, error}. */
+int ppd_set(const char *profile);
+int ppd_profile_valid(const char *p);
+
+#endif
diff --git a/server/src/hw/sysbus.c b/server/src/hw/sysbus.c
new file mode 100644
index 0000000..0e54582
--- /dev/null
+++ b/server/src/hw/sysbus.c
@@ -0,0 +1,151 @@
+/* sysbus.c — system bus connection for Settings (see sysbus.h). */
+#include "sysbus.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define MAX_PENDING 64
+#define MAX_HANDLERS 4
+#define MAX_WATCH 4
+
+typedef struct { uint32_t serial; SbReply cb; void *ctx; } Pending;
+typedef struct { char name[64]; SbOwner fn; } Watch;
+
+static DConn conn = { .fd = -1 };
+static int up;
+static Pending pending[MAX_PENDING];
+static SbSignal signals[MAX_HANDLERS];
+static SbCall calls[MAX_HANDLERS];
+static Watch watches[MAX_WATCH];
+static int nsig, ncall, nwatch;
+
+int sysbus_up(void) { return up; }
+int sysbus_fd(void) { return up ? conn.fd : -1; }
+int sysbus_wants_write(void) { return up && dbus_pending_out(&conn); }
+DConn *sysbus_conn(void) { return &conn; }
+
+int16_t sb_i16(DRd *r) {
+ r->pos = (r->pos + 1) & ~(size_t)1;
+ if (r->err || r->pos + 2 > r->len) { r->err = 1; return 0; }
+ const uint8_t *p = r->b + r->pos;
+ r->pos += 2;
+ return (int16_t)(r->be ? (p[0] << 8 | p[1]) : (p[1] << 8 | p[0]));
+}
+uint16_t sb_u16(DRd *r) { return (uint16_t)sb_i16(r); }
+
+uint32_t sysbus_call(const char *dest, const char *path, const char *iface, const char *member,
+ const char *sig, const DBuf *body, SbReply cb, void *ctx) {
+ if (!up) return 0;
+ int slot = -1;
+ if (cb) {
+ for (int i = 0; i < MAX_PENDING && slot < 0; i++) if (!pending[i].serial) slot = i;
+ if (slot < 0) return 0;
+ }
+ DHdr h = { .type = DBUS_CALL, .flags = cb ? 0 : DBUS_NO_REPLY, .path = path, .iface = iface, .member = member,
+ .dest = dest, .sig = sig && *sig ? sig : NULL };
+ uint32_t s = dbus_send(&conn, &h, body);
+ if (s && cb) pending[slot] = (Pending){ s, cb, ctx };
+ return s;
+}
+
+void sysbus_add_match(const char *rule) {
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, rule);
+ sysbus_call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "AddMatch", "s", &b, NULL, NULL);
+ dw_free(&b);
+}
+
+void sysbus_on_signal(SbSignal fn) { if (nsig < MAX_HANDLERS) signals[nsig++] = fn; }
+void sysbus_on_call(SbCall fn) { if (ncall < MAX_HANDLERS) calls[ncall++] = fn; }
+
+static void got_owner(const DMsg *m, void *ctx) {
+ Watch *w = ctx;
+ const char *owner = "";
+ if (m && m->type == DBUS_RETURN && m->sig && !strcmp(m->sig, "s")) {
+ DRd r;
+ dr_init(&r, m);
+ const char *o = dr_str(&r, NULL);
+ if (!r.err && o) owner = o;
+ }
+ w->fn(w->name, owner);
+}
+
+static void ask_owner(Watch *w) {
+ DBuf b;
+ dw_init(&b);
+ dw_str(&b, w->name);
+ sysbus_call("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner", "s", &b, got_owner, w);
+ dw_free(&b);
+}
+
+void sysbus_watch_name(const char *name, SbOwner fn) {
+ if (nwatch >= MAX_WATCH || strlen(name) >= sizeof watches[0].name) return;
+ Watch *w = &watches[nwatch++];
+ snprintf(w->name, sizeof w->name, "%s", name);
+ w->fn = fn;
+ char rule[160];
+ snprintf(rule, sizeof rule, "type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='%s'", name);
+ sysbus_add_match(rule);
+ ask_owner(w);
+}
+
+int sysbus_start(void) {
+ if (up) return 0;
+ int fd = dbus_connect_system();
+ if (fd < 0 || dbus_open(&conn, fd, 2000)) {
+ if (fd >= 0) dbus_close(&conn);
+ fprintf(stderr, "sysbus: no system bus (Bluetooth and power profiles unavailable)\n");
+ return -1;
+ }
+ up = 1;
+ return 0;
+}
+
+static void lost(void) {
+ up = 0;
+ dbus_close(&conn);
+ for (int i = 0; i < MAX_PENDING; i++)
+ if (pending[i].serial) { Pending p = pending[i]; pending[i].serial = 0; p.cb(NULL, p.ctx); }
+ for (int i = 0; i < nwatch; i++) watches[i].fn(watches[i].name, "");
+ fprintf(stderr, "sysbus: the system bus connection was lost\n");
+}
+
+static void handle(DMsg *m) {
+ if (m->type == DBUS_RETURN || m->type == DBUS_ERROR) {
+ for (int i = 0; i < MAX_PENDING; i++)
+ if (pending[i].serial && pending[i].serial == m->reply_serial) {
+ Pending p = pending[i];
+ pending[i].serial = 0;
+ p.cb(m, p.ctx);
+ return;
+ }
+ return;
+ }
+ if (m->type == DBUS_SIGNAL) {
+ if (m->member && !strcmp(m->member, "NameOwnerChanged") && m->sender && !strcmp(m->sender, "org.freedesktop.DBus") &&
+ m->sig && !strcmp(m->sig, "sss")) {
+ DRd r;
+ dr_init(&r, m);
+ const char *name = dr_str(&r, NULL), *old = dr_str(&r, NULL), *now = dr_str(&r, NULL);
+ (void)old;
+ for (int i = 0; !r.err && i < nwatch; i++) if (!strcmp(watches[i].name, name)) watches[i].fn(name, now);
+ return;
+ }
+ for (int i = 0; i < nsig; i++) signals[i](m);
+ return;
+ }
+ if (m->type == DBUS_CALL) {
+ for (int i = 0; i < ncall; i++) if (calls[i](m)) return;
+ if (!(m->flags & DBUS_NO_REPLY)) dbus_error(&conn, m, "org.freedesktop.DBus.Error.UnknownMethod", "unknown method");
+ }
+}
+
+void sysbus_dispatch(void) {
+ if (!up) return;
+ DMsg m;
+ int r;
+ while ((r = dbus_next(&conn, &m)) == 1) { handle(&m); dbus_msg_free(&m); }
+ if (r < 0 || dbus_flush(&conn) < 0) lost();
+}
diff --git a/server/src/hw/sysbus.h b/server/src/hw/sysbus.h
new file mode 100644
index 0000000..4af3165
--- /dev/null
+++ b/server/src/hw/sysbus.h
@@ -0,0 +1,40 @@
+/* sysbus.h — one connection to the D-Bus system bus for Settings (BlueZ in hw/bt.c,
+ * power-profiles-daemon in hw/ppd.c), with our own D-Bus client (vault/dbus.c). Asynchronous:
+ * replies go to callbacks by serial, signals and incoming method calls to the registered
+ * handlers. Its fd is in the main loop's poll; nothing is polled. Only Hello blocks (at start). */
+#ifndef LORD_HW_SYSBUS_H
+#define LORD_HW_SYSBUS_H
+
+#include <stdint.h>
+#include "../vault/dbus.h"
+
+/* m is the reply (DBUS_RETURN or DBUS_ERROR) or NULL if the bus went away. */
+typedef void (*SbReply)(const DMsg *m, void *ctx);
+typedef void (*SbSignal)(const DMsg *m);
+/* An incoming method call: 1 if handled (the handler may keep *m: set m->raw = NULL to own it). */
+typedef int (*SbCall)(DMsg *m);
+/* A well-known name appeared (owner != "") or went away (owner == ""). */
+typedef void (*SbOwner)(const char *name, const char *owner);
+
+int sysbus_start(void); /* 0 if connected */
+int sysbus_up(void);
+int sysbus_fd(void);
+int sysbus_wants_write(void);
+void sysbus_dispatch(void);
+DConn *sysbus_conn(void);
+
+/* Method call; cb may be NULL (no reply wanted). Returns the serial or 0. */
+uint32_t sysbus_call(const char *dest, const char *path, const char *iface, const char *member,
+ const char *sig, const DBuf *body, SbReply cb, void *ctx);
+void sysbus_add_match(const char *rule);
+void sysbus_on_signal(SbSignal fn);
+void sysbus_on_call(SbCall fn);
+/* Watch a well-known name: fn is called with its current owner (GetNameOwner) and on every
+ * NameOwnerChanged. */
+void sysbus_watch_name(const char *name, SbOwner fn);
+
+/* Reading helpers over a validated body. */
+int16_t sb_i16(DRd *r);
+uint16_t sb_u16(DRd *r);
+
+#endif
diff --git a/server/src/hw/uevent.c b/server/src/hw/uevent.c
new file mode 100644
index 0000000..aea0e36
--- /dev/null
+++ b/server/src/hw/uevent.c
@@ -0,0 +1,54 @@
+/* uevent.c — kernel uevents (see uevent.h). */
+#include "uevent.h"
+
+#include <errno.h>
+#include <linux/netlink.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+static int fd = -1;
+
+int uevent_open(void) {
+ if (fd >= 0) return 0;
+ fd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, NETLINK_KOBJECT_UEVENT);
+ if (fd < 0) return -1;
+ struct sockaddr_nl a = { .nl_family = AF_NETLINK, .nl_groups = 1 }; /* group 1: the kernel's */
+ if (bind(fd, (struct sockaddr *)&a, sizeof a)) { close(fd); fd = -1; return -1; }
+ return 0;
+}
+
+int uevent_fd(void) { return fd; }
+
+int uevent_parse(const char *buf, int len) {
+ if (len <= 0 || !memchr(buf, '@', (size_t)len)) return 0; /* udev's own (libudev) messages have no '@' header */
+ for (int off = 0; off < len;) {
+ const char *s = buf + off;
+ size_t n = strnlen(s, (size_t)(len - off));
+ if (n > 10 && !strncmp(s, "SUBSYSTEM=", 10)) {
+ const char *v = s + 10;
+ if (!strcmp(v, "drm")) return UEV_DRM;
+ if (!strcmp(v, "power_supply")) return UEV_POWER;
+ if (!strcmp(v, "backlight")) return UEV_BACKLIGHT;
+ return 0;
+ }
+ off += (int)n + 1;
+ }
+ return 0;
+}
+
+int uevent_dispatch(void) {
+ int mask = 0;
+ char buf[8192];
+ for (;;) {
+ struct sockaddr_nl from;
+ struct iovec iov = { buf, sizeof buf - 1 };
+ struct msghdr m = { .msg_name = &from, .msg_namelen = sizeof from, .msg_iov = &iov, .msg_iovlen = 1 };
+ ssize_t r = recvmsg(fd, &m, 0);
+ if (r < 0) { if (errno == EINTR) continue; break; }
+ if (from.nl_pid != 0) continue; /* only the kernel */
+ buf[r] = 0;
+ mask |= uevent_parse(buf, (int)r);
+ }
+ return mask;
+}
diff --git a/server/src/hw/uevent.h b/server/src/hw/uevent.h
new file mode 100644
index 0000000..4dad4a7
--- /dev/null
+++ b/server/src/hw/uevent.h
@@ -0,0 +1,16 @@
+/* uevent.h — kernel uevents (NETLINK_KOBJECT_UEVENT) for Settings: DRM connector changes
+ * (hotplugged displays), power_supply (battery, charger) and backlight. One socket in the main
+ * loop's poll: nothing is polled. Receiving kernel uevents needs no privileges. */
+#ifndef LORD_HW_UEVENT_H
+#define LORD_HW_UEVENT_H
+
+enum { UEV_DRM = 1, UEV_POWER = 2, UEV_BACKLIGHT = 4 };
+
+int uevent_open(void); /* 0 or -1 */
+int uevent_fd(void); /* -1 if closed */
+/* Reads every pending uevent; returns a mask of UEV_* subsystems that changed. */
+int uevent_dispatch(void);
+/* Parses one uevent datagram ("ACTION@devpath\0KEY=VAL\0..."): its UEV_* subsystem, or 0. */
+int uevent_parse(const char *buf, int len);
+
+#endif
diff --git a/server/src/install/install.c b/server/src/install/install.c
index eaab26b..f405132 100644
--- a/server/src/install/install.c
+++ b/server/src/install/install.c
@@ -611,6 +611,7 @@ void install_act_run(const AdminReq *r, const char *arg, size_t len) {
/* administrador de impresoras de CUPS (grupo lpadmin, docs/IMPRESION.md); si CUPS no vino en
* la imagen, el grupo no existe y no pasa nada */
{ const char *const a[] = { "/usr/sbin/usermod", "--append", "--groups", "lpadmin", pl.user, NULL }; if (in_target(a)) { /* sin CUPS */ } }
+ { const char *const a[] = { "/usr/sbin/usermod", "--append", "--groups", "plugdev", pl.user, NULL }; if (in_target(a)) { /* no plugdev group */ } } /* FIDO2 keys (docs/PASSWORDS.md) */
char *salt = crypt_gensalt_ra("$y$", 0, NULL, 0);
struct crypt_data cd;
memset(&cd, 0, sizeof cd);
@@ -655,8 +656,8 @@ void install_act_run(const AdminReq *r, const char *arg, size_t len) {
if (chown(p, uid, gid)) admin_say("LOG", "aviso: no se pudo cambiar el dueño");
snprintf(p, sizeof p, TARGET "/home/%s/.config/locale.conf", pl.user);
writef(p, 0644, "LANG=%s\n", pl.locale); if (chown(p, uid, gid)) admin_say("LOG", "aviso: no se pudo cambiar el dueño"); }
- /* Escritorio, Documentos, Descargas… en el idioma elegido y ~/.config/user-dirs.dirs (la misma
- * lista que Ajustes → Usuarios y el live: users/homedirs.c) */
+ /* Escritorio, Documentos, Descargas… in the chosen language and ~/.config/user-dirs.dirs (the
+ * same list as Settings → Users and the live system: users/homedirs.c) */
{ char p[PATH_MAX]; snprintf(p, sizeof p, TARGET "/home/%s", pl.user);
if (homedirs_create(p, uid, gid, pl.locale)) admin_say("LOG", "aviso: no se pudieron crear las carpetas del usuario"); }
progress("configure", ++step, steps);
diff --git a/server/src/kms.c b/server/src/kms.c
index 1cd5365..11e5b8c 100644
--- a/server/src/kms.c
+++ b/server/src/kms.c
@@ -47,65 +47,142 @@ static void destroy_buffer(Kms *k, KmsBuffer *b) {
memset(b, 0, sizeof *b);
}
-/* Busca un conector enchufado, su modo preferido y un CRTC compatible. */
-static int pick_output(Kms *k) {
+/* ---- outputs (connectors), shared by the initial pick and Settings → Displays ---- */
+
+static KmsPicker picker;
+void kms_set_picker(KmsPicker fn) { picker = fn; }
+
+const char *kms_connector_type_name(uint32_t t) {
+ static const char *const names[] = { "Unknown", "VGA", "DVI-I", "DVI-D", "DVI-A", "Composite", "SVIDEO", "LVDS",
+ "Component", "DIN", "DP", "HDMI-A", "HDMI-B", "TV", "eDP", "Virtual", "DSI", "DPI", "Writeback", "SPI", "USB" };
+ return t < sizeof names / sizeof names[0] ? names[t] : "Unknown";
+}
+
+/* Reads the EDID blob of a connector (property "EDID"). */
+static void read_edid(int fd, uint32_t conn, KmsOutput *o) {
+ uint64_t blob = 0;
+ if (kms_obj_prop(fd, conn, DRM_MODE_OBJECT_CONNECTOR, "EDID", &blob, NULL) || !blob) return;
+ struct drm_mode_get_blob gb = { .blob_id = (uint32_t)blob };
+ if (xioctl(fd, DRM_IOCTL_MODE_GETPROPBLOB, &gb) || gb.length < 128 || gb.length > 32768) return;
+ uint8_t *d = malloc(gb.length);
+ if (!d) return;
+ gb.data = (uintptr_t)d;
+ if (xioctl(fd, DRM_IOCTL_MODE_GETPROPBLOB, &gb)) { free(d); return; }
+ o->edid = d;
+ o->edid_len = gb.length;
+}
+
+int kms_outputs(int fd, KmsOutput *out, int max) {
struct drm_mode_card_res res = {0};
- if (xioctl(k->fd, DRM_IOCTL_MODE_GETRESOURCES, &res)) { perror("GETRESOURCES"); return -1; }
- uint32_t *conns = calloc(res.count_connectors + 1, 4);
- uint32_t *crtcs = calloc(res.count_crtcs + 1, 4);
- uint32_t *encs = calloc(res.count_encoders + 1, 4);
- uint32_t *fbs = calloc(res.count_fbs + 1, 4);
+ if (xioctl(fd, DRM_IOCTL_MODE_GETRESOURCES, &res)) return 0;
+ uint32_t *conns = calloc(res.count_connectors + 1, 4), *crtcs = calloc(res.count_crtcs + 1, 4);
+ uint32_t *encs = calloc(res.count_encoders + 1, 4), *fbs = calloc(res.count_fbs + 1, 4);
+ int n = 0;
+ if (!conns || !crtcs || !encs || !fbs) goto out;
res.connector_id_ptr = (uintptr_t)conns;
res.crtc_id_ptr = (uintptr_t)crtcs;
res.encoder_id_ptr = (uintptr_t)encs;
res.fb_id_ptr = (uintptr_t)fbs;
- int ret = -1;
- if (xioctl(k->fd, DRM_IOCTL_MODE_GETRESOURCES, &res)) { perror("GETRESOURCES"); goto out; }
-
- for (uint32_t i = 0; i < res.count_connectors && ret; i++) {
+ if (xioctl(fd, DRM_IOCTL_MODE_GETRESOURCES, &res)) goto out;
+ for (uint32_t i = 0; i < res.count_connectors && n < max; i++) {
struct drm_mode_get_connector c = { .connector_id = conns[i] };
- if (xioctl(k->fd, DRM_IOCTL_MODE_GETCONNECTOR, &c)) continue;
- if (c.connection != 1 || c.count_modes == 0) continue;
-
- struct drm_mode_modeinfo *modes = calloc(c.count_modes, sizeof *modes);
- uint32_t *cencs = calloc(c.count_encoders + 1, 4);
+ if (xioctl(fd, DRM_IOCTL_MODE_GETCONNECTOR, &c)) continue;
+ KmsOutput *o = &out[n];
+ memset(o, 0, sizeof *o);
+ uint32_t nm = c.count_modes, ne = c.count_encoders;
+ struct drm_mode_modeinfo *modes = nm ? calloc(nm, sizeof *modes) : NULL;
+ uint32_t *cencs = calloc(ne + 1, 4);
c.modes_ptr = (uintptr_t)modes;
c.encoders_ptr = (uintptr_t)cencs;
c.count_props = 0; c.props_ptr = 0; c.prop_values_ptr = 0;
- if (xioctl(k->fd, DRM_IOCTL_MODE_GETCONNECTOR, &c) || c.count_modes == 0) {
- free(modes); free(cencs); continue;
- }
-
- struct drm_mode_modeinfo *mode = &modes[0];
- for (uint32_t m = 0; m < c.count_modes; m++)
- if (modes[m].type & DRM_MODE_TYPE_PREFERRED) { mode = &modes[m]; break; }
-
- uint32_t crtc = 0;
+ if ((nm && !modes) || !cencs || xioctl(fd, DRM_IOCTL_MODE_GETCONNECTOR, &c)) { free(modes); free(cencs); continue; }
+ if (c.count_modes < nm) nm = c.count_modes; /* the list can shrink between the two calls */
+ if (c.count_encoders < ne) ne = c.count_encoders;
+ o->id = c.connector_id;
+ o->type = c.connector_type;
+ o->type_id = c.connector_type_id;
+ o->connected = c.connection == 1;
+ o->mm_w = c.mm_width;
+ o->mm_h = c.mm_height;
+ o->modes = modes;
+ o->nmodes = (int)nm;
+ o->current_crtc = 0;
if (c.encoder_id) {
struct drm_mode_get_encoder e = { .encoder_id = c.encoder_id };
- if (!xioctl(k->fd, DRM_IOCTL_MODE_GETENCODER, &e)) crtc = e.crtc_id;
+ if (!xioctl(fd, DRM_IOCTL_MODE_GETENCODER, &e)) o->current_crtc = e.crtc_id;
}
- for (uint32_t e_i = 0; !crtc && e_i < c.count_encoders; e_i++) {
+ for (uint32_t e_i = 0; e_i < ne; e_i++) {
struct drm_mode_get_encoder e = { .encoder_id = cencs[e_i] };
- if (xioctl(k->fd, DRM_IOCTL_MODE_GETENCODER, &e)) continue;
- for (uint32_t j = 0; j < res.count_crtcs; j++)
- if (e.possible_crtcs & (1u << j)) { crtc = crtcs[j]; break; }
+ if (xioctl(fd, DRM_IOCTL_MODE_GETENCODER, &e)) continue;
+ for (uint32_t j = 0; j < res.count_crtcs && j < 32; j++)
+ if (e.possible_crtcs & (1u << j)) o->possible_crtcs |= 1u << j;
}
- if (crtc) {
- k->conn_id = c.connector_id;
- k->crtc_id = crtc;
- k->crtc_index = 0;
- for (uint32_t j = 0; j < res.count_crtcs; j++) if (crtcs[j] == crtc) { k->crtc_index = (int)j; break; }
- k->mode = *mode;
- k->width = mode->hdisplay;
- k->height = mode->vdisplay;
- ret = 0;
- }
- free(modes); free(cencs);
+ free(cencs);
+ if (o->connected) read_edid(fd, o->id, o);
+ n++;
}
- if (ret) fprintf(stderr, "kms: no hay monitor conectado\n");
out:
free(conns); free(crtcs); free(encs); free(fbs);
+ return n;
+}
+
+void kms_outputs_free(KmsOutput *o, int n) {
+ for (int i = 0; i < n; i++) { free(o[i].modes); free(o[i].edid); o[i].modes = NULL; o[i].edid = NULL; }
+}
+
+/* CRTC id (and index) able to drive `conn`: the one it already has, else `prefer` if possible,
+ * else the first free in possible_crtcs. 0 if none. */
+static uint32_t crtc_for(int fd, const KmsOutput *o, uint32_t prefer, int *index) {
+ struct drm_mode_card_res res = {0};
+ if (xioctl(fd, DRM_IOCTL_MODE_GETRESOURCES, &res) || !res.count_crtcs) return 0;
+ uint32_t *crtcs = calloc(res.count_crtcs, 4);
+ if (!crtcs) return 0;
+ struct drm_mode_card_res r2 = { .crtc_id_ptr = (uintptr_t)crtcs, .count_crtcs = res.count_crtcs };
+ uint32_t got = 0;
+ if (!xioctl(fd, DRM_IOCTL_MODE_GETRESOURCES, &r2)) {
+ uint32_t n = r2.count_crtcs < res.count_crtcs ? r2.count_crtcs : res.count_crtcs;
+ uint32_t want[3] = { o->current_crtc, prefer, 0 };
+ for (int w = 0; w < 2 && !got; w++)
+ for (uint32_t j = 0; j < n && j < 32 && want[w]; j++)
+ if (crtcs[j] == want[w] && (o->possible_crtcs >> j & 1)) { got = crtcs[j]; *index = (int)j; }
+ for (uint32_t j = 0; j < n && j < 32 && !got; j++)
+ if (o->possible_crtcs >> j & 1) { got = crtcs[j]; *index = (int)j; }
+ }
+ free(crtcs);
+ return got;
+}
+
+/* Picks a connected connector and its mode (Settings' choice through the picker, else the first
+ * connected one with its preferred mode) and a CRTC that can drive it. */
+static int pick_output(Kms *k) {
+ KmsOutput outs[KMS_MAX_OUTPUTS];
+ int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), sel = -1, ret = -1;
+ struct drm_mode_modeinfo mode;
+ if (picker && picker(outs, n, &sel, &mode) == 0 && sel >= 0 && sel < n && outs[sel].connected) {
+ /* the picker's choice */
+ } else {
+ sel = -1;
+ for (int i = 0; i < n && sel < 0; i++) {
+ if (!outs[i].connected || !outs[i].nmodes) continue;
+ sel = i;
+ mode = outs[i].modes[0];
+ for (int m = 0; m < outs[i].nmodes; m++)
+ if (outs[i].modes[m].type & DRM_MODE_TYPE_PREFERRED) { mode = outs[i].modes[m]; break; }
+ }
+ }
+ int idx = 0;
+ uint32_t crtc = sel >= 0 ? crtc_for(k->fd, &outs[sel], 0, &idx) : 0;
+ if (crtc) {
+ k->conn_id = outs[sel].id;
+ k->crtc_id = crtc;
+ k->crtc_index = idx;
+ k->mode = mode;
+ k->width = mode.hdisplay;
+ k->height = mode.vdisplay;
+ ret = 0;
+ }
+ kms_outputs_free(outs, n);
+ if (ret) fprintf(stderr, "kms: no hay monitor conectado\n");
return ret;
}
@@ -113,8 +190,8 @@ out:
#define PLANE_TYPE_PRIMARY 1 /* enum drm_plane_type del kernel (no está en la uapi) */
-/* Valor de la propiedad `name` de un objeto KMS. 0 si la encontró. */
-static int obj_prop(int fd, uint32_t obj, uint32_t type, const char *name, uint64_t *val) {
+/* Value (and property id) of property `name` of a KMS object. 0 if found. */
+int kms_obj_prop(int fd, uint32_t obj, uint32_t type, const char *name, uint64_t *val, uint32_t *prop_id) {
struct drm_mode_obj_get_properties op = { .obj_id = obj, .obj_type = type };
if (xioctl(fd, DRM_IOCTL_MODE_OBJ_GETPROPERTIES, &op) || !op.count_props) return -1;
uint32_t ids[64], n = op.count_props > 64 ? 64 : op.count_props;
@@ -128,10 +205,11 @@ static int obj_prop(int fd, uint32_t obj, uint32_t type, const char *name, uint6
struct drm_mode_get_property pr = { .prop_id = ids[i] };
if (xioctl(fd, DRM_IOCTL_MODE_GETPROPERTY, &pr)) continue;
pr.name[DRM_PROP_NAME_LEN - 1] = 0;
- if (!strcmp(pr.name, name)) { *val = vals[i]; return 0; }
+ if (!strcmp(pr.name, name)) { *val = vals[i]; if (prop_id) *prop_id = ids[i]; return 0; }
}
return -1;
}
+static int obj_prop(int fd, uint32_t obj, uint32_t type, const char *name, uint64_t *val) { return kms_obj_prop(fd, obj, type, name, val, NULL); }
static int rgb32(uint32_t f) {
return f == DRM_FORMAT_XRGB8888 || f == DRM_FORMAT_ARGB8888 || f == DRM_FORMAT_XBGR8888 || f == DRM_FORMAT_ABGR8888;
@@ -421,3 +499,73 @@ void kms_cursor_show(Kms *k, int visible) {
xioctl(k->fd, DRM_IOCTL_MODE_CURSOR2, &c);
k->cursor_visible = visible;
}
+
+/* ---- Settings → Displays: change the mode at runtime, gamma, DPMS ---- */
+
+int kms_modeset(Kms *k, uint32_t conn_id, const struct drm_mode_modeinfo *mode) {
+ if (k->fd < 0 || k->flip_pending) return -1;
+ KmsOutput outs[KMS_MAX_OUTPUTS];
+ int n = kms_outputs(k->fd, outs, KMS_MAX_OUTPUTS), sel = -1;
+ for (int i = 0; i < n; i++) if (outs[i].id == conn_id && outs[i].connected) sel = i;
+ int idx = k->crtc_index;
+ uint32_t crtc = sel >= 0 ? crtc_for(k->fd, &outs[sel], k->crtc_id, &idx) : 0;
+ kms_outputs_free(outs, n);
+ if (!crtc) return -1;
+ Kms old = *k;
+ destroy_buffer(k, &k->buf[0]);
+ destroy_buffer(k, &k->buf[1]);
+ k->conn_id = conn_id;
+ k->crtc_id = crtc;
+ k->crtc_index = idx;
+ k->mode = *mode;
+ k->width = mode->hdisplay;
+ k->height = mode->vdisplay;
+ k->custom = 0;
+ k->front = 0;
+ int ok = create_buffer(k, &k->buf[0]) == 0 && create_buffer(k, &k->buf[1]) == 0;
+ if (ok && crtc != old.crtc_id) { /* the old CRTC stops scanning out */
+ struct drm_mode_crtc off = { .crtc_id = old.crtc_id };
+ xioctl(k->fd, DRM_IOCTL_MODE_SETCRTC, &off);
+ }
+ if (ok) {
+ struct drm_mode_crtc set = { .crtc_id = k->crtc_id, .fb_id = k->buf[0].fb_id,
+ .set_connectors_ptr = (uintptr_t)&k->conn_id, .count_connectors = 1, .mode = k->mode, .mode_valid = 1 };
+ ok = xioctl(k->fd, DRM_IOCTL_MODE_SETCRTC, &set) == 0;
+ if (!ok) perror("kms: SETCRTC (new mode)");
+ }
+ if (!ok) { /* back to the previous mode */
+ destroy_buffer(k, &k->buf[0]);
+ destroy_buffer(k, &k->buf[1]);
+ k->conn_id = old.conn_id; k->crtc_id = old.crtc_id; k->crtc_index = old.crtc_index;
+ k->mode = old.mode; k->width = old.width; k->height = old.height;
+ if (create_buffer(k, &k->buf[0]) == 0 && create_buffer(k, &k->buf[1]) == 0) {
+ struct drm_mode_crtc set = { .crtc_id = k->crtc_id, .fb_id = k->buf[0].fb_id,
+ .set_connectors_ptr = (uintptr_t)&k->conn_id, .count_connectors = 1, .mode = k->mode, .mode_valid = 1 };
+ xioctl(k->fd, DRM_IOCTL_MODE_SETCRTC, &set);
+ }
+ return -1;
+ }
+ if (crtc != old.crtc_id) { k->scan_known = 0; k->nscan = 0; read_scanout_formats(k); k->cursor_ok = 0; }
+ fprintf(stderr, "kms: mode %ux%u@%u on connector %u, crtc %u\n", k->width, k->height, k->mode.vrefresh, k->conn_id, k->crtc_id);
+ return 0;
+}
+
+int kms_gamma_size(Kms *k) {
+ struct drm_mode_crtc c = { .crtc_id = k->crtc_id };
+ if (k->fd < 0 || xioctl(k->fd, DRM_IOCTL_MODE_GETCRTC, &c)) return 0;
+ return (int)c.gamma_size;
+}
+
+int kms_set_gamma(Kms *k, int n, const uint16_t *r, const uint16_t *g, const uint16_t *b) {
+ struct drm_mode_crtc_lut l = { .crtc_id = k->crtc_id, .gamma_size = (uint32_t)n,
+ .red = (uintptr_t)r, .green = (uintptr_t)g, .blue = (uintptr_t)b };
+ return k->fd < 0 || n <= 0 ? -1 : xioctl(k->fd, DRM_IOCTL_MODE_SETGAMMA, &l);
+}
+
+int kms_dpms(Kms *k, int on) {
+ uint64_t v = 0;
+ uint32_t id = 0;
+ if (k->fd < 0 || kms_obj_prop(k->fd, k->conn_id, DRM_MODE_OBJECT_CONNECTOR, "DPMS", &v, &id)) return -1;
+ struct drm_mode_connector_set_property sp = { .value = on ? DRM_MODE_DPMS_ON : DRM_MODE_DPMS_OFF, .prop_id = id, .connector_id = k->conn_id };
+ return xioctl(k->fd, DRM_IOCTL_MODE_SETPROPERTY, &sp);
+}
diff --git a/server/src/kms.h b/server/src/kms.h
index ce1008c..7f96dbf 100644
--- a/server/src/kms.h
+++ b/server/src/kms.h
@@ -2,6 +2,7 @@
#ifndef LORD_KMS_H
#define LORD_KMS_H
+#include <stddef.h>
#include <stdint.h>
#include <drm/drm.h>
#include <drm/drm_mode.h>
@@ -73,4 +74,40 @@ int kms_cursor_image(Kms *k, const uint32_t *argb, int w, int h, int hot_x, int
void kms_cursor_move(Kms *k, int x, int y);
void kms_cursor_show(Kms *k, int visible);
+/* ---- outputs and Settings → Displays (see hw/display.c, docs/SETTINGS.md) ---- */
+
+#define KMS_MAX_OUTPUTS 8
+typedef struct {
+ uint32_t id, type, type_id; /* connector id; type (DRM_MODE_CONNECTOR_*) and its number */
+ int connected;
+ uint32_t mm_w, mm_h;
+ uint32_t possible_crtcs; /* bit j = the j-th CRTC of GETRESOURCES */
+ uint32_t current_crtc; /* driving it now, 0 if none */
+ int nmodes;
+ struct drm_mode_modeinfo *modes; /* malloc */
+ uint8_t *edid; /* malloc, or NULL */
+ size_t edid_len;
+} KmsOutput;
+
+/* Every connector of the card (connected or not), with modes and EDID. Free with
+ * kms_outputs_free. Returns how many (≤ max). */
+int kms_outputs(int fd, KmsOutput *out, int max);
+void kms_outputs_free(KmsOutput *o, int n);
+const char *kms_connector_type_name(uint32_t type); /* "HDMI-A", "eDP", "Virtual"... */
+/* Optional choice for kms_open/kms_attach: which connected output (index in o) and mode. Returns
+ * 0 if it chose; otherwise the first connected output with its preferred mode is used. */
+typedef int (*KmsPicker)(const KmsOutput *o, int n, int *index, struct drm_mode_modeinfo *mode);
+void kms_set_picker(KmsPicker fn);
+/* Value and property id of a KMS object property by name. 0 if found. */
+int kms_obj_prop(int fd, uint32_t obj, uint32_t type, const char *name, uint64_t *val, uint32_t *prop_id);
+/* Runtime modeset (CPU path: the dumb buffers are recreated at the new size). The GPU path must
+ * be shut down first and started again after. Not while a flip is pending. On failure the
+ * previous mode is restored and -1 returned. */
+int kms_modeset(Kms *k, uint32_t conn_id, const struct drm_mode_modeinfo *mode);
+/* Hardware gamma LUT of the CRTC: entries per channel (0 = none, e.g. virtio-gpu), and set it. */
+int kms_gamma_size(Kms *k);
+int kms_set_gamma(Kms *k, int n, const uint16_t *r, const uint16_t *g, const uint16_t *b);
+/* Connector DPMS (screen off/on). 0 if the driver took it. */
+int kms_dpms(Kms *k, int on);
+
#endif
diff --git a/server/src/logs/journal.h b/server/src/logs/journal.h
index 84e76be..303bbcb 100644
--- a/server/src/logs/journal.h
+++ b/server/src/logs/journal.h
@@ -1,5 +1,5 @@
/* journal.h — lector propio de los archivos del journal de systemd (ver journal.c y
- * docs/SISTEMA.md, «Registros»). Sin libsystemd: se leen los archivos con pread y se valida cada
+ * docs/SYSTEM.md, «Registros»). Sin libsystemd: se leen los archivos con pread y se valida cada
* desplazamiento, así un archivo roto o cortado no tira abajo a lord-server. */
#ifndef LORD_LOGS_JOURNAL_H
#define LORD_LOGS_JOURNAL_H
diff --git a/server/src/logs/logs_admin.c b/server/src/logs/logs_admin.c
index c503059..8d3bf70 100644
--- a/server/src/logs/logs_admin.c
+++ b/server/src/logs/logs_admin.c
@@ -1,5 +1,5 @@
/* logs_admin.c — logs-system: el journal del sistema para un administrador que no está en los
- * grupos systemd-journal/adm (app Registros, docs/SISTEMA.md).
+ * grupos systemd-journal/adm (app Registros, docs/SYSTEM.md).
*
* logs-system <consulta> líneas clave=valor: since, until (segundos o µs), prio (0..7),
* kernel (0|1), match (unidad o identificador: [A-Za-z0-9@._:-]),
diff --git a/server/src/logs/logs_admin.h b/server/src/logs/logs_admin.h
index 2a28875..b86a066 100644
--- a/server/src/logs/logs_admin.h
+++ b/server/src/logs/logs_admin.h
@@ -1,5 +1,5 @@
/* logs_admin.h — la acción logs-system del ayudante (registros del sistema para los
- * administradores; app Registros, ver docs/SISTEMA.md). */
+ * administradores; app Registros, ver docs/SYSTEM.md). */
#ifndef LORD_LOGS_ADMIN_H
#define LORD_LOGS_ADMIN_H
diff --git a/server/src/mail/charset_tables.h b/server/src/mail/charset_tables.h
index acd1eba..1a9191d 100644
--- a/server/src/mail/charset_tables.h
+++ b/server/src/mail/charset_tables.h
@@ -1,5 +1,5 @@
-/* charset_tables.h — generado con tools (codecs de Python): 0x80..0xFF de cada juego de 8 bits → Unicode.
- * 0xFFFD donde el juego no define el byte. No editar a mano. */
+/* charset_tables.h — generated with tools (Python codecs): 0x80..0xFF of each 8-bit charset → Unicode.
+ * 0xFFFD where the charset does not define the byte. Do not edit by hand. */
#ifndef LORD_MAIL_CHARSET_TABLES_H
#define LORD_MAIL_CHARSET_TABLES_H
#include <stdint.h>
diff --git a/server/src/mail/dav.c b/server/src/mail/dav.c
new file mode 100644
index 0000000..4de97a5
--- /dev/null
+++ b/server/src/mail/dav.c
@@ -0,0 +1,130 @@
+/* dav.c — WebDAV transport and the per-account CalDAV/CardDAV worker (see dav.h, pim.c). */
+#include "dav.h"
+#include "mime.h"
+
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <time.h>
+#include <unistd.h>
+
+#define DAV_MAX_BODY ((size_t)48 << 20)
+
+static int dav_connect(Dav *d, const char *host, int port, int tls) {
+ if (d->c && !strcmp(d->host, host) && d->port == port && d->tls == tls) return 0;
+ if (d->c) { conn_close(d->c); d->c = NULL; }
+ if (!tls) { snprintf(d->err, sizeof d->err, "insecure"); return -1; }
+ TlsInfo ti;
+ char why[64];
+ d->c = open_conn(d->a->id, host, port, 1, d->a->pin_dav, &ti, why, sizeof why);
+ if (!d->c) { snprintf(d->err, sizeof d->err, "%s", why); return -1; }
+ snprintf(d->host, sizeof d->host, "%s", host);
+ d->port = port;
+ d->tls = tls;
+ return 0;
+}
+
+int dav_begin(Dav *d, Account *a) {
+ memset(d, 0, sizeof *d);
+ d->a = a;
+ pthread_mutex_lock(&G);
+ char *pw = a->password ? strdup(a->password) : NULL;
+ pthread_mutex_unlock(&G);
+ if (!pw) { snprintf(d->err, sizeof d->err, "no-password"); return -2; }
+ char up[600];
+ snprintf(up, sizeof up, "%s:%s", a->user, pw);
+ explicit_bzero(pw, strlen(pw));
+ free(pw);
+ size_t el;
+ char *e = b64_encode((const unsigned char *)up, strlen(up), 0, &el);
+ explicit_bzero(up, sizeof up);
+ if (!e) return -1;
+ snprintf(d->auth, sizeof d->auth, "Authorization: Basic %s\r\n", e);
+ explicit_bzero(e, el);
+ free(e);
+ int tls, port;
+ char host[256], path[1024];
+ if (http_split_url(a->url, &tls, host, sizeof host, &port, path, sizeof path)) { snprintf(d->err, sizeof d->err, "bad URL"); return -1; }
+ return dav_connect(d, host, port, tls);
+}
+
+void dav_end(Dav *d) {
+ if (d->c) conn_close(d->c);
+ d->c = NULL;
+ explicit_bzero(d->auth, sizeof d->auth);
+}
+
+void dav_abs(const Dav *d, const char *path, char *out, size_t cap) {
+ if (!strncasecmp(path, "https://", 8) || !strncasecmp(path, "http://", 7)) { snprintf(out, cap, "%s", path); return; }
+ if (d->port == 443) snprintf(out, cap, "https://%s%s", d->host, path);
+ else snprintf(out, cap, "https://%s:%d%s", d->host, d->port, path);
+}
+
+int dav_req(Dav *d, const char *method, const char *target, int depth, const char *body, const char *ctype, const char *extra, HttpResp *out) {
+ char cur[2048];
+ dav_abs(d, target, cur, sizeof cur);
+ for (int hop = 0; hop < 4; hop++) {
+ int tls, port;
+ char host[256], path[1800];
+ if (http_split_url(cur, &tls, host, sizeof host, &port, path, sizeof path)) { snprintf(d->err, sizeof d->err, "bad URL"); return -1; }
+ for (int attempt = 0; attempt < 2; attempt++) {
+ if (dav_connect(d, host, port, tls)) return -1;
+ char hdrs[2048];
+ snprintf(hdrs, sizeof hdrs, "%s%s%s%s%s%s", d->auth, depth >= 0 ? (depth == 0 ? "Depth: 0\r\n" : depth == 1 ? "Depth: 1\r\n" : "Depth: infinity\r\n") : "",
+ ctype ? "Content-Type: " : "", ctype ? ctype : "", ctype ? "\r\n" : "", extra ? extra : "");
+ int r = http_request(d->c, method, host, path, hdrs, body, body ? strlen(body) : 0, DAV_MAX_BODY, 60000, out);
+ if (r == -1 && attempt == 0) { conn_close(d->c); d->c = NULL; continue; } /* the server closed a kept-alive connection */
+ if (r) { snprintf(d->err, sizeof d->err, r == -2 ? "response too big" : "connection"); return -1; }
+ if (!out->keep_alive) { conn_close(d->c); d->c = NULL; }
+ break;
+ }
+ if (out->status == 401) d->auth_failed = 1;
+ if ((out->status == 301 || out->status == 302 || out->status == 307 || out->status == 308) && out->location[0]) {
+ char loc[1100];
+ snprintf(loc, sizeof loc, "%s", out->location);
+ http_resp_free(out);
+ if (loc[0] == '/') { char base[1200]; Dav tmp = *d; snprintf(tmp.host, sizeof tmp.host, "%s", host); tmp.port = port; dav_abs(&tmp, loc, base, sizeof base); snprintf(cur, sizeof cur, "%s", base); }
+ else snprintf(cur, sizeof cur, "%s", loc);
+ continue;
+ }
+ return 0;
+ }
+ snprintf(d->err, sizeof d->err, "too many redirects");
+ return -1;
+}
+
+/* ---- the worker ---- */
+
+void *dav_worker(void *arg) {
+ Account *a = arg;
+ Job *first = job_new(J_DAV_SYNC, 0, 1);
+ if (first) job_push(a, first);
+ time_t last = 0;
+ while (!a->stop) {
+ Job *j = job_pop(a);
+ if (!j) {
+ struct pollfd p = { a->wake, POLLIN, 0 };
+ int left = (int)(15 * 60 - (time(NULL) - last));
+ if (left < 1) left = 1;
+ poll(&p, 1, left * 1000);
+ uint64_t v;
+ if (read(a->wake, &v, sizeof v) < 0) { /* timeout */ }
+ if (a->stop) break;
+ if (!a->jobs && time(NULL) - last >= 15 * 60) { Job *s = job_new(J_DAV_SYNC, 0, 1); if (s) job_push(a, s); }
+ continue;
+ }
+ /* coalesce: many queued syncs are one sync */
+ int kind = j->kind;
+ uint32_t req = j->req;
+ job_free(j);
+ while ((j = job_pop(a))) { if (j->req) { if (req) { JBuf b; jb_init(&b); jb_raw(&b, "{\"ok\":true}"); reply_done(j->req, &b); } else req = j->req; } job_free(j); }
+ (void)kind;
+ acct_status(a, "sync", "");
+ pim_dav_sync(a);
+ last = time(NULL);
+ if (req) { JBuf b; jb_init(&b); jb_raw(&b, "{\"ok\":true}"); reply_done(req, &b); }
+ }
+ return NULL;
+}
diff --git a/server/src/mail/dav.h b/server/src/mail/dav.h
new file mode 100644
index 0000000..f711ea2
--- /dev/null
+++ b/server/src/mail/dav.h
@@ -0,0 +1,27 @@
+/* dav.h — WebDAV requests (CalDAV RFC 4791, CardDAV RFC 6352) over our HTTP client, for the
+ * account's DAV worker (dav.c) and the calendar/contacts sync (pim.c). */
+#ifndef LORD_MAIL_DAV_H
+#define LORD_MAIL_DAV_H
+
+#include "maild.h"
+#include "http.h"
+
+typedef struct {
+ Account *a;
+ Conn *c;
+ char host[256];
+ int port, tls;
+ char auth[600]; /* "Authorization: Basic …\r\n" */
+ char err[200];
+ int auth_failed;
+} Dav;
+
+int dav_begin(Dav *d, Account *a);
+void dav_end(Dav *d);
+/* target: absolute URL or a path on the current host. depth < 0: no Depth header.
+ * Follows up to 3 redirects. 0 when a response arrived (check out->status). */
+int dav_req(Dav *d, const char *method, const char *target, int depth, const char *body, const char *ctype, const char *extra, HttpResp *out);
+/* absolute URL of a path on the current host */
+void dav_abs(const Dav *d, const char *path, char *out, size_t cap);
+
+#endif
diff --git a/server/src/mail/html.c b/server/src/mail/html.c
new file mode 100644
index 0000000..1092496
--- /dev/null
+++ b/server/src/mail/html.c
@@ -0,0 +1,1174 @@
+/* html.c — see html.h. Lenient tokenizer + tree building in a single pass. */
+#include "html.h"
+#include "html_entities.h"
+#include "../doc/wire.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+
+/* ---- text: entities and UTF-8 ---- */
+
+static int put_cp(char *o, uint32_t cp) {
+ if (cp < 0x80) { o[0] = (char)cp; return 1; }
+ if (cp < 0x800) { o[0] = (char)(0xc0 | (cp >> 6)); o[1] = (char)(0x80 | (cp & 0x3f)); return 2; }
+ if (cp < 0x10000) { o[0] = (char)(0xe0 | (cp >> 12)); o[1] = (char)(0x80 | ((cp >> 6) & 0x3f)); o[2] = (char)(0x80 | (cp & 0x3f)); return 3; }
+ o[0] = (char)(0xf0 | (cp >> 18)); o[1] = (char)(0x80 | ((cp >> 12) & 0x3f)); o[2] = (char)(0x80 | ((cp >> 6) & 0x3f)); o[3] = (char)(0x80 | (cp & 0x3f));
+ return 4;
+}
+
+/* windows-1252 for numeric references 128-159 (as browsers do) */
+static const uint16_t c1fix[32] = { 0x20ac, 0xfffd, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021, 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0xfffd, 0x017d, 0xfffd,
+ 0xfffd, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014, 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0xfffd, 0x017e, 0x0178 };
+
+static uint32_t ent_lookup(const char *name, size_t n) {
+ char key[40];
+ if (n == 0 || n >= sizeof key) return 0;
+ memcpy(key, name, n);
+ key[n] = 0;
+ size_t lo = 0, hi = sizeof html_ents / sizeof html_ents[0];
+ while (lo < hi) {
+ size_t mid = (lo + hi) / 2;
+ int c = strcmp(html_ents[mid].name, key);
+ if (!c) return html_ents[mid].cp;
+ if (c < 0) lo = mid + 1; else hi = mid;
+ }
+ return 0;
+}
+
+/* Decodes an entity at s[i] == '&'. Returns the code point (0 if not an entity) and stores in *used
+ * the bytes consumed. */
+static uint32_t entity(const char *s, size_t len, size_t i, size_t *used) {
+ *used = 0;
+ if (i + 1 >= len) return 0;
+ if (s[i + 1] == '#') {
+ size_t k = i + 2;
+ int hex = 0;
+ if (k < len && (s[k] == 'x' || s[k] == 'X')) { hex = 1; k++; }
+ uint32_t cp = 0;
+ size_t d0 = k;
+ while (k < len && k - d0 < 8) {
+ char c = s[k];
+ int v = (c >= '0' && c <= '9') ? c - '0' : (hex && c >= 'a' && c <= 'f') ? c - 'a' + 10 : (hex && c >= 'A' && c <= 'F') ? c - 'A' + 10 : -1;
+ if (v < 0) break;
+ cp = cp * (hex ? 16u : 10u) + (uint32_t)v;
+ k++;
+ }
+ if (k == d0) return 0;
+ if (k < len && s[k] == ';') k++;
+ *used = k - i;
+ if (cp >= 0x80 && cp <= 0x9f) cp = c1fix[cp - 0x80];
+ if (!cp || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) cp = 0xfffd;
+ return cp;
+ }
+ size_t k = i + 1;
+ while (k < len && k - i <= 32 && isalnum((unsigned char)s[k])) k++;
+ size_t n = k - i - 1;
+ /* longest matching name (legacy ones without ";", like &nbsp without a semicolon) */
+ for (size_t m = n; m >= 2; m--) {
+ uint32_t cp = ent_lookup(s + i + 1, m);
+ if (cp) {
+ size_t u = 1 + m;
+ if (m == n && k < len && s[k] == ';') u++;
+ else if (m != n) { if (m < 4) return 0; } /* &notit → ¬it only for long names */
+ *used = u;
+ return cp;
+ }
+ }
+ return 0;
+}
+
+/* Characters that are never shown (preheader padding, BOM, soft hyphens). */
+static int invisible(uint32_t cp) {
+ return cp == 0x034f || cp == 0x200b || cp == 0x200c || cp == 0x200d || cp == 0x2060 || cp == 0xfeff || cp == 0x00ad ||
+ cp == 0x200e || cp == 0x200f || (cp >= 0x202a && cp <= 0x202e) || (cp >= 0x2066 && cp <= 0x2069);
+}
+
+static uint32_t next_cp(const char *s, size_t len, size_t *i) {
+ unsigned char c = (unsigned char)s[*i];
+ if (c < 0x80) { (*i)++; return c; }
+ int k = 0;
+ uint32_t cp = 0;
+ if (c >= 0xc2 && c <= 0xdf) { k = 2; cp = c & 0x1f; }
+ else if (c >= 0xe0 && c <= 0xef) { k = 3; cp = c & 0x0f; }
+ else if (c >= 0xf0 && c <= 0xf4) { k = 4; cp = c & 0x07; }
+ if (!k || *i + (size_t)k > len) { (*i)++; return 0xfffd; }
+ for (int j = 1; j < k; j++) {
+ unsigned char d = (unsigned char)s[*i + (size_t)j];
+ if ((d & 0xc0) != 0x80) { (*i)++; return 0xfffd; }
+ cp = (cp << 6) | (d & 0x3f);
+ }
+ if ((k == 3 && cp < 0x800) || (k == 4 && (cp < 0x10000 || cp > 0x10ffff)) || (cp >= 0xd800 && cp <= 0xdfff)) { (*i)++; return 0xfffd; }
+ *i += (size_t)k;
+ return cp;
+}
+
+/* Bounded integer from an attribute (never atoi: it overflows on hostile input). */
+static int hnum(const char *v, long lo, long hi, long dflt) {
+ if (!v) return (int)dflt;
+ while (*v == ' ') v++;
+ char *e;
+ errno = 0;
+ long x = strtol(v, &e, 10);
+ if (e == v || errno == ERANGE) return (int)dflt;
+ return (int)(x < lo ? lo : x > hi ? hi : x);
+}
+
+/* ---- buffers ---- */
+
+typedef struct { char *p; size_t n, cap; } Buf;
+static void bput(Buf *b, const char *d, size_t n) {
+ if (b->n + n + 1 > b->cap) {
+ size_t nc = b->cap ? b->cap * 2 : 128;
+ while (nc < b->n + n + 1) nc *= 2;
+ char *np = realloc(b->p, nc);
+ if (!np) return;
+ b->p = np; b->cap = nc;
+ }
+ memcpy(b->p + b->n, d, n);
+ b->n += n;
+ b->p[b->n] = 0;
+}
+
+/* ---- colors and lengths ---- */
+
+typedef struct { const char *n; uint32_t rgb; } Named;
+static const Named named[] = {
+ { "aqua", 0x00ffff }, { "black", 0x000000 }, { "blue", 0x0000ff }, { "brown", 0xa52a2a }, { "crimson", 0xdc143c }, { "cyan", 0x00ffff },
+ { "darkblue", 0x00008b }, { "darkgray", 0xa9a9a9 }, { "darkgreen", 0x006400 }, { "darkgrey", 0xa9a9a9 }, { "darkred", 0x8b0000 },
+ { "dimgray", 0x696969 }, { "fuchsia", 0xff00ff }, { "gainsboro", 0xdcdcdc }, { "gold", 0xffd700 }, { "gray", 0x808080 }, { "green", 0x008000 },
+ { "grey", 0x808080 }, { "indigo", 0x4b0082 }, { "lightblue", 0xadd8e6 }, { "lightgray", 0xd3d3d3 }, { "lightgrey", 0xd3d3d3 },
+ { "lime", 0x00ff00 }, { "magenta", 0xff00ff }, { "maroon", 0x800000 }, { "navy", 0x000080 }, { "olive", 0x808000 }, { "orange", 0xffa500 },
+ { "pink", 0xffc0cb }, { "purple", 0x800080 }, { "red", 0xff0000 }, { "silver", 0xc0c0c0 }, { "skyblue", 0x87ceeb }, { "steelblue", 0x4682b4 },
+ { "teal", 0x008080 }, { "tomato", 0xff6347 }, { "violet", 0xee82ee }, { "white", 0xffffff }, { "whitesmoke", 0xf5f5f5 }, { "yellow", 0xffff00 },
+};
+
+/* "#abc", "#aabbcc", "rgb(1,2,3)", "rgba(...)", names. Returns 1 and stores 0xRRGGBBAA. */
+static int parse_color(const char *v, uint32_t *out) {
+ while (*v == ' ') v++;
+ if (*v == '#') {
+ v++;
+ size_t n = 0;
+ while (isxdigit((unsigned char)v[n])) n++;
+ unsigned long x = strtoul(v, NULL, 16);
+ if (n == 3) { unsigned r = (unsigned)(x >> 8) & 15, g = (unsigned)(x >> 4) & 15, b = (unsigned)x & 15; *out = ((r * 17u) << 24) | ((g * 17u) << 16) | ((b * 17u) << 8) | 0xff; return 1; }
+ if (n == 6) { *out = ((uint32_t)x << 8) | 0xff; return 1; }
+ if (n == 8) { *out = (uint32_t)x; return 1; }
+ return 0;
+ }
+ if (!strncasecmp(v, "rgb", 3)) {
+ const char *p = strchr(v, '(');
+ if (!p) return 0;
+ double c[4] = { 0, 0, 0, 1 };
+ int k = 0;
+ p++;
+ while (k < 4 && *p) {
+ while (*p == ' ' || *p == ',' || *p == '/') p++;
+ char *e;
+ double x = strtod(p, &e);
+ if (e == p) break;
+ if (*e == '%') { x = k < 3 ? x * 2.55 : x / 100.0; e++; }
+ c[k++] = x;
+ p = e;
+ }
+ if (k < 3) return 0;
+ for (int i = 0; i < 3; i++) c[i] = c[i] < 0 ? 0 : c[i] > 255 ? 255 : c[i];
+ double a = c[3] < 0 ? 0 : c[3] > 1 ? 1 : c[3];
+ *out = ((uint32_t)c[0] << 24) | ((uint32_t)c[1] << 16) | ((uint32_t)c[2] << 8) | (uint32_t)(a * 255);
+ return 1;
+ }
+ char low[24];
+ size_t n = 0;
+ while (v[n] && v[n] != ' ' && v[n] != ';' && n + 1 < sizeof low) { low[n] = (char)tolower((unsigned char)v[n]); n++; }
+ low[n] = 0;
+ if (!strcmp(low, "transparent")) { *out = 0; return 1; }
+ for (size_t i = 0; i < sizeof named / sizeof named[0]; i++) if (!strcmp(named[i].n, low)) { *out = (named[i].rgb << 8) | 0xff; return 1; }
+ return 0;
+}
+
+/* CSS length → px (em/rem relative to base). Returns 1 if there is a number; *pct if a percentage. */
+static int parse_len(const char *v, double base, double *px, int *pct) {
+ while (*v == ' ') v++;
+ char *e;
+ double x = strtod(v, &e);
+ if (e == v) return 0;
+ *pct = 0;
+ if (*e == '%') *pct = 1;
+ else if (!strncasecmp(e, "pt", 2)) x *= 4.0 / 3.0;
+ else if (!strncasecmp(e, "em", 2) || !strncasecmp(e, "rem", 3)) x *= base;
+ else if (!strncasecmp(e, "pc", 2)) x *= 16;
+ else if (!strncasecmp(e, "in", 2)) x *= 96;
+ else if (!strncasecmp(e, "cm", 2)) x *= 37.8;
+ else if (!strncasecmp(e, "mm", 2)) x *= 3.78;
+ if (x != x || x > 1e5 || x < -1e5) return 0;
+ *px = x;
+ return 1;
+}
+
+/* ---- styles ---- */
+
+typedef struct {
+ unsigned b : 1, i : 1, u : 1, st : 1, mono : 1, pre : 1;
+ uint32_t color, bg;
+ unsigned has_color : 1, has_bg : 1;
+ double fs; /* 0 = the app's default */
+ int link; /* -1 = no link */
+} IStyle;
+
+typedef struct {
+ /* block */
+ int align; /* 0, 's', 'c', 'e', 'j' */
+ int self_center;
+ uint32_t bg; int has_bg;
+ double pad[4]; int has_pad;
+ double mt, mb;
+ double w; int wpct, has_w;
+ double mw; int has_mw;
+ double bw; uint32_t bc; int has_border;
+ double bl; uint32_t blc; int has_bl;
+ double radius;
+ int valign; /* 't','m','b' */
+ int hidden;
+} BStyle;
+
+static int sw(const char *a, const char *b) { return !strncasecmp(a, b, strlen(b)); }
+
+/* Applies a style="" attribute to both styles. */
+static void apply_css(const char *css, size_t n, IStyle *is, BStyle *bs) {
+ char decl[512];
+ size_t i = 0;
+ int overflow_hidden = 0, zero_height = 0;
+ while (i < n) {
+ size_t a = i;
+ int par = 0;
+ while (i < n && (par || css[i] != ';')) { if (css[i] == '(') par++; else if (css[i] == ')' && par) par--; i++; }
+ size_t dl = i - a;
+ i++;
+ if (dl >= sizeof decl) continue;
+ memcpy(decl, css + a, dl);
+ decl[dl] = 0;
+ char *colon = strchr(decl, ':');
+ if (!colon) continue;
+ *colon = 0;
+ char *prop = decl, *val = colon + 1;
+ while (*prop == ' ' || *prop == '\t' || *prop == '\n' || *prop == '\r') prop++;
+ for (char *p = prop + strlen(prop); p > prop && (p[-1] == ' ' || p[-1] == '\t'); ) *--p = 0;
+ for (char *p = prop; *p; p++) *p = (char)tolower((unsigned char)*p);
+ while (*val == ' ' || *val == '\t' || *val == '\n' || *val == '\r') val++;
+ char *imp = strcasestr(val, "!important");
+ if (imp) *imp = 0;
+ for (char *p = val + strlen(val); p > val && (p[-1] == ' ' || p[-1] == '\t' || p[-1] == '\r' || p[-1] == '\n'); ) *--p = 0;
+ /* no url(), expression() or @import: the whole declaration is ignored */
+ if (strcasestr(val, "url(") || strcasestr(val, "expression") || strcasestr(val, "javascript")) continue;
+ double px; int pct; uint32_t c;
+ double base = is->fs > 0 ? is->fs : 14;
+ if (!strcmp(prop, "display") && !strcasecmp(val, "none")) bs->hidden = 1;
+ else if (!strcmp(prop, "visibility") && !strcasecmp(val, "hidden")) bs->hidden = 1;
+ else if (!strcmp(prop, "mso-hide") && !strcasecmp(val, "all")) bs->hidden = 1;
+ else if (!strcmp(prop, "opacity") && strtod(val, NULL) <= 0.01 && isdigit((unsigned char)val[0])) bs->hidden = 1;
+ else if (!strcmp(prop, "overflow") && !strcasecmp(val, "hidden")) overflow_hidden = 1;
+ else if ((!strcmp(prop, "max-height") || !strcmp(prop, "height")) && parse_len(val, base, &px, &pct) && px <= 0) zero_height = 1;
+ else if (!strcmp(prop, "color") && parse_color(val, &c)) { is->color = c; is->has_color = 1; }
+ else if ((!strcmp(prop, "background-color") || !strcmp(prop, "background")) && parse_color(val, &c)) { bs->bg = c; bs->has_bg = 1; is->bg = c; is->has_bg = 0; }
+ else if (!strcmp(prop, "font-weight")) { is->b = (sw(val, "bold") || sw(val, "bolder") || hnum(val, 0, 1000, 400) >= 600) ? 1 : 0; }
+ else if (!strcmp(prop, "font-style")) is->i = sw(val, "italic") || sw(val, "oblique");
+ else if (!strcmp(prop, "text-decoration") || !strcmp(prop, "text-decoration-line")) {
+ if (strcasestr(val, "none")) { is->u = 0; is->st = 0; }
+ if (strcasestr(val, "underline")) is->u = 1;
+ if (strcasestr(val, "line-through")) is->st = 1;
+ } else if (!strcmp(prop, "font-family")) is->mono = strcasestr(val, "mono") || strcasestr(val, "courier") || strcasestr(val, "consolas");
+ else if (!strcmp(prop, "font-size")) {
+ if (parse_len(val, base, &px, &pct)) { double v = pct ? base * px / 100 : px; if (v <= 0.5) bs->hidden = 1; else is->fs = v < 8 ? 8 : v > 48 ? 48 : v; }
+ else if (!strcasecmp(val, "small")) is->fs = 12; else if (!strcasecmp(val, "x-small")) is->fs = 10;
+ else if (!strcasecmp(val, "large")) is->fs = 18; else if (!strcasecmp(val, "x-large")) is->fs = 24; else if (!strcasecmp(val, "xx-large")) is->fs = 32;
+ else if (!strcasecmp(val, "medium")) is->fs = 15;
+ } else if (!strcmp(prop, "font")) {
+ /* shorthand: only weight and size */
+ if (strcasestr(val, "bold")) is->b = 1;
+ if (strcasestr(val, "italic")) is->i = 1;
+ const char *p = val;
+ while (*p) { if (isdigit((unsigned char)*p) && parse_len(p, base, &px, &pct) && !pct && px >= 6) { is->fs = px > 48 ? 48 : px; break; } while (*p && *p != ' ') p++; while (*p == ' ') p++; }
+ } else if (!strcmp(prop, "text-align")) {
+ bs->align = sw(val, "center") ? 'c' : (sw(val, "right") || sw(val, "end")) ? 'e' : sw(val, "justify") ? 'j' : 's';
+ } else if (!strcmp(prop, "white-space")) is->pre = sw(val, "pre");
+ else if (!strncmp(prop, "padding", 7)) {
+ double v[4];
+ int k = 0;
+ const char *p = val;
+ while (k < 4 && *p) { if (!parse_len(p, base, &v[k], &pct)) break; if (pct) v[k] = 0; k++; while (*p && *p != ' ') p++; while (*p == ' ') p++; }
+ if (!k) continue;
+ if (!strcmp(prop, "padding")) {
+ double t = v[0], r = k > 1 ? v[1] : t, b = k > 2 ? v[2] : t, l = k > 3 ? v[3] : r;
+ bs->pad[0] = t; bs->pad[1] = r; bs->pad[2] = b; bs->pad[3] = l;
+ } else if (!strcmp(prop, "padding-top")) bs->pad[0] = v[0];
+ else if (!strcmp(prop, "padding-right")) bs->pad[1] = v[0];
+ else if (!strcmp(prop, "padding-bottom")) bs->pad[2] = v[0];
+ else if (!strcmp(prop, "padding-left")) bs->pad[3] = v[0];
+ bs->has_pad = 1;
+ } else if (!strncmp(prop, "margin", 6)) {
+ if (!strcmp(prop, "margin")) {
+ char tmp[128];
+ snprintf(tmp, sizeof tmp, "%s", val);
+ char *tok[4]; int k = 0;
+ for (char *t = strtok(tmp, " "); t && k < 4; t = strtok(NULL, " ")) tok[k++] = t;
+ if (!k) continue;
+ const char *top = tok[0], *right = k > 1 ? tok[1] : top, *bot = k > 2 ? tok[2] : top, *left = k > 3 ? tok[3] : right;
+ if (!strcasecmp(right, "auto") && !strcasecmp(left, "auto")) bs->self_center = 1;
+ if (parse_len(top, base, &px, &pct) && !pct && px > 0) bs->mt = px;
+ if (parse_len(bot, base, &px, &pct) && !pct && px > 0) bs->mb = px;
+ } else if (!strcmp(prop, "margin-top") && parse_len(val, base, &px, &pct) && !pct && px > 0) bs->mt = px;
+ else if (!strcmp(prop, "margin-bottom") && parse_len(val, base, &px, &pct) && !pct && px > 0) bs->mb = px;
+ } else if (!strcmp(prop, "width") && parse_len(val, base, &px, &pct) && px > 0) { bs->w = px; bs->wpct = pct; bs->has_w = 1; }
+ else if (!strcmp(prop, "max-width") && parse_len(val, base, &px, &pct) && !pct && px > 0) { bs->mw = px; bs->has_mw = 1; }
+ else if (!strcmp(prop, "border") || !strcmp(prop, "border-left") || !strcmp(prop, "border-top") || !strcmp(prop, "border-bottom")) {
+ double w = 0; uint32_t col = 0x999999ff; int none = strcasestr(val, "none") != NULL;
+ const char *p = val;
+ while (*p) {
+ if (isdigit((unsigned char)*p)) { parse_len(p, base, &w, &pct); }
+ else if (*p == '#' || !strncasecmp(p, "rgb", 3) || isalpha((unsigned char)*p)) parse_color(p, &col);
+ while (*p && *p != ' ') { if (*p == '(') { while (*p && *p != ')') p++; } if (*p) p++; }
+ while (*p == ' ') p++;
+ }
+ if (none || w <= 0) continue;
+ if (w > 8) w = 8;
+ if (!strcmp(prop, "border-left")) { bs->bl = w; bs->blc = col; bs->has_bl = 1; }
+ else if (!strcmp(prop, "border")) { bs->bw = w; bs->bc = col; bs->has_border = 1; }
+ } else if (!strcmp(prop, "border-radius") && parse_len(val, base, &px, &pct) && !pct) bs->radius = px > 40 ? 40 : px;
+ else if (!strcmp(prop, "vertical-align")) bs->valign = sw(val, "middle") ? 'm' : sw(val, "bottom") ? 'b' : 't';
+ }
+ if (overflow_hidden && zero_height) bs->hidden = 1;
+}
+
+/* ---- tags ---- */
+
+enum { K_INLINE, K_BLOCK, K_DROP, K_RAW, K_IGNORE };
+
+static int tag_is(const char *t, const char *const *list) { for (; *list; list++) if (!strcmp(t, *list)) return 1; return 0; }
+static const char *const T_VOID[] = { "br", "hr", "img", "meta", "link", "input", "wbr", "col", "area", "base", "source", "track", "param", "embed", "keygen", "basefont", "image", NULL };
+static const char *const T_RAW[] = { "script", "style", "textarea", "title", "xmp", "noembed", "noframes", "plaintext", "iframe", NULL };
+static const char *const T_DROP[] = { "head", "object", "applet", "frame", "frameset", "noscript", "template", "svg", "math", "audio", "video", "canvas", "map",
+ "select", "button", "option", "optgroup", "datalist", "dialog", "portal", "picture", NULL };
+static const char *const T_BLOCK[] = { "div", "p", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre", "center", "ul", "ol", "li", "dl", "dt", "dd",
+ "address", "article", "section", "header", "footer", "nav", "main", "aside", "figure", "figcaption", "table",
+ "tr", "td", "th", "caption", "body", "html", "form", "fieldset", "legend", "details", "summary", "hgroup", "menu", "listing", NULL };
+static const char *const T_IGNORE[] = { "thead", "tbody", "tfoot", "colgroup", NULL };
+
+static int kind_of(const char *t) {
+ if (tag_is(t, T_RAW)) return K_RAW;
+ if (tag_is(t, T_DROP)) return K_DROP;
+ if (tag_is(t, T_IGNORE)) return K_IGNORE;
+ if (tag_is(t, T_BLOCK)) return K_BLOCK;
+ return K_INLINE;
+}
+
+/* ---- attributes ---- */
+
+#define MAX_ATTRS 32
+typedef struct { char name[24]; const char *v; size_t vn; char *dec; } Attr;
+
+static const char *attr(Attr *a, int n, const char *name) {
+ for (int i = 0; i < n; i++) if (!strcmp(a[i].name, name)) return a[i].dec ? a[i].dec : "";
+ return NULL;
+}
+
+/* attribute value with entities decoded (malloc) */
+static char *decode_attr(const char *v, size_t n) {
+ Buf b = { 0 };
+ for (size_t i = 0; i < n;) {
+ if (v[i] == '&') {
+ size_t used;
+ uint32_t cp = entity(v, n, i, &used);
+ if (cp && used) { char t[4]; bput(&b, t, (size_t)put_cp(t, cp)); i += used; continue; }
+ }
+ bput(&b, v + i, 1);
+ i++;
+ }
+ if (!b.p) { b.p = calloc(1, 1); }
+ return b.p;
+}
+
+/* ---- the builder ---- */
+
+typedef struct { char tag[16]; IStyle is; int frame; int list_n, ordered; } Open;
+typedef struct { int kids; char kind; } Frame;
+typedef struct { char *href; Buf text; int warn; } Link;
+
+typedef struct {
+ JBuf out;
+ Open open[HTML_MAX_DEPTH * 2];
+ int nopen;
+ Frame fr[HTML_MAX_DEPTH + 2];
+ int nfr;
+ IStyle cur;
+ Buf run;
+ IStyle run_st;
+ int space, line_start;
+ Link links[HTML_MAX_LINKS];
+ int nlinks, cur_link;
+ char *remote[HTML_MAX_REMOTE];
+ int nremote;
+ HtmlStats st;
+ uint32_t root_bg; int has_root_bg;
+ HtmlData *data; int ndata;
+ int colors;
+} H;
+
+static void frame_sep(H *h) {
+ Frame *f = &h->fr[h->nfr - 1];
+ if (f->kids++) jb_raw(&h->out, ",");
+}
+
+static int istyle_eq(const IStyle *a, const IStyle *b) {
+ return a->b == b->b && a->i == b->i && a->u == b->u && a->st == b->st && a->mono == b->mono && a->has_color == b->has_color &&
+ (!a->has_color || a->color == b->color) && a->fs == b->fs && a->link == b->link && a->has_bg == b->has_bg && (!a->has_bg || a->bg == b->bg);
+}
+
+static void color_json(JBuf *o, const char *k, uint32_t c) {
+ if ((c & 0xff) == 0xff) jb_printf(o, ",\"%s\":\"#%06x\"", k, c >> 8);
+ else jb_printf(o, ",\"%s\":\"#%08x\"", k, c);
+}
+
+static void flush_run(H *h) {
+ if (!h->run.n) return;
+ if (h->st.nodes++ >= HTML_MAX_NODES) { h->st.truncated = 1; h->run.n = 0; return; }
+ frame_sep(h);
+ jb_raw(&h->out, "{\"t\":\"x\",\"x\":");
+ jb_strn(&h->out, h->run.p, h->run.n);
+ IStyle *s = &h->run_st;
+ if (s->b || s->i || s->u || s->st || s->mono || s->has_color || s->fs > 0 || s->has_bg) {
+ jb_raw(&h->out, ",\"s\":{\"_\":0");
+ if (s->b) jb_raw(&h->out, ",\"b\":1");
+ if (s->i) jb_raw(&h->out, ",\"i\":1");
+ if (s->u) jb_raw(&h->out, ",\"u\":1");
+ if (s->st) jb_raw(&h->out, ",\"st\":1");
+ if (s->mono) jb_raw(&h->out, ",\"mono\":1");
+ if (s->has_color) { color_json(&h->out, "c", s->color); h->colors = 1; }
+ if (s->has_bg) color_json(&h->out, "bg", s->bg);
+ if (s->fs > 0) jb_printf(&h->out, ",\"fs\":%d", (int)(s->fs + 0.5));
+ jb_raw(&h->out, "}");
+ }
+ if (s->link >= 0) jb_printf(&h->out, ",\"l\":%d", s->link);
+ jb_raw(&h->out, "}");
+ h->run.n = 0;
+}
+
+static void block_break(H *h) {
+ flush_run(h);
+ h->space = 0;
+ h->line_start = 1;
+}
+
+static void add_text(H *h, const char *s, size_t n) {
+ /* s: UTF-8, already decoded */
+ for (size_t i = 0; i < n;) {
+ uint32_t cp = next_cp(s, n, &i);
+ if (invisible(cp)) continue;
+ if (!h->cur.pre && (cp == ' ' || cp == '\t' || cp == '\n' || cp == '\r' || cp == '\f')) { if (!h->line_start) h->space = 1; continue; }
+ if (h->cur.pre && cp == '\r') continue;
+ if (h->cur.pre && cp == '\n') {
+ flush_run(h);
+ if (h->st.nodes++ < HTML_MAX_NODES) { frame_sep(h); jb_raw(&h->out, "{\"t\":\"br\"}"); }
+ h->line_start = 1;
+ continue;
+ }
+ if (cp < 0x20 && cp != '\t') continue;
+ if (h->run.n && !istyle_eq(&h->run_st, &h->cur)) flush_run(h);
+ if (!h->run.n) h->run_st = h->cur;
+ if (h->space) {
+ bput(&h->run, " ", 1);
+ if (h->cur_link >= 0) bput(&h->links[h->cur_link].text, " ", 1);
+ }
+ h->space = 0;
+ h->line_start = 0;
+ char t[4];
+ int k = put_cp(t, cp);
+ bput(&h->run, t, (size_t)k);
+ if (h->cur_link >= 0 && h->links[h->cur_link].text.n < 600) bput(&h->links[h->cur_link].text, t, (size_t)k);
+ }
+}
+
+static void bstyle_json(H *h, const BStyle *b, const IStyle *is) {
+ JBuf *o = &h->out;
+ jb_raw(o, ",\"s\":{\"_\":0");
+ if (b->align) jb_printf(o, ",\"a\":\"%c\"", b->align);
+ if (b->self_center) jb_raw(o, ",\"ac\":1");
+ if (b->has_bg) { color_json(o, "bg", b->bg); h->colors = 1; }
+ if (b->has_pad) jb_printf(o, ",\"p\":[%d,%d,%d,%d]", (int)b->pad[0], (int)b->pad[1], (int)b->pad[2], (int)b->pad[3]);
+ if (b->mt > 0) jb_printf(o, ",\"mt\":%d", (int)(b->mt > 60 ? 60 : b->mt));
+ if (b->mb > 0) jb_printf(o, ",\"mb\":%d", (int)(b->mb > 60 ? 60 : b->mb));
+ if (b->has_w) jb_printf(o, b->wpct ? ",\"wp\":%d" : ",\"w\":%d", (int)(b->w > 4000 ? 4000 : b->w));
+ if (b->has_mw) jb_printf(o, ",\"mw\":%d", (int)(b->mw > 4000 ? 4000 : b->mw));
+ if (b->has_border) { jb_printf(o, ",\"bw\":%d", (int)(b->bw + 0.5) ? (int)(b->bw + 0.5) : 1); color_json(o, "bc", b->bc); }
+ if (b->has_bl) { jb_printf(o, ",\"bl\":%d", (int)(b->bl + 0.5) ? (int)(b->bl + 0.5) : 1); color_json(o, "blc", b->blc); }
+ if (b->radius > 0) jb_printf(o, ",\"r\":%d", (int)b->radius);
+ if (b->valign) jb_printf(o, ",\"va\":\"%c\"", b->valign);
+ if (is && is->pre) jb_raw(o, ",\"pre\":1");
+ jb_raw(o, "}");
+}
+
+static int open_frame(H *h, const char *t, const BStyle *b, const char *extra) {
+ if (h->nfr >= HTML_MAX_DEPTH) { block_break(h); return 0; }
+ block_break(h);
+ if (h->st.nodes++ >= HTML_MAX_NODES) { h->st.truncated = 1; return 0; }
+ frame_sep(h);
+ jb_printf(&h->out, "{\"t\":\"%s\"", t);
+ bstyle_json(h, b, &h->cur);
+ if (extra) jb_raw(&h->out, extra);
+ jb_raw(&h->out, ",\"c\":[");
+ h->fr[h->nfr].kids = 0;
+ h->fr[h->nfr].kind = t[0];
+ h->nfr++;
+ return 1;
+}
+
+static void close_frame(H *h) {
+ block_break(h);
+ if (h->nfr <= 1) return;
+ jb_raw(&h->out, "]}");
+ h->nfr--;
+}
+
+static void end_link(H *h) {
+ if (h->cur_link < 0) return;
+ Link *l = &h->links[h->cur_link];
+ const char *why = html_link_warning(l->text.p ? l->text.p : "", l->href);
+ if (why) { l->warn = 1; h->st.warn++; }
+ h->cur_link = -1;
+ h->cur.link = -1;
+}
+
+/* Closes open elements from the top down to index idx (inclusive). */
+static void pop_to(H *h, int idx) {
+ while (h->nopen > idx) {
+ Open *o = &h->open[--h->nopen];
+ if (!strcmp(o->tag, "a")) end_link(h);
+ if (o->frame) close_frame(h);
+ else if (kind_of(o->tag) == K_BLOCK) block_break(h);
+ flush_run(h);
+ h->cur = o->is; /* the style from before it was opened */
+ if (h->cur_link >= 0 && h->cur.link != h->cur_link) h->cur_link = h->cur.link;
+ }
+}
+
+static int find_open(H *h, const char *tag, const char *const *stop) {
+ for (int i = h->nopen - 1; i >= 0; i--) {
+ if (!strcmp(h->open[i].tag, tag)) return i;
+ if (stop && tag_is(h->open[i].tag, stop)) return -1;
+ }
+ return -1;
+}
+
+static const char *const STOP_CELL[] = { "td", "th", "table", NULL };
+static const char *const STOP_TABLE[] = { "table", NULL };
+static const char *const STOP_LIST[] = { "ul", "ol", "table", "td", "th", NULL };
+
+static int is_ip_host(const char *h) {
+ if (h[0] == '[') return 1;
+ int dots = 0, digits = 1;
+ for (const char *c = h; *c; c++) { if (*c == '.') dots++; else if (!isdigit((unsigned char)*c)) digits = 0; }
+ return digits && dots == 3;
+}
+
+void html_url_host(const char *url, char *out, size_t cap) {
+ if (!cap) return;
+ out[0] = 0;
+ if (!url) return;
+ const char *p = url;
+ while (*p == ' ') p++;
+ const char *sch = strstr(p, "://");
+ if (sch && sch - p < 10) p = sch + 3;
+ else if (!strncasecmp(p, "www.", 4)) { /* no scheme */ }
+ else return;
+ const char *end = p;
+ while (*end && *end != '/' && *end != '?' && *end != '#') end++;
+ /* user@host */
+ const char *at = NULL;
+ for (const char *c = p; c < end; c++) if (*c == '@') at = c;
+ if (at) p = at + 1;
+ const char *colon = NULL;
+ for (const char *c = p; c < end; c++) if (*c == ':' && p[0] != '[') colon = c;
+ if (colon) end = colon;
+ size_t n = (size_t)(end - p);
+ if (n >= cap) n = cap - 1;
+ for (size_t i = 0; i < n; i++) out[i] = (char)tolower((unsigned char)p[i]);
+ out[n] = 0;
+ while (n && out[n - 1] == '.') out[--n] = 0;
+ if (n >= 4 && !strncmp(out, "www.", 4)) memmove(out, out + 4, n - 3);
+}
+
+static int host_match(const char *a, const char *b) {
+ if (!strcmp(a, b)) return 1;
+ size_t la = strlen(a), lb = strlen(b);
+ if (la > lb && a[la - lb - 1] == '.' && !strcmp(a + la - lb, b)) return 1;
+ if (lb > la && b[lb - la - 1] == '.' && !strcmp(b + lb - la, a)) return 1;
+ return 0;
+}
+
+/* Does the text look like a web address? Stores the host in out. */
+static int text_as_url(const char *t, char *out, size_t cap) {
+ char buf[600];
+ size_t n = 0;
+ while (*t == ' ') t++;
+ for (; *t && n + 1 < sizeof buf; t++) buf[n++] = *t;
+ while (n && (buf[n - 1] == ' ' || buf[n - 1] == '.' || buf[n - 1] == '/')) n--;
+ buf[n] = 0;
+ if (!n || strchr(buf, ' ')) return 0;
+ if (!strncasecmp(buf, "http://", 7) || !strncasecmp(buf, "https://", 8) || !strncasecmp(buf, "www.", 4)) {
+ html_url_host(buf, out, cap);
+ return out[0] != 0;
+ }
+ /* domain.tld[/...] */
+ const char *slash = strchr(buf, '/');
+ size_t hl = slash ? (size_t)(slash - buf) : n;
+ if (hl >= cap || hl < 4) return 0;
+ int dot = 0;
+ for (size_t i = 0; i < hl; i++) {
+ char c = buf[i];
+ if (c == '.') dot = 1;
+ else if (!isalnum((unsigned char)c) && c != '-' && (unsigned char)c < 0x80) return 0;
+ if (c == '@') return 0;
+ }
+ if (!dot) return 0;
+ /* the last label must be letters (a TLD), not "3.5" */
+ const char *ld = strrchr(buf, '.');
+ if (!ld || (size_t)(ld - buf) >= hl || !isalpha((unsigned char)ld[1])) return 0;
+ for (size_t i = 0; i < hl; i++) out[i] = (char)tolower((unsigned char)buf[i]);
+ out[hl] = 0;
+ if (!strncmp(out, "www.", 4)) memmove(out, out + 4, strlen(out + 4) + 1);
+ return 1;
+}
+
+const char *html_link_warning(const char *text, const char *href) {
+ if (!href) return NULL;
+ if (!strncasecmp(href, "mailto:", 7)) {
+ /* text shaped like an email address different from the mailto one */
+ char tt[300];
+ snprintf(tt, sizeof tt, "%s", text ? text : "");
+ char *a = tt; while (*a == ' ') a++;
+ size_t l = strlen(a); while (l && a[l - 1] == ' ') a[--l] = 0;
+ if (strchr(a, '@') && !strchr(a, ' ')) {
+ const char *m = href + 7;
+ size_t ml = strcspn(m, "?");
+ if (strlen(a) != ml || strncasecmp(a, m, ml)) return "deceptive";
+ }
+ return NULL;
+ }
+ char hh[256];
+ html_url_host(href, hh, sizeof hh);
+ if (!hh[0]) return NULL;
+ /* user@ in the authority: "https://[email protected]" */
+ const char *p = strstr(href, "://");
+ if (p) {
+ p += 3;
+ const char *e = p + strcspn(p, "/?#");
+ if (memchr(p, '@', (size_t)(e - p))) return "userinfo";
+ }
+ char th[256];
+ int looks = text_as_url(text ? text : "", th, sizeof th);
+ if (is_ip_host(hh) && looks) return "ip";
+ if (looks && !host_match(th, hh)) return "deceptive";
+ if (looks && strstr(hh, "xn--") && !strstr(th, "xn--")) return "punycode";
+ return NULL;
+}
+
+static int href_ok(const char *v) {
+ /* no whitespace or control characters inside the scheme ("java\tscript:") */
+ char sch[16];
+ size_t n = 0;
+ for (const char *c = v; *c && n + 1 < sizeof sch; c++) {
+ if ((unsigned char)*c <= 0x20) continue;
+ if (*c == ':') break;
+ sch[n++] = (char)tolower((unsigned char)*c);
+ }
+ sch[n] = 0;
+ if (!strchr(v, ':')) return 0;
+ return !strcmp(sch, "http") || !strcmp(sch, "https") || !strcmp(sch, "mailto");
+}
+
+static int add_remote(H *h, const char *url) {
+ for (int i = 0; i < h->nremote; i++) if (!strcmp(h->remote[i], url)) return i;
+ if (h->nremote >= HTML_MAX_REMOTE) return -1;
+ h->remote[h->nremote] = strdup(url);
+ if (!h->remote[h->nremote]) return -1;
+ return h->nremote++;
+}
+
+static void do_img(H *h, Attr *a, int na, const BStyle *bs) {
+ const char *src = attr(a, na, "src");
+ if (!src || !*src) return;
+ while (*src == ' ' || *src == '\n' || *src == '\t') src++;
+ double w = 0, hh = 0, px; int pct = 0, wpct = 0;
+ const char *ws = attr(a, na, "width"), *hs = attr(a, na, "height");
+ if (ws && parse_len(ws, 14, &px, &pct)) { w = px; wpct = pct; }
+ if (hs && parse_len(hs, 14, &px, &pct) && !pct) hh = px;
+ if (bs->has_w) { w = bs->w; wpct = bs->wpct; }
+ if (!wpct && ((ws && w <= 2 && hs && hh <= 2) || (ws && w == 0) || (hs && hh == 0))) { h->st.trackers++; return; }
+ char ref[32];
+ if (!strncasecmp(src, "cid:", 4)) { h->st.cid++; ref[0] = 0; }
+ else if (!strncasecmp(src, "http://", 7) || !strncasecmp(src, "https://", 8)) {
+ int k = add_remote(h, src);
+ if (k < 0) return;
+ snprintf(ref, sizeof ref, "r:%d", k);
+ h->st.remote++;
+ } else if (!strncasecmp(src, "data:image/", 11)) {
+ const char *semi = strstr(src, ";base64,");
+ if (!semi || !h->data || h->ndata >= HTML_MAX_DATA) return;
+ HtmlData *d = &h->data[h->ndata];
+ size_t tl = (size_t)(semi - (src + 11));
+ if (tl >= sizeof d->type) return;
+ memcpy(d->type, src + 11, tl);
+ d->type[tl] = 0;
+ if (strcmp(d->type, "png") && strcmp(d->type, "jpeg") && strcmp(d->type, "jpg") && strcmp(d->type, "gif") && strcmp(d->type, "bmp")) return;
+ d->p = semi + 8; /* points to the decoded copy (attributes live until the end) */
+ d->n = strlen(d->p);
+ snprintf(ref, sizeof ref, "d:%d", h->ndata);
+ h->ndata++;
+ h->st.data++;
+ } else return; /* relative paths, file:, javascript: … */
+ flush_run(h);
+ if (h->st.nodes++ >= HTML_MAX_NODES) { h->st.truncated = 1; return; }
+ frame_sep(h);
+ jb_raw(&h->out, "{\"t\":\"img\",\"src\":");
+ if (ref[0]) jb_str(&h->out, ref);
+ else {
+ char cid[200];
+ snprintf(cid, sizeof cid, "cid:%s", src + 4);
+ jb_str(&h->out, cid);
+ }
+ if (w > 0) jb_printf(&h->out, wpct ? ",\"wp\":%d" : ",\"w\":%d", (int)(w > 4000 ? 4000 : w));
+ if (hh > 0) jb_printf(&h->out, ",\"h\":%d", (int)(hh > 4000 ? 4000 : hh));
+ const char *alt = attr(a, na, "alt");
+ if (alt && *alt) { char t[200]; snprintf(t, sizeof t, "%s", alt); jb_raw(&h->out, ",\"alt\":"); jb_str(&h->out, t); }
+ if (h->cur.link >= 0) jb_printf(&h->out, ",\"l\":%d", h->cur.link);
+ if (bs->align) jb_printf(&h->out, ",\"a\":\"%c\"", bs->align);
+ jb_raw(&h->out, "}");
+ h->line_start = 0;
+}
+
+/* Legacy presentational attributes (bgcolor, align, width…) */
+static void legacy_attrs(Attr *a, int na, IStyle *is, BStyle *bs, const char *tag) {
+ const char *v;
+ uint32_t c;
+ double px; int pct;
+ if ((v = attr(a, na, "bgcolor")) && parse_color(v, &c)) { bs->bg = c; bs->has_bg = 1; }
+ if ((v = attr(a, na, "align"))) {
+ if (!strcmp(tag, "table") || !strcmp(tag, "img")) { if (!strcasecmp(v, "center")) bs->self_center = 1; }
+ else bs->align = !strcasecmp(v, "center") ? 'c' : !strcasecmp(v, "right") ? 'e' : !strcasecmp(v, "justify") ? 'j' : 's';
+ }
+ if ((v = attr(a, na, "valign"))) bs->valign = !strcasecmp(v, "middle") ? 'm' : !strcasecmp(v, "bottom") ? 'b' : 't';
+ if (strcmp(tag, "img") && (v = attr(a, na, "width")) && parse_len(v, 14, &px, &pct) && px > 0) { bs->w = px; bs->wpct = pct; bs->has_w = 1; }
+ if (!strcmp(tag, "table") && (v = attr(a, na, "border")) && hnum(v, 0, 4, 0) > 0) { bs->bw = hnum(v, 0, 4, 0); bs->bc = 0x999999ff; bs->has_border = 1; }
+ if (!strcmp(tag, "font")) {
+ if ((v = attr(a, na, "color")) && parse_color(v, &c)) { is->color = c; is->has_color = 1; }
+ if ((v = attr(a, na, "size"))) {
+ static const int fsz[] = { 10, 10, 13, 15, 18, 24, 32, 44 };
+ int k = hnum(v, -10, 10, 3);
+ if (v[0] == '+') k = 3 + hnum(v + 1, 0, 10, 0); else if (v[0] == '-') k = 3 - hnum(v + 1, 0, 10, 0);
+ if (k < 1) k = 1;
+ if (k > 7) k = 7;
+ is->fs = fsz[k];
+ }
+ if ((v = attr(a, na, "face"))) is->mono = strcasestr(v, "mono") || strcasestr(v, "courier");
+ }
+ if (!strcmp(tag, "body") && (v = attr(a, na, "text")) && parse_color(v, &c)) { is->color = c; is->has_color = 1; }
+ if ((v = attr(a, na, "hidden"))) bs->hidden = 1;
+}
+
+static void open_tag(H *h, const char *tag, Attr *a, int na, int selfclose) {
+ int kind = kind_of(tag);
+ if (kind == K_IGNORE) return;
+ int is_void = tag_is(tag, T_VOID);
+ /* implicit closes */
+ if (kind == K_BLOCK) {
+ int p = find_open(h, "p", STOP_CELL);
+ if (p >= 0 && strcmp(tag, "td") && strcmp(tag, "th") && strcmp(tag, "tr")) pop_to(h, p);
+ }
+ if (!strcmp(tag, "li")) { int k = find_open(h, "li", STOP_LIST); if (k >= 0) pop_to(h, k); }
+ if (!strcmp(tag, "dt") || !strcmp(tag, "dd")) { int k = find_open(h, "dt", STOP_LIST); if (k < 0) k = find_open(h, "dd", STOP_LIST); if (k >= 0) pop_to(h, k); }
+ if (!strcmp(tag, "td") || !strcmp(tag, "th")) {
+ int k = find_open(h, "td", STOP_TABLE); if (k < 0) k = find_open(h, "th", STOP_TABLE);
+ if (k >= 0) pop_to(h, k);
+ }
+ if (!strcmp(tag, "tr")) {
+ int k = find_open(h, "tr", STOP_TABLE);
+ if (k >= 0) pop_to(h, k);
+ }
+ if (!strcmp(tag, "a")) { int k = find_open(h, "a", STOP_CELL); if (k >= 0) pop_to(h, k); }
+ /* stray td inside a table without tr: open a tr */
+ if ((!strcmp(tag, "td") || !strcmp(tag, "th")) && h->nfr > 0 && h->fr[h->nfr - 1].kind == 't' && h->nopen < (int)(sizeof h->open / sizeof h->open[0])) {
+ Attr none[1];
+ open_tag(h, "tr", none, 0, 0);
+ }
+
+ IStyle saved = h->cur;
+ BStyle bs;
+ memset(&bs, 0, sizeof bs);
+ legacy_attrs(a, na, &h->cur, &bs, tag);
+ const char *style = attr(a, na, "style");
+ if (style) apply_css(style, strlen(style), &h->cur, &bs);
+
+ if (bs.hidden || kind == K_DROP) {
+ h->cur = saved;
+ /* skipped up to its close: the main loop does it with skip */
+ if (!is_void && !selfclose) {
+ if (h->nopen < (int)(sizeof h->open / sizeof h->open[0])) {
+ Open *o = &h->open[h->nopen++];
+ snprintf(o->tag, sizeof o->tag, "%s", tag);
+ o->is = saved;
+ o->frame = -1; /* marker: skip */
+ }
+ }
+ return;
+ }
+
+ /* per-tag styles */
+ if (!strcmp(tag, "b") || !strcmp(tag, "strong") || !strcmp(tag, "th")) h->cur.b = 1;
+ else if (!strcmp(tag, "i") || !strcmp(tag, "em") || !strcmp(tag, "cite") || !strcmp(tag, "var") || !strcmp(tag, "dfn")) h->cur.i = 1;
+ else if (!strcmp(tag, "u") || !strcmp(tag, "ins")) h->cur.u = 1;
+ else if (!strcmp(tag, "s") || !strcmp(tag, "strike") || !strcmp(tag, "del")) h->cur.st = 1;
+ else if (!strcmp(tag, "code") || !strcmp(tag, "tt") || !strcmp(tag, "kbd") || !strcmp(tag, "samp")) h->cur.mono = 1;
+ else if (!strcmp(tag, "pre") || !strcmp(tag, "listing")) { h->cur.mono = 1; h->cur.pre = 1; }
+ else if (!strcmp(tag, "small") || !strcmp(tag, "sub") || !strcmp(tag, "sup")) h->cur.fs = (saved.fs > 0 ? saved.fs : 14) * 0.85;
+ else if (!strcmp(tag, "big")) h->cur.fs = (saved.fs > 0 ? saved.fs : 14) * 1.2;
+ else if (tag[0] == 'h' && tag[1] >= '1' && tag[1] <= '6' && !tag[2]) {
+ static const int hs[] = { 24, 20, 17, 15, 14, 13 };
+ h->cur.b = 1;
+ if (!style || !strcasestr(style, "font-size")) h->cur.fs = hs[tag[1] - '1'];
+ if (bs.mt <= 0) bs.mt = 10;
+ if (bs.mb <= 0) bs.mb = 6;
+ } else if (!strcmp(tag, "p")) { if (bs.mt <= 0 && !(style && strcasestr(style, "margin"))) bs.mt = 6; if (bs.mb <= 0 && !(style && strcasestr(style, "margin"))) bs.mb = 6; }
+ else if (!strcmp(tag, "blockquote")) { if (!bs.has_bl) { bs.bl = 3; bs.blc = 0x88888888; bs.has_bl = 1; } if (!bs.has_pad) { bs.pad[3] = 10; bs.has_pad = 1; } bs.mt = bs.mt > 0 ? bs.mt : 4; bs.mb = bs.mb > 0 ? bs.mb : 4; }
+ else if (!strcmp(tag, "center")) bs.align = 'c';
+ else if (!strcmp(tag, "ul") || !strcmp(tag, "ol") || !strcmp(tag, "menu") || !strcmp(tag, "dd")) { if (!bs.has_pad) { bs.pad[3] = 22; bs.has_pad = 1; } }
+
+ if (!strcmp(tag, "body") || !strcmp(tag, "html")) {
+ if (bs.has_bg && !h->has_root_bg) { h->root_bg = bs.bg; h->has_root_bg = 1; }
+ bs.has_bg = 0;
+ }
+
+ if (!strcmp(tag, "br")) {
+ flush_run(h);
+ if (h->st.nodes++ < HTML_MAX_NODES) { frame_sep(h); jb_raw(&h->out, "{\"t\":\"br\"}"); }
+ h->space = 0;
+ h->line_start = 1;
+ h->cur = saved;
+ return;
+ }
+ if (!strcmp(tag, "hr")) {
+ block_break(h);
+ if (h->st.nodes++ < HTML_MAX_NODES) { frame_sep(h); jb_raw(&h->out, "{\"t\":\"hr\"}"); }
+ h->cur = saved;
+ return;
+ }
+ if (!strcmp(tag, "img") || !strcmp(tag, "image")) { do_img(h, a, na, &bs); h->cur = saved; return; }
+ if (is_void) { h->cur = saved; return; }
+
+ if (!strcmp(tag, "a")) {
+ const char *href = attr(a, na, "href");
+ h->cur.link = -1;
+ if (href && href_ok(href) && h->nlinks < HTML_MAX_LINKS) {
+ Link *l = &h->links[h->nlinks];
+ memset(l, 0, sizeof *l);
+ l->href = strdup(href);
+ if (l->href) {
+ /* canonical form: no blanks or control characters anywhere (as browsers do) */
+ size_t o2 = 0;
+ for (char *c = l->href; *c; c++) if ((unsigned char)*c > 0x20 && *c != 0x7f) l->href[o2++] = *c;
+ l->href[o2] = 0;
+ h->cur.link = h->nlinks;
+ h->cur_link = h->nlinks;
+ h->nlinks++;
+ }
+ }
+ }
+
+ if (h->nopen >= (int)(sizeof h->open / sizeof h->open[0])) { h->cur = saved; return; }
+ Open *o = &h->open[h->nopen++];
+ snprintf(o->tag, sizeof o->tag, "%s", tag);
+ o->is = saved;
+ o->frame = 0;
+ o->list_n = 0;
+ o->ordered = !strcmp(tag, "ol");
+ if (kind == K_BLOCK) {
+ const char *t = "blk";
+ char extra[96] = "";
+ if (!strcmp(tag, "table")) {
+ t = "tbl";
+ const char *cp = attr(a, na, "cellpadding");
+ if (cp && hnum(cp, 0, 30, 0) > 0) snprintf(extra, sizeof extra, ",\"cp\":%d", hnum(cp, 0, 30, 0));
+ } else if (!strcmp(tag, "tr")) t = "tr";
+ else if (!strcmp(tag, "td") || !strcmp(tag, "th")) {
+ t = "td";
+ const char *cs = attr(a, na, "colspan");
+ if (cs && hnum(cs, 1, 50, 1) > 1) snprintf(extra, sizeof extra, ",\"cs\":%d", hnum(cs, 1, 50, 1));
+ } else if (!strcmp(tag, "li")) {
+ int lst = find_open(h, "ol", STOP_LIST);
+ int ul = find_open(h, "ul", STOP_LIST);
+ if (lst > ul) { h->open[lst].list_n++; snprintf(extra, sizeof extra, ",\"mk\":\"%d.\"", h->open[lst].list_n); }
+ else snprintf(extra, sizeof extra, ",\"mk\":\"•\"");
+ }
+ o->frame = open_frame(h, t, &bs, extra[0] ? extra : NULL);
+ }
+}
+
+static void close_tag(H *h, const char *tag) {
+ if (kind_of(tag) == K_IGNORE) return;
+ const char *const *stop = (!strcmp(tag, "td") || !strcmp(tag, "th") || !strcmp(tag, "tr")) ? STOP_TABLE :
+ !strcmp(tag, "table") ? NULL : STOP_CELL;
+ if (!strcmp(tag, "td") || !strcmp(tag, "th") || !strcmp(tag, "tr")) {
+ int k = find_open(h, tag, stop);
+ if (k >= 0) pop_to(h, k);
+ return;
+ }
+ if (!strcmp(tag, "br")) { Attr none[1]; open_tag(h, "br", none, 0, 1); return; } /* </br> = <br> */
+ int k = find_open(h, tag, stop);
+ if (k >= 0) pop_to(h, k);
+}
+
+/* ---- tokenizer ---- */
+
+static int name_char(unsigned char c) { return isalnum(c) || c == '-' || c == '_' || c == ':'; }
+
+char *html_sanitize(const char *s, size_t len, size_t *olen, HtmlStats *stats, HtmlData *data, int *ndata) {
+ H *h = calloc(1, sizeof *h);
+ if (!h) return NULL;
+ if (len > HTML_MAX_INPUT) { len = HTML_MAX_INPUT; h->st.truncated = 1; }
+ jb_init(&h->out);
+ h->cur.link = -1;
+ h->cur_link = -1;
+ h->line_start = 1;
+ h->data = data;
+ jb_raw(&h->out, "{\"v\":1,\"blocks\":[");
+ h->nfr = 1;
+ h->fr[0].kids = 0;
+ h->fr[0].kind = 'r';
+ /* decoded attribute values live until the end (data: references them) */
+ char **keep = NULL;
+ size_t nkeep = 0, capkeep = 0;
+ Attr at[MAX_ATTRS];
+ size_t i = 0;
+ while (i < len) {
+ /* inside something being skipped? */
+ int skipping = h->nopen && h->open[h->nopen - 1].frame == -1;
+ if (s[i] != '<') {
+ size_t a = i;
+ while (i < len && s[i] != '<') i++;
+ if (skipping) continue;
+ /* text: entities → UTF-8 */
+ Buf t = { 0 };
+ for (size_t k = a; k < i;) {
+ if (s[k] == '&') {
+ size_t used;
+ uint32_t cp = entity(s, i, k, &used);
+ if (cp && used) { char u[4]; bput(&t, u, (size_t)put_cp(u, cp)); k += used; continue; }
+ bput(&t, "&", 1);
+ k++;
+ continue;
+ }
+ size_t k0 = k;
+ while (k < i && s[k] != '&') k++;
+ bput(&t, s + k0, k - k0);
+ }
+ if (t.n) add_text(h, t.p, t.n);
+ free(t.p);
+ continue;
+ }
+ /* comments, doctype, CDATA, instructions */
+ if (i + 3 < len && !memcmp(s + i, "<!--", 4)) {
+ const char *e = NULL;
+ for (size_t k = i + 4; k + 2 < len + 0 && k + 3 <= len; k++) if (s[k] == '-' && s[k + 1] == '-' && s[k + 2] == '>') { e = s + k; break; }
+ i = e ? (size_t)(e - s) + 3 : len;
+ continue;
+ }
+ if (i + 1 < len && (s[i + 1] == '!' || s[i + 1] == '?')) {
+ const char *e = memchr(s + i, '>', len - i);
+ i = e ? (size_t)(e - s) + 1 : len;
+ continue;
+ }
+ int closing = i + 1 < len && s[i + 1] == '/';
+ size_t k = i + 1 + (size_t)closing;
+ if (k >= len || !isalpha((unsigned char)s[k])) {
+ /* stray "<": it is text */
+ if (!skipping) add_text(h, "<", 1);
+ i++;
+ continue;
+ }
+ char tag[16];
+ size_t tn = 0;
+ while (k < len && name_char((unsigned char)s[k])) { if (tn + 1 < sizeof tag) tag[tn++] = (char)tolower((unsigned char)s[k]); k++; }
+ tag[tn] = 0;
+ /* attributes */
+ int na = 0, selfclose = 0;
+ while (k < len && s[k] != '>') {
+ while (k < len && (isspace((unsigned char)s[k]) || s[k] == '/')) { if (s[k] == '/' && k + 1 < len && s[k + 1] == '>') selfclose = 1; k++; }
+ if (k >= len || s[k] == '>') break;
+ size_t an = k;
+ while (k < len && !isspace((unsigned char)s[k]) && s[k] != '=' && s[k] != '>' && s[k] != '/') k++;
+ size_t anl = k - an;
+ while (k < len && isspace((unsigned char)s[k])) k++;
+ const char *v = NULL;
+ size_t vn = 0;
+ if (k < len && s[k] == '=') {
+ k++;
+ while (k < len && isspace((unsigned char)s[k])) k++;
+ if (k < len && (s[k] == '"' || s[k] == '\'')) {
+ char q = s[k++];
+ v = s + k;
+ while (k < len && s[k] != q) k++;
+ vn = (size_t)(s + k - v);
+ if (k < len) k++;
+ } else {
+ v = s + k;
+ while (k < len && !isspace((unsigned char)s[k]) && s[k] != '>') k++;
+ vn = (size_t)(s + k - v);
+ }
+ }
+ if (!anl) { if (k < len && s[k] != '>') k++; continue; }
+ if (na < MAX_ATTRS && anl < sizeof at[0].name && !closing && !skipping) {
+ Attr *x = &at[na];
+ for (size_t c = 0; c < anl; c++) x->name[c] = (char)tolower((unsigned char)s[an + c]);
+ x->name[anl] = 0;
+ /* no events (on*) or anything unused */
+ if (!strncmp(x->name, "on", 2)) continue;
+ x->v = v; x->vn = vn;
+ x->dec = v ? decode_attr(v, vn) : calloc(1, 1);
+ if (!x->dec) continue;
+ if (nkeep == capkeep) { capkeep = capkeep ? capkeep * 2 : 64; char **nk = realloc(keep, capkeep * sizeof *nk); if (!nk) { free(x->dec); continue; } keep = nk; }
+ keep[nkeep++] = x->dec;
+ na++;
+ }
+ }
+ i = k < len ? k + 1 : len;
+ if (skipping) {
+ /* only the close of what is being skipped matters (with same-name nesting) */
+ Open *top = &h->open[h->nopen - 1];
+ if (!strcmp(tag, top->tag)) {
+ if (closing) { if (top->list_n > 0) top->list_n--; else { h->nopen--; h->cur = top->is; } }
+ else if (!selfclose && !tag_is(tag, T_VOID)) top->list_n++;
+ } else if (!closing && !strcmp(top->tag, "head") && !strcmp(tag, "body")) {
+ h->nopen--; /* unclosed <head> */
+ open_tag(h, tag, at, na, selfclose);
+ }
+ continue;
+ }
+ if (closing) { close_tag(h, tag); continue; }
+ if (tag_is(tag, T_RAW)) {
+ /* skip up to </tag> without interpreting anything */
+ size_t e = i;
+ for (;;) {
+ const char *lt = memchr(s + e, '<', len - e);
+ if (!lt) { e = len; break; }
+ e = (size_t)(lt - s);
+ if (e + 2 + tn <= len && s[e + 1] == '/' && !strncasecmp(s + e + 2, tag, tn) && (e + 2 + tn == len || !name_char((unsigned char)s[e + 2 + tn]))) {
+ const char *gt = memchr(s + e, '>', len - e);
+ e = gt ? (size_t)(gt - s) + 1 : len;
+ break;
+ }
+ e++;
+ }
+ i = e;
+ continue;
+ }
+ open_tag(h, tag, at, na, selfclose);
+ }
+ pop_to(h, 0);
+ flush_run(h);
+ while (h->nfr > 1) close_frame(h);
+ jb_raw(&h->out, "]");
+ if (h->has_root_bg) color_json(&h->out, "bg", h->root_bg);
+ if (h->colors || h->has_root_bg) jb_raw(&h->out, ",\"colors\":1");
+ jb_raw(&h->out, ",\"remote\":[");
+ for (int r = 0; r < h->nremote; r++) { if (r) jb_raw(&h->out, ","); jb_str(&h->out, h->remote[r]); free(h->remote[r]); }
+ jb_raw(&h->out, "],\"links\":[");
+ for (int l = 0; l < h->nlinks; l++) {
+ if (l) jb_raw(&h->out, ",");
+ jb_raw(&h->out, "{\"h\":");
+ jb_str(&h->out, h->links[l].href);
+ if (h->links[l].warn) {
+ jb_raw(&h->out, ",\"w\":");
+ jb_str(&h->out, html_link_warning(h->links[l].text.p ? h->links[l].text.p : "", h->links[l].href));
+ jb_raw(&h->out, ",\"txt\":");
+ jb_str(&h->out, h->links[l].text.p ? h->links[l].text.p : "");
+ }
+ jb_raw(&h->out, "}");
+ free(h->links[l].href);
+ free(h->links[l].text.p);
+ }
+ jb_printf(&h->out, "],\"stats\":{\"remote\":%d,\"trackers\":%d,\"warn\":%d,\"cid\":%d,\"data\":%d,\"nodes\":%d,\"truncated\":%d}}",
+ h->st.remote, h->st.trackers, h->st.warn, h->st.cid, h->st.data, h->st.nodes, h->st.truncated);
+ free(h->run.p);
+ if (stats) *stats = h->st;
+ /* data: points into the decoded copies: copy them before freeing */
+ if (data && ndata) {
+ for (int d = 0; d < h->ndata; d++) {
+ char *cp = malloc(data[d].n + 1);
+ if (cp) { memcpy(cp, data[d].p, data[d].n); cp[data[d].n] = 0; }
+ data[d].p = cp;
+ if (!cp) data[d].n = 0;
+ }
+ *ndata = h->ndata;
+ }
+ for (size_t k2 = 0; k2 < nkeep; k2++) free(keep[k2]);
+ free(keep);
+ char *r = h->out.oom ? NULL : h->out.p;
+ if (olen) *olen = r ? h->out.n : 0;
+ if (!r) jb_free(&h->out);
+ free(h);
+ return r;
+}
+
+char *html_to_text(const char *s, size_t len, size_t *olen) {
+ Buf b = { 0 };
+ int space = 0;
+ int skip = 0;
+ char skiptag[16] = "";
+ for (size_t i = 0; i < len;) {
+ if (s[i] == '<') {
+ size_t k = i + 1;
+ int closing = k < len && s[k] == '/';
+ if (closing) k++;
+ char tag[16];
+ size_t tn = 0;
+ while (k < len && name_char((unsigned char)s[k])) { if (tn + 1 < sizeof tag) tag[tn++] = (char)tolower((unsigned char)s[k]); k++; }
+ tag[tn] = 0;
+ int comment = i + 3 < len && !memcmp(s + i, "<!--", 4);
+ if (comment) {
+ size_t e = i + 4;
+ while (e + 2 < len && !(s[e] == '-' && s[e + 1] == '-' && s[e + 2] == '>')) e++;
+ i = e + 3 < len ? e + 3 : len;
+ continue;
+ }
+ const char *gt = memchr(s + k, '>', len - k);
+ i = gt ? (size_t)(gt - s) + 1 : len;
+ if (skip) { if (closing && !strcmp(tag, skiptag)) skip = 0; continue; }
+ if (!closing && (tag_is(tag, T_RAW) || !strcmp(tag, "head"))) { skip = 1; snprintf(skiptag, sizeof skiptag, "%s", tag); continue; }
+ if (!strcmp(tag, "br") || !strcmp(tag, "p") || !strcmp(tag, "div") || !strcmp(tag, "tr") || !strcmp(tag, "li") || (tag[0] == 'h' && isdigit((unsigned char)tag[1])) || !strcmp(tag, "table")) {
+ if (b.n && b.p[b.n - 1] != '\n') bput(&b, "\n", 1);
+ space = 0;
+ } else if (!strcmp(tag, "td") || !strcmp(tag, "th")) space = 1;
+ continue;
+ }
+ if (skip) { i++; continue; }
+ uint32_t cp;
+ if (s[i] == '&') {
+ size_t used;
+ cp = entity(s, len, i, &used);
+ if (cp && used) i += used; else { cp = '&'; i++; }
+ } else cp = next_cp(s, len, &i);
+ if (invisible(cp)) continue;
+ if (cp == ' ' || cp == '\t' || cp == '\n' || cp == '\r' || cp == 0xa0) { space = 1; continue; }
+ if (cp < 0x20) continue;
+ if (space && b.n && b.p[b.n - 1] != '\n') bput(&b, " ", 1);
+ space = 0;
+ char t[4];
+ bput(&b, t, (size_t)put_cp(t, cp));
+ }
+ while (b.n && (b.p[b.n - 1] == '\n' || b.p[b.n - 1] == ' ')) b.p[--b.n] = 0;
+ if (!b.p) b.p = calloc(1, 1);
+ if (olen) *olen = b.p ? b.n : 0;
+ return b.p;
+}
diff --git a/server/src/mail/html.h b/server/src/mail/html.h
index f51fb25..5024d3c 100644
--- a/server/src/mail/html.h
+++ b/server/src/mail/html.h
@@ -1,24 +1,24 @@
-/* html.h — el HTML del correo, sin navegador (ver docs/MAIL.md, «HTML sin ejecutar nada»).
+/* html.h — mail HTML, without a browser (see docs/MAIL.md, "HTML without executing anything").
*
- * LordOS no tiene motor web: el HTML de un mensaje nunca se ejecuta ni se «carga». Este
- * sanitizador lo lee con un tokenizador propio y tolerante y arma un árbol chico, en JSON, que
- * Mail dibuja con sus vistas nativas (View/Text/Image):
+ * LordOS has no web engine: a message's HTML is never executed or "loaded". This
+ * sanitizer reads it with an in-house, lenient tokenizer and builds a small JSON tree that
+ * Mail renders with its native views (View/Text/Image):
*
- * {"v":1,"bg":"#fff","blocks":[nodo…],"remote":["https://…"],"links":[{"h":"…","w":"deceptive"}],
+ * {"v":1,"bg":"#fff","blocks":[node…],"remote":["https://…"],"links":[{"h":"…","w":"deceptive"}],
* "stats":{"remote":3,"trackers":1,"warn":1,"cid":2,"data":0}}
- * nodo: {"t":"blk","s":{…},"c":[…]} bloque (div, p, h1-6, blockquote, pre, center, li)
+ * node: {"t":"blk","s":{…},"c":[…]} block (div, p, h1-6, blockquote, pre, center, li)
* {"t":"tbl","s":{…},"c":[{"t":"tr","c":[{"t":"td","s":{…},"c":[…]}]}]}
* {"t":"img","src":"cid:x"|"r:N"|"d:N","w":600,"h":200,"alt":"…","l":N}
* {"t":"hr"} {"t":"br"}
- * {"t":"x","x":"texto","s":{b,i,u,st,mono,c,bg,fs},"l":N} texto con estilo; l = índice del enlace
+ * {"t":"x","x":"text","s":{b,i,u,st,mono,c,bg,fs},"l":N} styled text; l = link index
*
- * Qué queda afuera, siempre: script, style, iframe, object, embed, form y sus controles, svg,
- * math, audio/video, comentarios, <!DOCTYPE>, eventos (on*), url() de CSS, javascript:/vbscript:/
- * data: en los enlaces (los enlaces solo pueden ser http, https y mailto) y todo lo de display:none.
- * Las imágenes remotas no se piden acá: quedan en "remote" y Mail decide (bloqueadas de entrada).
- * Las de 1×1 o 2×2 (píxeles de seguimiento) se cuentan en "trackers" y no se muestran nunca.
- * Enlaces engañosos: si el texto visible parece una dirección web y su dominio no es el del href
- * (o el href lleva usuario@, una IP o un esquema raro), el enlace sale con "w". */
+ * Always stripped: script, style, iframe, object, embed, form and its controls, svg,
+ * math, audio/video, comments, <!DOCTYPE>, events (on*), CSS url(), javascript:/vbscript:/
+ * data: in links (links may only be http, https and mailto) and everything under display:none.
+ * Remote images are not fetched here: they go into "remote" and Mail decides (blocked by default).
+ * 1×1 or 2×2 ones (tracking pixels) are counted in "trackers" and never shown.
+ * Deceptive links: if the visible text looks like a web address and its domain is not the href's
+ * (or the href contains user@, an IP or an odd scheme), the link is emitted with "w". */
#ifndef LORD_MAIL_HTML_H
#define LORD_MAIL_HTML_H
@@ -32,13 +32,18 @@
typedef struct { int remote, trackers, warn, cid, data, nodes, truncated; } HtmlStats;
-/* JSON del árbol (malloc, siempre válido) o NULL sin memoria. */
-char *html_sanitize(const char *html, size_t len, size_t *olen, HtmlStats *st);
-/* Texto plano del HTML (para la vista previa, la búsqueda y la parte text/plain al responder). */
+/* data: (base64) images found: they point into the input; "d:N" is the Nth one. */
+typedef struct { const char *p; size_t n; char type[16]; } HtmlData;
+#define HTML_MAX_DATA 64
+
+/* JSON of the tree (malloc, always valid) or NULL when out of memory. data (optional) receives up to
+ * HTML_MAX_DATA data: images and ndata how many. */
+char *html_sanitize(const char *html, size_t len, size_t *olen, HtmlStats *st, HtmlData *data, int *ndata);
+/* Plain text of the HTML (for the preview, search and the text/plain part when replying). */
char *html_to_text(const char *html, size_t len, size_t *olen);
-/* Dominio (host en minúsculas, sin "www.") de una URL http(s); "" si no tiene. */
+/* Domain (lowercase host, without "www.") of an http(s) URL; "" if none. */
void html_url_host(const char *url, char *out, size_t cap);
-/* ¿El texto visible de un enlace engaña sobre su destino? Devuelve un motivo o NULL. */
+/* Does a link's visible text mislead about its destination? Returns a reason or NULL. */
const char *html_link_warning(const char *text, const char *href);
#endif
diff --git a/server/src/mail/html_entities.h b/server/src/mail/html_entities.h
index f126f57..835b611 100644
--- a/server/src/mail/html_entities.h
+++ b/server/src/mail/html_entities.h
@@ -1,5 +1,5 @@
-/* html_entities.h — entidades con nombre de HTML5 (solo las de un carácter), generadas desde
-* html.entities de Python. Ordenadas por nombre para búsqueda binaria. No editar a mano. */
+/* html_entities.h — HTML5 named entities (single-character ones only), generated from
+* Python's html.entities. Sorted by name for binary search. Do not edit by hand. */
#ifndef LORD_MAIL_HTML_ENTITIES_H
#define LORD_MAIL_HTML_ENTITIES_H
#include <stdint.h>
diff --git a/server/src/mail/http.c b/server/src/mail/http.c
new file mode 100644
index 0000000..2dfae36
--- /dev/null
+++ b/server/src/mail/http.c
@@ -0,0 +1,131 @@
+/* http.c — see http.h. */
+#include "http.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <time.h>
+
+static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
+
+int http_split_url(const char *url, int *tls, char *host, size_t hcap, int *port, char *path, size_t pcap) {
+ if (!url) return -1;
+ const char *p;
+ if (!strncasecmp(url, "https://", 8)) { *tls = 1; p = url + 8; *port = 443; }
+ else if (!strncasecmp(url, "http://", 7)) { *tls = 0; p = url + 7; *port = 80; }
+ else return -1;
+ const char *e = p + strcspn(p, "/?#");
+ const char *at = memchr(p, '@', (size_t)(e - p));
+ if (at) return -1; /* no credentials in URLs */
+ const char *colon = memchr(p, ':', (size_t)(e - p));
+ size_t hl = (size_t)((colon ? colon : e) - p);
+ if (!hl || hl >= hcap) return -1;
+ for (size_t i = 0; i < hl; i++) {
+ unsigned char c = (unsigned char)p[i];
+ if (!isalnum(c) && c != '-' && c != '.') return -1;
+ host[i] = (char)tolower(c);
+ }
+ host[hl] = 0;
+ if (colon) { *port = atoi(colon + 1); if (*port <= 0 || *port > 65535) return -1; }
+ const char *path0 = *e == '/' ? e : "/";
+ size_t pl = strcspn(path0, "#");
+ if (*e == '?') { snprintf(path, pcap, "/%.*s", (int)strcspn(e, "#"), e); return 0; }
+ if (pl >= pcap) return -1;
+ memcpy(path, path0, pl);
+ path[pl] = 0;
+ for (char *c = path; *c; c++) if ((unsigned char)*c <= 0x20 || *c == 0x7f) return -1;
+ return 0;
+}
+
+void http_resp_free(HttpResp *r) { free(r->body); memset(r, 0, sizeof *r); }
+
+static void hdr_copy(const char *line, const char *name, char *out, size_t cap) {
+ size_t n = strlen(name);
+ if (strncasecmp(line, name, n) || line[n] != ':') return;
+ const char *v = line + n + 1;
+ while (*v == ' ' || *v == '\t') v++;
+ size_t l = strcspn(v, "\r\n");
+ if (l >= cap) l = cap - 1;
+ memcpy(out, v, l);
+ out[l] = 0;
+}
+
+int http_request(Conn *c, const char *method, const char *host, const char *path, const char *extra, const char *body, size_t blen,
+ size_t max_body, int deadline_ms, HttpResp *out) {
+ memset(out, 0, sizeof *out);
+ double end = now_ms() + (deadline_ms > 0 ? deadline_ms : 60000);
+ if (conn_printf(c, "%s %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: LordOS-Mail/1.0\r\nAccept-Encoding: identity\r\n%sContent-Length: %zu\r\n\r\n",
+ method, path, host, extra ? extra : "", body ? blen : 0)) return -1;
+ if (body && blen && conn_write(c, body, blen)) return -1;
+ size_t ll;
+ char *line = conn_line(c, &ll, 8192);
+ if (!line) return -1;
+ int maj = 0, mn = 0;
+ if (sscanf(line, "HTTP/%d.%d %d", &maj, &mn, &out->status) != 3) { free(line); return -1; }
+ free(line);
+ long long clen = -1;
+ int chunked = 0, close_after = maj == 1 && mn == 0;
+ for (int n = 0; n < 200; n++) {
+ if (now_ms() > end) return -1;
+ line = conn_line(c, &ll, 16384);
+ if (!line) return -1;
+ if (!strcmp(line, "\r\n") || !strcmp(line, "\n")) { free(line); break; }
+ char v[64] = "";
+ hdr_copy(line, "Content-Length", v, sizeof v);
+ if (v[0]) clen = atoll(v);
+ v[0] = 0;
+ hdr_copy(line, "Transfer-Encoding", v, sizeof v);
+ if (strcasestr(v, "chunked")) chunked = 1;
+ v[0] = 0;
+ hdr_copy(line, "Connection", v, sizeof v);
+ if (strcasestr(v, "close")) close_after = 1;
+ hdr_copy(line, "Location", out->location, sizeof out->location);
+ hdr_copy(line, "ETag", out->etag, sizeof out->etag);
+ hdr_copy(line, "Content-Type", out->content_type, sizeof out->content_type);
+ free(line);
+ }
+ size_t cap = 0;
+ out->blen = 0;
+ if (!strcasecmp(method, "HEAD") || out->status == 204 || out->status == 304 || (out->status >= 100 && out->status < 200)) clen = 0;
+ if (chunked) {
+ for (;;) {
+ if (now_ms() > end) { http_resp_free(out); return -1; }
+ line = conn_line(c, &ll, 1024);
+ if (!line) { http_resp_free(out); return -1; }
+ unsigned long long sz = strtoull(line, NULL, 16);
+ free(line);
+ if (sz == 0) {
+ /* trailers until the empty line */
+ while ((line = conn_line(c, &ll, 8192))) { int done = !strcmp(line, "\r\n") || !strcmp(line, "\n"); free(line); if (done) break; }
+ break;
+ }
+ if (out->blen + sz > max_body) { http_resp_free(out); return -2; }
+ if (conn_read_n(c, (size_t)sz, &out->body, &out->blen, &cap)) { http_resp_free(out); return -1; }
+ line = conn_line(c, &ll, 16);
+ free(line);
+ }
+ } else if (clen >= 0) {
+ if ((unsigned long long)clen > max_body) { http_resp_free(out); return -2; }
+ if (clen && conn_read_n(c, (size_t)clen, &out->body, &out->blen, &cap)) { http_resp_free(out); return -1; }
+ } else {
+ /* until the server closes */
+ char tmp[16384];
+ for (;;) {
+ if (now_ms() > end) { http_resp_free(out); return -1; }
+ ssize_t r = conn_read_some(c, tmp, sizeof tmp);
+ if (r <= 0) break;
+ if (out->blen + (size_t)r > max_body) { http_resp_free(out); return -2; }
+ size_t want = (size_t)r;
+ if (out->blen + want + 1 > cap) { cap = (out->blen + want + 1) * 2; char *nb = realloc(out->body, cap); if (!nb) { http_resp_free(out); return -1; } out->body = nb; }
+ memcpy(out->body + out->blen, tmp, want);
+ out->blen += want;
+ }
+ close_after = 1;
+ }
+ if (!out->body) { out->body = calloc(1, 1); }
+ else out->body[out->blen] = 0;
+ out->keep_alive = !close_after;
+ return 0;
+}
diff --git a/server/src/mail/http.h b/server/src/mail/http.h
new file mode 100644
index 0000000..b841466
--- /dev/null
+++ b/server/src/mail/http.h
@@ -0,0 +1,27 @@
+/* http.h — a small HTTP/1.1 client for lord-maild: WebDAV (CalDAV, CardDAV) and remote images.
+ * Responses are bounded (max body bytes), chunked transfer coding is decoded, and every read has
+ * a deadline. The connection comes from lord-server (see net.h). */
+#ifndef LORD_MAIL_HTTP_H
+#define LORD_MAIL_HTTP_H
+
+#include <stddef.h>
+#include "net.h"
+
+typedef struct {
+ int status;
+ char location[1024];
+ char etag[256];
+ char content_type[128];
+ char *body; /* malloc, NUL-terminated */
+ size_t blen;
+ int keep_alive;
+} HttpResp;
+
+/* URL pieces: https only unless http is allowed. 0 ok. */
+int http_split_url(const char *url, int *tls, char *host, size_t hcap, int *port, char *path, size_t pcap);
+/* One request on an open connection. extra_headers: "Name: value\r\n…" or NULL. 0 ok (any status). */
+int http_request(Conn *c, const char *method, const char *host, const char *path, const char *extra_headers,
+ const char *body, size_t blen, size_t max_body, int deadline_ms, HttpResp *out);
+void http_resp_free(HttpResp *r);
+
+#endif
diff --git a/server/src/mail/ical.c b/server/src/mail/ical.c
new file mode 100644
index 0000000..77410d8
--- /dev/null
+++ b/server/src/mail/ical.c
@@ -0,0 +1,1070 @@
+/* ical.c — see ical.h. */
+#include "ical.h"
+#include "../ui/tzif.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+/* Bounded integer from untrusted text (strtol with range and end checks; never atoi).
+ * Leading sign allowed; parsing stops at the first non-digit (reported in *end if given). */
+static int bnum(const char *s, long lo, long hi, long dflt, const char **end) {
+ char *e;
+ errno = 0;
+ long v = strtol(s ? s : "", &e, 10);
+ if (end) *end = e;
+ if (!s || e == s || errno == ERANGE || v < lo || v > hi) return (int)dflt;
+ return (int)v;
+}
+
+/* ---- content lines ---- */
+
+static IcComp *comp_new(const char *name, IcComp *parent) {
+ IcComp *c = calloc(1, sizeof *c);
+ if (!c) return NULL;
+ snprintf(c->name, sizeof c->name, "%s", name);
+ for (char *p = c->name; *p; p++) *p = (char)toupper((unsigned char)*p);
+ c->parent = parent;
+ if (parent) { if (parent->last) parent->last->next = c; else parent->kid = c; parent->last = c; }
+ return c;
+}
+
+void ic_free(IcComp *root) {
+ IcComp *n = root;
+ while (n) {
+ if (n->kid) { IcComp *k = n->kid; n->kid = NULL; n = k; continue; }
+ IcComp *next = n->next, *parent = n->parent;
+ int last = n == root;
+ for (int i = 0; i < n->nprops; i++) { free(n->props[i].params); free(n->props[i].value); }
+ free(n->props);
+ free(n);
+ if (last) break;
+ n = next ? next : parent;
+ }
+}
+
+static int add_prop(IcComp *c, const char *line, size_t n, long *total) {
+ if (++*total > IC_MAX_PROPS * 50) return -1;
+ if (c->nprops >= IC_MAX_PROPS) return 0;
+ /* name[;params]:value (':' inside a quoted parameter does not count) */
+ size_t i = 0;
+ while (i < n && line[i] != ';' && line[i] != ':') i++;
+ if (i == n || i == 0) return 0;
+ size_t name_end = i;
+ size_t params_start = i, colon = i;
+ if (line[i] == ';') {
+ int q = 0;
+ for (colon = i; colon < n; colon++) { if (line[colon] == '"') q = !q; else if (line[colon] == ':' && !q) break; }
+ if (colon >= n) return 0;
+ params_start = i + 1;
+ }
+ if (c->nprops == c->capprops) {
+ int nc = c->capprops ? c->capprops * 2 : 16;
+ IcProp *np = realloc(c->props, (size_t)nc * sizeof *np);
+ if (!np) return -1;
+ c->props = np;
+ c->capprops = nc;
+ }
+ IcProp *p = &c->props[c->nprops];
+ memset(p, 0, sizeof *p);
+ /* group prefix ("item1.EMAIL") */
+ const char *nm = line;
+ size_t nl = name_end;
+ const char *dot = memchr(line, '.', name_end);
+ if (dot) {
+ size_t gl = (size_t)(dot - line);
+ if (gl >= sizeof p->group) gl = sizeof p->group - 1;
+ memcpy(p->group, line, gl);
+ nm = dot + 1;
+ nl = name_end - (size_t)(nm - line);
+ }
+ if (nl >= sizeof p->name) nl = sizeof p->name - 1;
+ for (size_t k = 0; k < nl; k++) p->name[k] = (char)toupper((unsigned char)nm[k]);
+ p->name[nl] = 0;
+ size_t pl = colon > params_start ? colon - params_start : 0;
+ p->params = malloc(pl + 1);
+ p->value = malloc(n - colon);
+ if (!p->params || !p->value) { free(p->params); free(p->value); return -1; }
+ memcpy(p->params, line + params_start, pl);
+ p->params[pl] = 0;
+ memcpy(p->value, line + colon + 1, n - colon - 1);
+ p->value[n - colon - 1] = 0;
+ c->nprops++;
+ return 0;
+}
+
+IcComp *ic_parse(const char *s, size_t len, const char **err) {
+ IcComp *root = comp_new("", NULL);
+ if (!root) { if (err) *err = "memory"; return NULL; }
+ IcComp *cur = root;
+ int depth = 0;
+ long lines = 0, total = 0;
+ char *logical = NULL;
+ size_t ll = 0, lcap = 0;
+ size_t i = 0;
+ const char *e = NULL;
+ if (len >= 3 && (unsigned char)s[0] == 0xef && (unsigned char)s[1] == 0xbb && (unsigned char)s[2] == 0xbf) i = 3;
+ for (;;) {
+ /* next physical line */
+ int have = i < len;
+ size_t a = i, b = i;
+ if (have) {
+ while (b < len && s[b] != '\n') b++;
+ i = b < len ? b + 1 : len;
+ if (b > a && s[b - 1] == '\r') b--;
+ if (++lines > IC_MAX_LINES) { e = "too many lines"; goto fail; }
+ }
+ int cont = have && b > a && (s[a] == ' ' || s[a] == '\t');
+ /* vCard 2.1: quoted-printable soft line break ("=" at the end) */
+ int qp = 0;
+ if (have && !cont && ll && logical[ll - 1] == '=') {
+ size_t cl = 0;
+ while (cl < ll && logical[cl] != ':') cl++;
+ for (size_t k = 0; k + 16 <= cl; k++) if (!strncasecmp(logical + k, "QUOTED-PRINTABLE", 16)) { qp = 1; break; }
+ }
+ if (cont || qp) {
+ size_t skip = cont ? 1 : 0;
+ size_t add = b - a - skip;
+ if (qp) ll--; /* drop the "=" */
+ if (ll + add + 1 > lcap) { size_t nc = (ll + add + 1) * 2; char *nl = realloc(logical, nc); if (!nl) { e = "memory"; goto fail; } logical = nl; lcap = nc; }
+ memcpy(logical + ll, s + a + skip, add);
+ ll += add;
+ continue;
+ }
+ /* the previous logical line is complete */
+ if (ll) {
+ if (ll >= 6 && !strncasecmp(logical, "BEGIN:", 6)) {
+ if (depth >= IC_MAX_DEPTH) { e = "too deep"; goto fail; }
+ char nm[24];
+ size_t n = ll - 6;
+ while (n && (logical[6 + n - 1] == ' ')) n--;
+ if (n >= sizeof nm) n = sizeof nm - 1;
+ memcpy(nm, logical + 6, n);
+ nm[n] = 0;
+ IcComp *c = comp_new(nm, cur);
+ if (!c) { e = "memory"; goto fail; }
+ cur = c;
+ depth++;
+ } else if (ll >= 4 && !strncasecmp(logical, "END:", 4)) {
+ char nm[24];
+ size_t n = ll - 4;
+ while (n && logical[4 + n - 1] == ' ') n--;
+ if (n >= sizeof nm) n = sizeof nm - 1;
+ memcpy(nm, logical + 4, n);
+ nm[n] = 0;
+ /* close up to the matching component (tolerates missing END lines) */
+ IcComp *m = cur;
+ while (m && m != root && strcasecmp(m->name, nm)) m = m->parent;
+ if (m && m != root) {
+ while (cur != m) { cur = cur->parent; depth--; }
+ cur = cur->parent;
+ depth--;
+ }
+ } else if (add_prop(cur, logical, ll, &total)) { e = "too many properties"; goto fail; }
+ }
+ ll = 0;
+ if (!have) break;
+ size_t add = b - a;
+ if (add + 1 > lcap) { size_t nc = (add + 1) * 2; char *nl = realloc(logical, nc); if (!nl) { e = "memory"; goto fail; } logical = nl; lcap = nc; }
+ memcpy(logical, s + a, add);
+ ll = add;
+ }
+ free(logical);
+ if (err) *err = NULL;
+ return root;
+fail:
+ free(logical);
+ ic_free(root);
+ if (err) *err = e;
+ return NULL;
+}
+
+IcProp *ic_prop(const IcComp *c, const char *name) {
+ for (int i = 0; c && i < c->nprops; i++) if (!strcmp(c->props[i].name, name)) return &c->props[i];
+ return NULL;
+}
+
+IcProp *ic_prop_next(const IcComp *c, const IcProp *after, const char *name) {
+ if (!c) return NULL;
+ int start = after ? (int)(after - c->props) + 1 : 0;
+ for (int i = start; i < c->nprops; i++) if (!strcmp(c->props[i].name, name)) return &c->props[i];
+ return NULL;
+}
+
+int ic_param(const IcProp *p, const char *name, char *out, size_t cap) {
+ if (cap) out[0] = 0;
+ if (!p || !p->params) return 0;
+ size_t nl = strlen(name);
+ const char *s = p->params;
+ while (*s) {
+ const char *a = s;
+ while (*s && *s != '=' && *s != ';') s++;
+ size_t kl = (size_t)(s - a);
+ int match = kl == nl && !strncasecmp(a, name, nl);
+ /* vCard 2.1: bare parameters ("TEL;WORK;VOICE:") count as TYPE */
+ if (*s != '=') {
+ if (!strcasecmp(name, "TYPE") && kl && cap) {
+ size_t cur = strlen(out);
+ if (cur + kl + 2 < cap) { if (cur) out[cur++] = ','; memcpy(out + cur, a, kl); out[cur + kl] = 0; }
+ if (*s == ';') s++;
+ continue;
+ }
+ if (*s == ';') s++;
+ continue;
+ }
+ s++;
+ size_t o = match && cap ? strlen(out) : 0;
+ if (match && o && o + 1 < cap) out[o++] = ',';
+ int q = 0;
+ while (*s && (q || *s != ';')) {
+ if (*s == '"') { q = !q; s++; continue; }
+ if (match && cap && o + 1 < cap) out[o++] = *s;
+ s++;
+ }
+ if (match && cap) { out[o] = 0; if (strcasecmp(name, "TYPE")) return 1; }
+ if (*s == ';') s++;
+ }
+ return cap && out[0];
+}
+
+void ic_unescape(const char *in, char *out, size_t cap) {
+ if (!cap) return;
+ size_t o = 0;
+ for (; in && *in && o + 1 < cap; in++) {
+ if (*in == '\\' && in[1]) {
+ in++;
+ if (*in == 'n' || *in == 'N') out[o++] = '\n';
+ else out[o++] = *in;
+ } else out[o++] = *in;
+ }
+ out[o] = 0;
+ /* do not cut a UTF-8 character */
+ while (o && ((unsigned char)out[o - 1] & 0xc0) == 0x80 && o + 1 >= cap) out[--o] = 0;
+}
+
+char *ic_unescape_dup(const char *in) {
+ size_t n = in ? strlen(in) : 0;
+ char *o = malloc(n + 1);
+ if (o) ic_unescape(in ? in : "", o, n + 1);
+ return o;
+}
+
+char *ic_escape(const char *in) {
+ size_t n = in ? strlen(in) : 0;
+ char *o = malloc(n * 2 + 1);
+ if (!o) return NULL;
+ size_t k = 0;
+ for (size_t i = 0; i < n; i++) {
+ char c = in[i];
+ if (c == '\r') continue;
+ if (c == '\n') { o[k++] = '\\'; o[k++] = 'n'; continue; }
+ if (c == '\\' || c == ',' || c == ';') o[k++] = '\\';
+ o[k++] = c;
+ }
+ o[k] = 0;
+ return o;
+}
+
+void ic_line(JBuf *b, const char *line) {
+ size_t n = strlen(line), col = 0;
+ for (size_t i = 0; i < n;) {
+ size_t k = 1;
+ unsigned char c = (unsigned char)line[i];
+ if (c >= 0xf0) k = 4; else if (c >= 0xe0) k = 3; else if (c >= 0xc0) k = 2;
+ if (i + k > n) k = n - i;
+ if (col + k > 75) { jb_raw(b, "\r\n "); col = 1; }
+ {
+ char t[5];
+ memcpy(t, line + i, k);
+ t[k] = 0;
+ jb_raw(b, t);
+ }
+ col += k;
+ i += k;
+ }
+ jb_raw(b, "\r\n");
+}
+
+/* ---- time ---- */
+
+int64_t ic_days_from_civil(int64_t y, int m, int d) {
+ y -= m <= 2;
+ int64_t era = (y >= 0 ? y : y - 399) / 400;
+ int64_t yoe = y - era * 400;
+ int64_t doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
+ int64_t doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
+ return era * 146097 + doe - 719468;
+}
+
+void ic_civil_from_days(int64_t z, int *y, int *m, int *d) {
+ z += 719468;
+ int64_t era = (z >= 0 ? z : z - 146096) / 146097;
+ int64_t doe = z - era * 146097;
+ int64_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
+ int64_t yy = yoe + era * 400;
+ int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ int64_t mp = (5 * doy + 2) / 153;
+ int dd = (int)(doy - (153 * mp + 2) / 5 + 1);
+ int mm = (int)(mp < 10 ? mp + 3 : mp - 9);
+ *y = (int)(yy + (mm <= 2));
+ *m = mm;
+ *d = dd;
+}
+
+static char local_zone[64] = "UTC";
+void ic_set_local_zone(const char *z) { if (z && tz_zone_valid(z)) snprintf(local_zone, sizeof local_zone, "%s", z); }
+const char *ic_local_zone(void) { return local_zone; }
+
+typedef struct { char name[64]; uint8_t *buf; size_t n; int bad; } ZoneCache;
+static ZoneCache zones[24];
+
+static const struct { const char *win, *iana; } winzones[] = {
+ { "Pacific Standard Time", "America/Los_Angeles" }, { "Mountain Standard Time", "America/Denver" }, { "Central Standard Time", "America/Chicago" },
+ { "Eastern Standard Time", "America/New_York" }, { "GMT Standard Time", "Europe/London" }, { "Greenwich Standard Time", "Atlantic/Reykjavik" },
+ { "W. Europe Standard Time", "Europe/Berlin" }, { "Romance Standard Time", "Europe/Paris" }, { "Central Europe Standard Time", "Europe/Budapest" },
+ { "Central European Standard Time", "Europe/Warsaw" }, { "E. Europe Standard Time", "Europe/Chisinau" }, { "FLE Standard Time", "Europe/Kiev" },
+ { "GTB Standard Time", "Europe/Bucharest" }, { "Russian Standard Time", "Europe/Moscow" }, { "Argentina Standard Time", "America/Argentina/Buenos_Aires" },
+ { "E. South America Standard Time", "America/Sao_Paulo" }, { "SA Pacific Standard Time", "America/Bogota" }, { "Pacific SA Standard Time", "America/Santiago" },
+ { "Central America Standard Time", "America/Guatemala" }, { "Central Standard Time (Mexico)", "America/Mexico_City" }, { "Mexico Standard Time", "America/Mexico_City" },
+ { "Venezuela Standard Time", "America/Caracas" }, { "Montevideo Standard Time", "America/Montevideo" }, { "SA Western Standard Time", "America/La_Paz" },
+ { "Paraguay Standard Time", "America/Asuncion" }, { "Tokyo Standard Time", "Asia/Tokyo" }, { "China Standard Time", "Asia/Shanghai" },
+ { "India Standard Time", "Asia/Kolkata" }, { "AUS Eastern Standard Time", "Australia/Sydney" }, { "Arabian Standard Time", "Asia/Dubai" },
+ { "Israel Standard Time", "Asia/Jerusalem" }, { "Korea Standard Time", "Asia/Seoul" }, { "Singapore Standard Time", "Asia/Singapore" },
+ { "UTC", "UTC" }, { "Coordinated Universal Time", "UTC" }, { "Atlantic Standard Time", "America/Halifax" }, { "Hawaiian Standard Time", "Pacific/Honolulu" },
+ { "Alaskan Standard Time", "America/Anchorage" }, { "US Mountain Standard Time", "America/Phoenix" }, { "SE Asia Standard Time", "Asia/Bangkok" },
+ { "New Zealand Standard Time", "Pacific/Auckland" }, { "South Africa Standard Time", "Africa/Johannesburg" }, { "Turkey Standard Time", "Europe/Istanbul" },
+};
+
+static ZoneCache *zone_load(const char *zone) {
+ char z[64];
+ if (!zone || !*zone) zone = local_zone;
+ snprintf(z, sizeof z, "%s", zone);
+ for (size_t i = 0; i < sizeof winzones / sizeof winzones[0]; i++) if (!strcasecmp(z, winzones[i].win)) { snprintf(z, sizeof z, "%s", winzones[i].iana); break; }
+ /* "/mozilla.org/20050126_1/Europe/Madrid", "/freeassociation.sourceforge.net/Tzfile/Europe/Madrid" */
+ if (z[0] == '/') {
+ char *last = strrchr(z, '/'), *prev = NULL;
+ if (last) { *last = 0; prev = strrchr(z, '/'); *last = '/'; }
+ if (prev) memmove(z, prev + 1, strlen(prev + 1) + 1);
+ else if (last) memmove(z, last + 1, strlen(last + 1) + 1);
+ }
+ if (!strcasecmp(z, "Z") || !strcasecmp(z, "GMT") || !strcasecmp(z, "Etc/UTC")) snprintf(z, sizeof z, "UTC");
+ for (size_t i = 0; i < sizeof zones / sizeof zones[0]; i++) if (zones[i].name[0] && !strcmp(zones[i].name, z)) return zones[i].bad ? NULL : &zones[i];
+ size_t slot = 0;
+ for (; slot < sizeof zones / sizeof zones[0]; slot++) if (!zones[slot].name[0]) break;
+ if (slot == sizeof zones / sizeof zones[0]) { slot = 0; free(zones[0].buf); memset(&zones[0], 0, sizeof zones[0]); }
+ ZoneCache *c = &zones[slot];
+ snprintf(c->name, sizeof c->name, "%s", z);
+ c->bad = 1;
+ if (!tz_zone_valid(z)) return NULL;
+ char path[160];
+ snprintf(path, sizeof path, "/usr/share/zoneinfo/%s", z);
+ int fd = open(path, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) return NULL;
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size <= 0 || st.st_size > (1 << 20)) { close(fd); return NULL; }
+ c->buf = malloc((size_t)st.st_size);
+ if (!c->buf) { close(fd); return NULL; }
+ ssize_t r = read(fd, c->buf, (size_t)st.st_size);
+ close(fd);
+ if (r != st.st_size) { free(c->buf); c->buf = NULL; return NULL; }
+ c->n = (size_t)r;
+ c->bad = 0;
+ return c;
+}
+
+int32_t ic_zone_offset(const char *zone, int64_t t) {
+ ZoneCache *c = zone_load(zone);
+ if (!c) c = zone_load(local_zone);
+ if (!c) return 0;
+ TzInfo ti;
+ if (tzif_lookup(c->buf, c->n, t, &ti)) return 0;
+ return ti.utoff;
+}
+
+int64_t ic_wall_to_utc(int64_t wall, const char *zone) {
+ int32_t o1 = ic_zone_offset(zone, wall);
+ int64_t t = wall - o1;
+ int32_t o2 = ic_zone_offset(zone, t);
+ if (o2 != o1) t = wall - o2;
+ return t;
+}
+
+static int digits(const char *s, int n, int *out) {
+ int v = 0;
+ for (int i = 0; i < n; i++) { if (!isdigit((unsigned char)s[i])) return 0; v = v * 10 + (s[i] - '0'); }
+ *out = v;
+ return 1;
+}
+
+/* "20251018", "20251018T103000", "20251018T103000Z"; returns wall/UTC seconds */
+static int parse_dt(const char *v, int64_t *t, int *allday, int *utc) {
+ while (*v == ' ') v++;
+ int y, mo, d, h = 0, mi = 0, s = 0;
+ size_t n = strlen(v);
+ if (n >= 10 && v[4] == '-' && v[7] == '-') { /* vCard: 1990-05-17 */
+ if (!digits(v, 4, &y) || !digits(v + 5, 2, &mo) || !digits(v + 8, 2, &d)) return 0;
+ *allday = 1; *utc = 0;
+ *t = ic_days_from_civil(y, mo, d) * 86400;
+ return mo >= 1 && mo <= 12 && d >= 1 && d <= 31;
+ }
+ if (n < 8 || !digits(v, 4, &y) || !digits(v + 4, 2, &mo) || !digits(v + 6, 2, &d)) return 0;
+ if (mo < 1 || mo > 12 || d < 1 || d > 31) return 0;
+ *allday = 1;
+ *utc = 0;
+ if (n >= 15 && (v[8] == 'T' || v[8] == 't')) {
+ if (!digits(v + 9, 2, &h) || !digits(v + 11, 2, &mi) || !digits(v + 13, 2, &s)) return 0;
+ if (h > 23 || mi > 59 || s > 60) return 0;
+ *allday = 0;
+ *utc = n >= 16 && (v[15] == 'Z' || v[15] == 'z');
+ }
+ *t = ic_days_from_civil(y, mo, d) * 86400 + h * 3600 + mi * 60 + s;
+ return 1;
+}
+
+int ic_time(const IcProp *p, int64_t *t, int *allday, char *tzid, size_t tzcap) {
+ if (tzcap) tzid[0] = 0;
+ if (!p || !p->value) return 0;
+ char vt[32] = "";
+ ic_param(p, "VALUE", vt, sizeof vt);
+ int utc = 0;
+ int64_t w;
+ if (!parse_dt(p->value, &w, allday, &utc)) return 0;
+ if (!strcasecmp(vt, "DATE")) *allday = 1;
+ if (*allday) { *t = ic_wall_to_utc(w - w % 86400, NULL); return 1; }
+ if (utc) { *t = w; return 1; }
+ char z[64] = "";
+ ic_param(p, "TZID", z, sizeof z);
+ if (tzcap) snprintf(tzid, tzcap, "%s", z);
+ *t = ic_wall_to_utc(w, z[0] ? z : NULL);
+ return 1;
+}
+
+/* ISO 8601 duration ("-PT15M", "P1DT2H", "P2W") in seconds. */
+static int parse_dur(const char *v, long long *out) {
+ while (*v == ' ') v++;
+ int neg = 0;
+ if (*v == '-') { neg = 1; v++; } else if (*v == '+') v++;
+ if (*v != 'P' && *v != 'p') return 0;
+ v++;
+ long long tot = 0;
+ int time = 0, any = 0;
+ while (*v) {
+ if (*v == 'T' || *v == 't') { time = 1; v++; continue; }
+ if (!isdigit((unsigned char)*v)) return 0;
+ long long x = 0;
+ while (isdigit((unsigned char)*v)) { x = x * 10 + (*v - '0'); if (x > 100000000) return 0; v++; }
+ char u = (char)toupper((unsigned char)*v);
+ if (!u) return 0;
+ v++;
+ any = 1;
+ if (tot > 100000000000LL) return 0;
+ if (u == 'W') tot += x * 604800;
+ else if (u == 'D') tot += x * 86400;
+ else if (u == 'H' && time) tot += x * 3600;
+ else if (u == 'M' && time) tot += x * 60;
+ else if (u == 'S' && time) tot += x;
+ else return 0;
+ }
+ if (!any || tot > 100000000000LL) return 0;
+ *out = neg ? -tot : tot;
+ return 1;
+}
+
+/* ---- events ---- */
+
+static void text_prop(const IcComp *c, const char *name, char *out, size_t cap) {
+ IcProp *p = ic_prop(c, name);
+ if (cap) out[0] = 0;
+ if (p) ic_unescape(p->value, out, cap);
+}
+
+static void mailto(const char *v, char *out, size_t cap) {
+ while (*v == ' ') v++;
+ if (!strncasecmp(v, "mailto:", 7)) v += 7;
+ snprintf(out, cap, "%s", v);
+ for (char *p = out; *p; p++) *p = (char)tolower((unsigned char)*p);
+}
+
+static void fill_event(const IcComp *c, IcEvent *e) {
+ memset(e, 0, sizeof *e);
+ e->is_todo = !strcmp(c->name, "VTODO");
+ text_prop(c, "UID", e->uid, sizeof e->uid);
+ text_prop(c, "SUMMARY", e->summary, sizeof e->summary);
+ text_prop(c, "LOCATION", e->location, sizeof e->location);
+ text_prop(c, "URL", e->url, sizeof e->url);
+ text_prop(c, "STATUS", e->status, sizeof e->status);
+ for (char *p = e->status; *p; p++) *p = (char)toupper((unsigned char)*p);
+ text_prop(c, "CATEGORIES", e->categories, sizeof e->categories);
+ IcProp *d = ic_prop(c, "DESCRIPTION");
+ e->description = ic_unescape_dup(d ? d->value : "");
+ IcProp *rr = ic_prop(c, "RRULE");
+ if (rr) snprintf(e->rrule, sizeof e->rrule, "%s", rr->value);
+ IcProp *seq = ic_prop(c, "SEQUENCE");
+ if (seq) e->sequence = bnum(seq->value, 0, 1000000000, 0, NULL);
+ int ad;
+ char tz[64];
+ int64_t t;
+ if (ic_time(ic_prop(c, "DTSTAMP"), &t, &ad, tz, sizeof tz)) e->dtstamp = t;
+ if (ic_time(ic_prop(c, "LAST-MODIFIED"), &t, &ad, tz, sizeof tz)) e->modified = t;
+ IcProp *ds = ic_prop(c, "DTSTART");
+ if (ic_time(ds, &e->start, &e->allday, e->tzid, sizeof e->tzid)) {
+ if (e->allday) {
+ int64_t w; int u, a2;
+ if (parse_dt(ds->value, &w, &a2, &u)) e->sdate = (int)(w / 86400);
+ }
+ }
+ IcProp *de = ic_prop(c, e->is_todo ? "DUE" : "DTEND");
+ if (e->is_todo) {
+ if (de && ic_time(de, &e->due, &e->due_allday, tz, sizeof tz)) { /* ok */ }
+ if (!ds) { e->start = e->due; e->allday = e->due_allday; }
+ }
+ if (!e->is_todo && de && ic_time(de, &e->end, &ad, tz, sizeof tz)) {
+ if (e->allday) { int64_t w; int u, a2; if (parse_dt(de->value, &w, &a2, &u)) e->edate = (int)(w / 86400); }
+ } else if (!e->is_todo) {
+ long long dur = 0;
+ IcProp *du = ic_prop(c, "DURATION");
+ if (du && parse_dur(du->value, &dur) && dur >= 0) e->end = e->start + dur;
+ else e->end = e->start + (e->allday ? 86400 : 0);
+ if (e->allday) e->edate = e->sdate + (int)((e->end - e->start + 86399) / 86400);
+ }
+ if (e->allday && e->edate <= e->sdate) e->edate = e->sdate + 1;
+ if (e->end < e->start) e->end = e->start;
+ IcProp *rid = ic_prop(c, "RECURRENCE-ID");
+ if (rid) ic_time(rid, &e->recurrence_id, &ad, tz, sizeof tz);
+ for (IcProp *x = ic_prop(c, "EXDATE"); x; x = ic_prop_next(c, x, "EXDATE")) {
+ /* comma separated, with the same parameters */
+ char *v = x->value;
+ while (*v && e->nexdate < 64) {
+ char one[40];
+ size_t n = strcspn(v, ",");
+ if (n < sizeof one) {
+ memcpy(one, v, n);
+ one[n] = 0;
+ IcProp tmp = *x;
+ tmp.value = one;
+ int64_t et;
+ if (ic_time(&tmp, &et, &ad, tz, sizeof tz)) e->exdate[e->nexdate++] = et;
+ }
+ v += n;
+ if (*v == ',') v++;
+ }
+ }
+ IcProp *org = ic_prop(c, "ORGANIZER");
+ if (org) { mailto(org->value, e->organizer, sizeof e->organizer); char cn[160]; if (ic_param(org, "CN", cn, sizeof cn)) snprintf(e->organizer_name, sizeof e->organizer_name, "%s", cn); }
+ for (IcProp *a = ic_prop(c, "ATTENDEE"); a && e->natt < IC_MAX_ATT; a = ic_prop_next(c, a, "ATTENDEE")) {
+ IcAttendee *na = realloc(e->att, (size_t)(e->natt + 1) * sizeof *na);
+ if (!na) break;
+ e->att = na;
+ IcAttendee *x = &e->att[e->natt++];
+ memset(x, 0, sizeof *x);
+ mailto(a->value, x->email, sizeof x->email);
+ ic_param(a, "CN", x->name, sizeof x->name);
+ if (!ic_param(a, "PARTSTAT", x->partstat, sizeof x->partstat)) snprintf(x->partstat, sizeof x->partstat, "NEEDS-ACTION");
+ for (char *p = x->partstat; *p; p++) *p = (char)toupper((unsigned char)*p);
+ ic_param(a, "ROLE", x->role, sizeof x->role);
+ char rs[16];
+ x->rsvp = ic_param(a, "RSVP", rs, sizeof rs) && !strcasecmp(rs, "TRUE");
+ }
+ IcProp *pr = ic_prop(c, "PRIORITY");
+ if (pr) e->priority = bnum(pr->value, 0, 9, 0, NULL);
+ IcProp *co = ic_prop(c, "COMPLETED");
+ if (co) ic_time(co, &e->completed, &ad, tz, sizeof tz);
+ if (!e->completed && !strcmp(e->status, "COMPLETED")) e->completed = e->modified ? e->modified : 1;
+ IcProp *fl = ic_prop(c, "X-LORDOS-FLAGGED");
+ if (fl) e->flagged = bnum(fl->value, 0, 1, 0, NULL) != 0;
+ IcProp *rel = ic_prop(c, "RELATED-TO");
+ if (rel) ic_unescape(rel->value, e->parent_uid, sizeof e->parent_uid);
+ /* alarms */
+ for (IcComp *k = c->kid; k && e->nalarms < 8; k = k->next) {
+ if (strcmp(k->name, "VALARM")) continue;
+ IcProp *tr = ic_prop(k, "TRIGGER");
+ if (!tr) continue;
+ char vt[24] = "";
+ ic_param(tr, "VALUE", vt, sizeof vt);
+ long long dur;
+ if (!strcasecmp(vt, "DATE-TIME")) {
+ int64_t at;
+ if (ic_time(tr, &at, &ad, tz, sizeof tz)) { int64_t ref = e->is_todo && e->due ? e->due : e->start; int64_t m = (ref - at) / 60; e->alarms[e->nalarms++] = (int)(m < -5000000 ? -5000000 : m > 5000000 ? 5000000 : m); }
+ } else if (parse_dur(tr->value, &dur)) {
+ char rel2[16] = "";
+ ic_param(tr, "RELATED", rel2, sizeof rel2);
+ long long before = -dur;
+ if (!strcasecmp(rel2, "END") && !e->is_todo) before -= (e->end - e->start);
+ long long m = before / 60;
+ e->alarms[e->nalarms++] = (int)(m < -5000000 ? -5000000 : m > 5000000 ? 5000000 : m);
+ }
+ }
+}
+
+int ical_events(const char *text, size_t len, IcEvent **out, char *method, size_t mcap) {
+ *out = NULL;
+ if (mcap) method[0] = 0;
+ const char *err;
+ IcComp *root = ic_parse(text, len, &err);
+ if (!root) return -1;
+ int n = 0, cap = 0;
+ IcEvent *ev = NULL;
+ for (IcComp *cal = root->kid; cal; cal = cal->next) {
+ if (strcmp(cal->name, "VCALENDAR")) continue;
+ IcProp *m = ic_prop(cal, "METHOD");
+ if (m && mcap && !method[0]) { snprintf(method, mcap, "%s", m->value); for (char *p = method; *p; p++) *p = (char)toupper((unsigned char)*p); }
+ for (IcComp *c = cal->kid; c; c = c->next) {
+ if (strcmp(c->name, "VEVENT") && strcmp(c->name, "VTODO")) continue;
+ if (n == cap) {
+ int nc = cap ? cap * 2 : 4;
+ IcEvent *ne = realloc(ev, (size_t)nc * sizeof *ne);
+ if (!ne) break;
+ ev = ne; cap = nc;
+ }
+ fill_event(c, &ev[n++]);
+ if (n >= 20000) break;
+ }
+ }
+ ic_free(root);
+ *out = ev;
+ return n;
+}
+
+void ical_events_free(IcEvent *ev, int n) {
+ for (int i = 0; i < n; i++) { free(ev[i].description); free(ev[i].att); }
+ free(ev);
+}
+
+/* ---- recurrence ---- */
+
+typedef struct {
+ int freq; /* 'D','W','M','Y' */
+ int interval, count;
+ int64_t until;
+ int byday[16], byday_n[16], nbyday; /* weekday 0=MO..6=SU, ordinal (0 = every) */
+ int bymonthday[16], nbmd;
+ int bymonth[12], nbm;
+} Rule;
+
+static int wd_index(const char *s) {
+ static const char *w[] = { "MO", "TU", "WE", "TH", "FR", "SA", "SU" };
+ for (int i = 0; i < 7; i++) if (!strncasecmp(s, w[i], 2)) return i;
+ return -1;
+}
+
+static int parse_rule(const char *r, Rule *o) {
+ memset(o, 0, sizeof *o);
+ o->interval = 1;
+ char buf[512];
+ snprintf(buf, sizeof buf, "%s", r);
+ for (char *save = NULL, *part = strtok_r(buf, ";", &save); part; part = strtok_r(NULL, ";", &save)) {
+ char *eq = strchr(part, '=');
+ if (!eq) continue;
+ *eq = 0;
+ char *k = part, *v = eq + 1;
+ if (!strcasecmp(k, "FREQ")) o->freq = !strcasecmp(v, "DAILY") ? 'D' : !strcasecmp(v, "WEEKLY") ? 'W' : !strcasecmp(v, "MONTHLY") ? 'M' : !strcasecmp(v, "YEARLY") ? 'Y' : 0;
+ else if (!strcasecmp(k, "INTERVAL")) o->interval = bnum(v, 1, 1000, 1, NULL);
+ else if (!strcasecmp(k, "COUNT")) o->count = bnum(v, 0, 100000, 0, NULL);
+ else if (!strcasecmp(k, "UNTIL")) {
+ int64_t t; int ad, utc;
+ if (parse_dt(v, &t, &ad, &utc)) o->until = ad ? ic_wall_to_utc(t + 86399, NULL) : utc ? t : ic_wall_to_utc(t, NULL);
+ } else if (!strcasecmp(k, "BYDAY")) {
+ int maxd = (int)(sizeof o->byday / sizeof o->byday[0]);
+ for (char *s2 = NULL, *d = strtok_r(v, ",", &s2); d && o->nbyday < maxd; d = strtok_r(NULL, ",", &s2)) {
+ int ord = 0;
+ if (*d == '+' || *d == '-' || isdigit((unsigned char)*d)) {
+ const char *e;
+ ord = bnum(d, -53, 53, 99, &e); /* RFC 5545: ±1..53 */
+ if (ord == 99 || ord == 0) continue;
+ d = (char *)e;
+ }
+ int w = wd_index(d);
+ if (w < 0) continue;
+ o->byday[o->nbyday] = w;
+ o->byday_n[o->nbyday] = ord;
+ o->nbyday++;
+ }
+ } else if (!strcasecmp(k, "BYMONTHDAY")) {
+ for (char *s2 = NULL, *d = strtok_r(v, ",", &s2); d && o->nbmd < 16; d = strtok_r(NULL, ",", &s2)) { int x = bnum(d, -31, 31, 0, NULL); if (x) o->bymonthday[o->nbmd++] = x; }
+ } else if (!strcasecmp(k, "BYMONTH")) {
+ for (char *s2 = NULL, *d = strtok_r(v, ",", &s2); d && o->nbm < 12; d = strtok_r(NULL, ",", &s2)) { int x = bnum(d, 1, 12, 0, NULL); if (x) o->bymonth[o->nbm++] = x; }
+ }
+ }
+ return o->freq != 0;
+}
+
+static int weekday_of(int64_t days) { int64_t w = (days + 3) % 7; if (w < 0) w += 7; return (int)w; } /* 1970-01-01 = Thursday → 0=MO */
+static int month_len(int y, int m) { static const int ml[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return m == 2 && ((y % 4 == 0 && y % 100) || y % 400 == 0) ? 29 : ml[m - 1]; }
+
+static int in_list(const int *l, int n, int v) { for (int i = 0; i < n; i++) if (l[i] == v) return 1; return 0; }
+
+/* days of a month that match the rule (ascending); returns count */
+static int month_days(const Rule *r, int y, int m, int dflt_day, int64_t *out) {
+ int ml = month_len(y, m), n = 0;
+ int64_t first = ic_days_from_civil(y, m, 1);
+ int pick[32] = { 0 };
+ if (r->nbmd) {
+ for (int i = 0; i < r->nbmd; i++) { int d = r->bymonthday[i] > 0 ? r->bymonthday[i] : ml + r->bymonthday[i] + 1; if (d >= 1 && d <= ml) pick[d] = 1; }
+ } else if (r->nbyday) {
+ for (int i = 0; i < r->nbyday; i++) {
+ int w = r->byday[i], ord = r->byday_n[i];
+ int fw = weekday_of(first);
+ int d1 = 1 + (w - fw + 7) % 7; /* first such weekday */
+ if (ord < -53 || ord > 53) continue; /* already bounded by parse_rule */
+ if (!ord) { for (int d = d1; d >= 1 && d <= ml; d += 7) pick[d] = 1; }
+ else if (ord > 0) { int d = d1 + (ord - 1) * 7; if (d >= 1 && d <= ml) pick[d] = 1; }
+ else { int last = d1; while (last + 7 <= ml) last += 7; int d = last + (ord + 1) * 7; if (d >= 1 && d <= ml) pick[d] = 1; }
+ }
+ } else if (dflt_day >= 1 && dflt_day <= ml) pick[dflt_day] = 1;
+ for (int d = 1; d <= ml; d++) if (pick[d]) out[n++] = first + d - 1;
+ return n;
+}
+
+int ical_expand(const IcEvent *ev, int64_t from, int64_t to, int max, void (*fn)(void *u, int64_t start), void *u) {
+ int64_t dur = ev->end - ev->start;
+ int nout = 0;
+ const char *zone = ev->allday ? NULL : (ev->tzid[0] ? ev->tzid : NULL);
+#define EMIT(t) do { int64_t _t = (t); int _ex = 0; for (int _k = 0; _k < ev->nexdate; _k++) if (ev->exdate[_k] == _t || (ev->allday && (ev->exdate[_k] - _t) / 86400 == 0 && llabs(ev->exdate[_k] - _t) < 86400)) _ex = 1; \
+ if (!_ex && _t < to && (_t + (dur > 0 ? dur : 1)) > from) { if (fn) fn(u, _t); nout++; } } while (0)
+ Rule r;
+ if (!ev->rrule[0] || ev->recurrence_id || !parse_rule(ev->rrule, &r)) { EMIT(ev->start); return nout; }
+ int64_t wall0 = ev->start + ic_zone_offset(zone, ev->start);
+ int64_t day0 = wall0 >= 0 ? wall0 / 86400 : (wall0 - 86399) / 86400;
+ int64_t tod = wall0 - day0 * 86400;
+ if (ev->allday) { day0 = ev->sdate; tod = 0; }
+ int y0, m0, d0;
+ ic_civil_from_days(day0, &y0, &m0, &d0);
+ int seen = 0;
+ int64_t cand[400];
+ for (long period = 0; period < 50000 && nout < max; period++) {
+ int nc = 0;
+ if (r.freq == 'D') {
+ int64_t d = day0 + period * r.interval;
+ int y, m, dd;
+ ic_civil_from_days(d, &y, &m, &dd);
+ if ((!r.nbm || in_list(r.bymonth, r.nbm, m)) && (!r.nbyday || in_list(r.byday, r.nbyday, weekday_of(d))) &&
+ (!r.nbmd || in_list(r.bymonthday, r.nbmd, dd))) cand[nc++] = d;
+ } else if (r.freq == 'W') {
+ int64_t wk = day0 - weekday_of(day0) + period * 7 * r.interval;
+ for (int w = 0; w < 7; w++) {
+ int64_t d = wk + w;
+ if (r.nbyday ? in_list(r.byday, r.nbyday, w) : w == weekday_of(day0)) {
+ int y, m, dd;
+ ic_civil_from_days(d, &y, &m, &dd);
+ if (!r.nbm || in_list(r.bymonth, r.nbm, m)) cand[nc++] = d;
+ }
+ }
+ } else if (r.freq == 'M') {
+ long mi = (long)y0 * 12 + (m0 - 1) + period * r.interval;
+ int y = (int)(mi / 12), m = (int)(mi % 12) + 1;
+ if (!r.nbm || in_list(r.bymonth, r.nbm, m)) nc = month_days(&r, y, m, d0, cand);
+ } else {
+ int y = y0 + (int)(period * r.interval);
+ if (y > 9999) break;
+ if (r.nbm) { for (int k = 0; k < r.nbm && nc + 31 <= (int)(sizeof cand / sizeof cand[0]); k++) nc += month_days(&r, y, r.bymonth[k], d0, cand + nc); }
+ else nc = month_days(&r, y, m0, d0, cand);
+ }
+ /* candidates are in ascending order per period (yearly months may not be: sort) */
+ for (int a = 1; a < nc; a++) for (int b = a; b > 0 && cand[b] < cand[b - 1]; b--) { int64_t t = cand[b]; cand[b] = cand[b - 1]; cand[b - 1] = t; }
+ int stop = 0;
+ for (int k = 0; k < nc; k++) {
+ if (cand[k] < day0) continue;
+ int64_t start = ev->allday ? ic_wall_to_utc(cand[k] * 86400, NULL) : ic_wall_to_utc(cand[k] * 86400 + tod, zone);
+ if (cand[k] == day0) start = ev->start;
+ if (r.until && start > r.until) { stop = 1; break; }
+ if (r.count && seen >= r.count) { stop = 1; break; }
+ seen++;
+ if (start >= to) { stop = 1; break; }
+ EMIT(start);
+ if (nout >= max) { stop = 1; break; }
+ }
+ if (stop) break;
+ /* nothing can match anymore? (e.g. BYMONTHDAY=31 forever is fine; guard by the period cap) */
+ }
+#undef EMIT
+ return nout;
+}
+
+/* ---- JSON ---- */
+
+static void date_str(int days, char *out, size_t cap) {
+ int y, m, d;
+ ic_civil_from_days(days, &y, &m, &d);
+ snprintf(out, cap, "%04d-%02d-%02d", y, m, d);
+}
+
+void ical_event_json(JBuf *b, const IcEvent *e, int64_t occ) {
+ int64_t start = occ ? occ : e->start;
+ int64_t end = start + (e->end - e->start);
+ jb_raw(b, "{\"uid\":"); jb_str(b, e->uid);
+ jb_raw(b, ",\"title\":"); jb_str(b, e->summary);
+ if (e->location[0]) { jb_raw(b, ",\"loc\":"); jb_str(b, e->location); }
+ if (e->description && e->description[0]) { jb_raw(b, ",\"notes\":"); jb_str(b, e->description); }
+ if (e->url[0]) { jb_raw(b, ",\"url\":"); jb_str(b, e->url); }
+ if (e->status[0]) { jb_raw(b, ",\"status\":"); jb_str(b, e->status); }
+ if (e->categories[0]) { jb_raw(b, ",\"cats\":"); jb_str(b, e->categories); }
+ jb_printf(b, ",\"start\":%lld,\"end\":%lld,\"allDay\":%s", (long long)start * 1000, (long long)end * 1000, e->allday ? "true" : "false");
+ if (e->allday) {
+ char ds[16], de[16];
+ int sd = e->sdate, ed = e->edate;
+ if (occ) { int64_t w = occ + ic_zone_offset(NULL, occ); int nd = (int)(w >= 0 ? w / 86400 : (w - 86399) / 86400); ed = nd + (ed - sd); sd = nd; }
+ date_str(sd, ds, sizeof ds);
+ date_str(ed, de, sizeof de);
+ jb_raw(b, ",\"sdate\":"); jb_str(b, ds);
+ jb_raw(b, ",\"edate\":"); jb_str(b, de);
+ }
+ if (e->tzid[0]) { jb_raw(b, ",\"tz\":"); jb_str(b, e->tzid); }
+ if (e->rrule[0]) { jb_raw(b, ",\"rrule\":"); jb_str(b, e->rrule); }
+ if (occ) jb_printf(b, ",\"occ\":%lld", (long long)occ * 1000);
+ if (e->recurrence_id) jb_printf(b, ",\"rid\":%lld", (long long)e->recurrence_id * 1000);
+ jb_raw(b, ",\"alarms\":[");
+ for (int i = 0; i < e->nalarms; i++) jb_printf(b, "%s%d", i ? "," : "", e->alarms[i]);
+ jb_raw(b, "]");
+ if (e->organizer[0]) { jb_raw(b, ",\"org\":{\"email\":"); jb_str(b, e->organizer); jb_raw(b, ",\"name\":"); jb_str(b, e->organizer_name); jb_raw(b, "}"); }
+ if (e->natt) {
+ jb_raw(b, ",\"att\":[");
+ for (int i = 0; i < e->natt; i++) {
+ if (i) jb_raw(b, ",");
+ jb_raw(b, "{\"email\":"); jb_str(b, e->att[i].email);
+ jb_raw(b, ",\"name\":"); jb_str(b, e->att[i].name);
+ jb_raw(b, ",\"ps\":"); jb_str(b, e->att[i].partstat);
+ if (e->att[i].role[0]) { jb_raw(b, ",\"role\":"); jb_str(b, e->att[i].role); }
+ jb_raw(b, "}");
+ }
+ jb_raw(b, "]");
+ }
+ jb_printf(b, ",\"seq\":%d", e->sequence);
+ if (e->is_todo) {
+ jb_raw(b, ",\"todo\":true");
+ if (e->due) {
+ jb_printf(b, ",\"due\":%lld,\"dueAllDay\":%s", (long long)e->due * 1000, e->due_allday ? "true" : "false");
+ if (e->due_allday) { char ds[16]; int64_t w = e->due + ic_zone_offset(NULL, e->due); date_str((int)(w / 86400), ds, sizeof ds); jb_raw(b, ",\"dueDate\":"); jb_str(b, ds); }
+ } else jb_raw(b, ",\"due\":null");
+ jb_printf(b, ",\"prio\":%d,\"done\":%s,\"flag\":%s", e->priority, e->completed ? "true" : "false", e->flagged ? "true" : "false");
+ if (e->completed > 1) jb_printf(b, ",\"doneAt\":%lld", (long long)e->completed * 1000);
+ if (e->parent_uid[0]) { jb_raw(b, ",\"parent\":"); jb_str(b, e->parent_uid); }
+ }
+ jb_raw(b, "}");
+}
+
+/* ---- building ---- */
+
+static void fmt_utc(int64_t t, char *out, size_t cap) {
+ int64_t days = t >= 0 ? t / 86400 : (t - 86399) / 86400;
+ int64_t s = t - days * 86400;
+ int y, m, d;
+ ic_civil_from_days(days, &y, &m, &d);
+ snprintf(out, cap, "%04d%02d%02dT%02d%02d%02dZ", y, m, d, (int)(s / 3600), (int)(s / 60 % 60), (int)(s % 60));
+}
+
+static void fmt_wall(int64_t t, const char *zone, char *out, size_t cap) {
+ int64_t w = t + ic_zone_offset(zone, t);
+ int64_t days = w >= 0 ? w / 86400 : (w - 86399) / 86400;
+ int64_t s = w - days * 86400;
+ int y, m, d;
+ ic_civil_from_days(days, &y, &m, &d);
+ snprintf(out, cap, "%04d%02d%02dT%02d%02d%02d", y, m, d, (int)(s / 3600), (int)(s / 60 % 60), (int)(s % 60));
+}
+
+static void fmt_date(int64_t t, char *out, size_t cap) {
+ int64_t w = t + ic_zone_offset(NULL, t);
+ int y, m, d;
+ ic_civil_from_days(w >= 0 ? w / 86400 : (w - 86399) / 86400, &y, &m, &d);
+ snprintf(out, cap, "%04d%02d%02d", y, m, d);
+}
+
+static void kv(JBuf *b, const char *k, const char *v) {
+ if (!v || !*v) return;
+ char *e = ic_escape(v);
+ if (!e) return;
+ size_t n = strlen(k) + strlen(e) + 2;
+ char *line = malloc(n);
+ if (line) { snprintf(line, n, "%s:%s", k, e); ic_line(b, line); free(line); }
+ free(e);
+}
+
+static int safe_rrule(const char *r) {
+ for (; *r; r++) if (!isalnum((unsigned char)*r) && !strchr("=;,:+-", *r)) return 0;
+ return 1;
+}
+
+static void safe_param(const char *in, char *out, size_t cap) {
+ /* parameter values: no quotes, no control characters */
+ size_t o = 0;
+ for (; in && *in && o + 1 < cap; in++) if ((unsigned char)*in >= 0x20 && *in != '"') out[o++] = *in;
+ out[o] = 0;
+}
+
+/* VTIMEZONE from the zone's TZif footer (POSIX rule "CET-1CEST,M3.5.0,M10.5.0/3"). 0 if done. */
+static int vtimezone(JBuf *b, const char *zone) {
+ ZoneCache *c = zone_load(zone);
+ if (!c || c->n < 2) return -1;
+ /* footer: "\n<rule>\n" at the end */
+ size_t e = c->n - 1;
+ if (c->buf[e] != '\n') return -1;
+ size_t s = e;
+ while (s > 0 && c->buf[s - 1] != '\n') s--;
+ char rule[80];
+ size_t rl = e - s;
+ if (!rl || rl >= sizeof rule) return -1;
+ memcpy(rule, c->buf + s, rl);
+ rule[rl] = 0;
+ /* std name, offset [dst name [offset], start, end] */
+ const char *p = rule;
+ char stdn[16], dstn[16] = "";
+ int i = 0;
+ if (*p == '<') { p++; while (*p && *p != '>' && i < 15) stdn[i++] = *p++; if (*p == '>') p++; }
+ else while (isalpha((unsigned char)*p) && i < 15) stdn[i++] = *p++;
+ stdn[i] = 0;
+ int sign = 1, hh = 0, mm = 0;
+ if (*p == '-') { sign = -1; p++; } else if (*p == '+') p++;
+ if (!isdigit((unsigned char)*p)) return -1;
+ hh = (int)strtol(p, (char **)&p, 10);
+ if (*p == ':') { p++; mm = (int)strtol(p, (char **)&p, 10); }
+ int stdoff = -sign * (hh * 3600 + mm * 60); /* POSIX sign is inverted */
+ int dstoff = stdoff + 3600;
+ int has_dst = 0;
+ int sm = 0, sw = 0, sd = 0, em = 0, ew = 0, ed = 0;
+ if (*p) {
+ i = 0;
+ if (*p == '<') { p++; while (*p && *p != '>' && i < 15) dstn[i++] = *p++; if (*p == '>') p++; }
+ else while (isalpha((unsigned char)*p) && i < 15) dstn[i++] = *p++;
+ dstn[i] = 0;
+ if (*p && *p != ',') {
+ int sg = 1;
+ if (*p == '-') { sg = -1; p++; } else if (*p == '+') p++;
+ int h2 = (int)strtol(p, (char **)&p, 10), m2 = 0;
+ if (*p == ':') { p++; m2 = (int)strtol(p, (char **)&p, 10); }
+ dstoff = -sg * (h2 * 3600 + m2 * 60);
+ }
+ if (sscanf(p, ",M%d.%d.%d", &sm, &sw, &sd) == 3) {
+ const char *q = strchr(p + 1, ',');
+ if (q && sscanf(q, ",M%d.%d.%d", &em, &ew, &ed) == 3) has_dst = 1;
+ }
+ if (!has_dst) return -1;
+ }
+ char line[160], zq[80];
+ safe_param(zone, zq, sizeof zq);
+ jb_raw(b, "BEGIN:VTIMEZONE\r\n");
+ snprintf(line, sizeof line, "TZID:%s", zq);
+ ic_line(b, line);
+ static const char *wd[] = { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };
+#define OFF(o) ((o) < 0 ? '-' : '+'), abs(o) / 3600, abs(o) / 60 % 60
+ if (!has_dst) {
+ jb_raw(b, "BEGIN:STANDARD\r\nDTSTART:19700101T000000\r\n");
+ jb_printf(b, "TZOFFSETFROM:%c%02d%02d\r\nTZOFFSETTO:%c%02d%02d\r\n", OFF(stdoff), OFF(stdoff));
+ if (stdn[0]) jb_printf(b, "TZNAME:%s\r\n", stdn);
+ jb_raw(b, "END:STANDARD\r\n");
+ } else {
+ int sord = sw == 5 ? -1 : sw, eord = ew == 5 ? -1 : ew;
+ jb_raw(b, "BEGIN:DAYLIGHT\r\nDTSTART:19700301T020000\r\n");
+ jb_printf(b, "TZOFFSETFROM:%c%02d%02d\r\nTZOFFSETTO:%c%02d%02d\r\n", OFF(stdoff), OFF(dstoff));
+ jb_printf(b, "RRULE:FREQ=YEARLY;BYMONTH=%d;BYDAY=%d%s\r\n", sm, sord, wd[sd % 7]);
+ if (dstn[0]) jb_printf(b, "TZNAME:%s\r\n", dstn);
+ jb_raw(b, "END:DAYLIGHT\r\nBEGIN:STANDARD\r\nDTSTART:19701001T020000\r\n");
+ jb_printf(b, "TZOFFSETFROM:%c%02d%02d\r\nTZOFFSETTO:%c%02d%02d\r\n", OFF(dstoff), OFF(stdoff));
+ jb_printf(b, "RRULE:FREQ=YEARLY;BYMONTH=%d;BYDAY=%d%s\r\n", em, eord, wd[ed % 7]);
+ if (stdn[0]) jb_printf(b, "TZNAME:%s\r\n", stdn);
+ jb_raw(b, "END:STANDARD\r\n");
+ }
+#undef OFF
+ jb_raw(b, "END:VTIMEZONE\r\n");
+ return 0;
+}
+
+static void time_line(JBuf *b, const char *name, int64_t t, int allday, const char *tz) {
+ char v[40], line[200];
+ if (allday) { fmt_date(t, v, sizeof v); snprintf(line, sizeof line, "%s;VALUE=DATE:%s", name, v); }
+ else if (tz && *tz) { char zq[80]; safe_param(tz, zq, sizeof zq); fmt_wall(t, tz, v, sizeof v); snprintf(line, sizeof line, "%s;TZID=%s:%s", name, zq, v); }
+ else { fmt_utc(t, v, sizeof v); snprintf(line, sizeof line, "%s:%s", name, v); }
+ ic_line(b, line);
+}
+
+static void person_line(JBuf *b, const char *prop, const char *email, const char *name, const char *ps, const char *role, int rsvp) {
+ char cn[200] = "", line[700];
+ safe_param(name, cn, sizeof cn);
+ char e[300];
+ safe_param(email, e, sizeof e);
+ size_t o = (size_t)snprintf(line, sizeof line, "%s", prop);
+ if (cn[0]) o += (size_t)snprintf(line + o, sizeof line - o, ";CN=\"%s\"", cn);
+ if (role && *role) o += (size_t)snprintf(line + o, sizeof line - o, ";ROLE=%s", role);
+ if (ps && *ps) o += (size_t)snprintf(line + o, sizeof line - o, ";PARTSTAT=%s", ps);
+ if (rsvp) o += (size_t)snprintf(line + o, sizeof line - o, ";RSVP=TRUE");
+ if (o < sizeof line) snprintf(line + o, sizeof line - o, ":mailto:%s", e);
+ ic_line(b, line);
+}
+
+char *ical_build(const IcBuild *x, size_t *olen) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//LordOS//Calendar 1.0//EN\r\nCALSCALE:GREGORIAN\r\n");
+ if (x->method && *x->method) jb_printf(&b, "METHOD:%s\r\n", x->method);
+ const char *tz = x->tzid && *x->tzid && tz_zone_valid(x->tzid) ? x->tzid : NULL;
+ if (tz && !x->allday) { if (vtimezone(&b, tz)) tz = NULL; }
+ jb_raw(&b, x->is_todo ? "BEGIN:VTODO\r\n" : "BEGIN:VEVENT\r\n");
+ kv(&b, "UID", x->uid);
+ char now[40];
+ fmt_utc((int64_t)time(NULL), now, sizeof now);
+ jb_printf(&b, "DTSTAMP:%s\r\nLAST-MODIFIED:%s\r\n", now, now);
+ jb_printf(&b, "SEQUENCE:%d\r\n", x->sequence);
+ if (!x->is_todo || x->start) time_line(&b, "DTSTART", x->start, x->allday, tz);
+ if (!x->is_todo) {
+ int64_t end = x->end > x->start ? x->end : x->start + (x->allday ? 86400 : 3600);
+ time_line(&b, "DTEND", end, x->allday, tz);
+ }
+ kv(&b, "SUMMARY", x->summary);
+ kv(&b, "LOCATION", x->location);
+ kv(&b, "DESCRIPTION", x->description);
+ if (x->url && *x->url) { char line[600]; char u[520]; safe_param(x->url, u, sizeof u); snprintf(line, sizeof line, "URL:%s", u); ic_line(&b, line); }
+ if (x->status && *x->status) { char st[32]; safe_param(x->status, st, sizeof st); jb_printf(&b, "STATUS:%s\r\n", st); }
+ kv(&b, "CATEGORIES", x->categories);
+ if (x->rrule && *x->rrule && safe_rrule(x->rrule)) { char line[600]; snprintf(line, sizeof line, "RRULE:%s", x->rrule); ic_line(&b, line); }
+ for (int i = 0; i < x->nexdate; i++) time_line(&b, "EXDATE", x->exdate[i], x->allday, tz);
+ if (x->organizer && *x->organizer) person_line(&b, "ORGANIZER", x->organizer, x->organizer_name, NULL, NULL, 0);
+ for (int i = 0; i < x->natt; i++) person_line(&b, "ATTENDEE", x->att[i].email, x->att[i].name, x->att[i].partstat[0] ? x->att[i].partstat : "NEEDS-ACTION",
+ x->att[i].role[0] ? x->att[i].role : "REQ-PARTICIPANT", x->att[i].rsvp);
+ if (x->is_todo) {
+ if (x->due) time_line(&b, "DUE", x->due, x->due_allday, NULL);
+ if (x->priority > 0 && x->priority <= 9) jb_printf(&b, "PRIORITY:%d\r\n", x->priority);
+ if (x->completed) {
+ char c[40];
+ fmt_utc(x->completed > 1 ? x->completed : (int64_t)time(NULL), c, sizeof c);
+ jb_printf(&b, "STATUS:COMPLETED\r\nCOMPLETED:%s\r\nPERCENT-COMPLETE:100\r\n", c);
+ } else if (!x->status || !*x->status) jb_raw(&b, "STATUS:NEEDS-ACTION\r\n");
+ if (x->flagged) jb_raw(&b, "X-LORDOS-FLAGGED:1\r\n");
+ kv(&b, "RELATED-TO", x->parent_uid);
+ }
+ for (int i = 0; i < x->nalarms && i < 8; i++) {
+ int m = x->alarms[i];
+ jb_raw(&b, "BEGIN:VALARM\r\nACTION:DISPLAY\r\n");
+ kv(&b, "DESCRIPTION", x->summary && *x->summary ? x->summary : "Reminder");
+ if (m >= 0) jb_printf(&b, "TRIGGER:-PT%dM\r\n", m);
+ else jb_printf(&b, "TRIGGER:PT%dM\r\n", -m);
+ jb_raw(&b, "END:VALARM\r\n");
+ }
+ jb_raw(&b, x->is_todo ? "END:VTODO\r\n" : "END:VEVENT\r\n");
+ jb_raw(&b, "END:VCALENDAR\r\n");
+ if (b.oom) { jb_free(&b); return NULL; }
+ if (olen) *olen = b.n;
+ return b.p;
+}
+
+char *ical_reply(const IcEvent *ev, const char *attendee, const char *name, const char *partstat, size_t *olen) {
+ IcAttendee me;
+ memset(&me, 0, sizeof me);
+ snprintf(me.email, sizeof me.email, "%s", attendee);
+ if (name) snprintf(me.name, sizeof me.name, "%s", name);
+ snprintf(me.partstat, sizeof me.partstat, "%s", partstat);
+ for (int i = 0; i < ev->natt; i++) if (!strcasecmp(ev->att[i].email, attendee)) { if (!name || !*name) snprintf(me.name, sizeof me.name, "%s", ev->att[i].name); snprintf(me.role, sizeof me.role, "%s", ev->att[i].role); }
+ IcBuild b = { 0 };
+ b.uid = ev->uid; b.summary = ev->summary; b.location = ev->location;
+ b.start = ev->start; b.end = ev->end; b.allday = ev->allday;
+ b.organizer = ev->organizer; b.organizer_name = ev->organizer_name;
+ b.att = &me; b.natt = 1;
+ b.sequence = ev->sequence;
+ b.method = "REPLY";
+ b.rrule = ev->rrule;
+ return ical_build(&b, olen);
+}
diff --git a/server/src/mail/ical.h b/server/src/mail/ical.h
new file mode 100644
index 0000000..fb2f7b8
--- /dev/null
+++ b/server/src/mail/ical.h
@@ -0,0 +1,128 @@
+/* ical.h — iCalendar (RFC 5545) and the shared content-line syntax of vCard (RFC 6350) for
+ * lord-maild: calendars, reminders (VTODO) and invitations (iTIP, RFC 5546).
+ *
+ * The parser is bounded (line count, nesting, property count) and never reads outside the input.
+ * Times are kept as Unix seconds (UTC). An all-day value keeps its civil date (YYYYMMDD) so it
+ * never shifts with the time zone. TZID values are resolved with the system tz database
+ * (/usr/share/zoneinfo, through our TZif reader); Windows zone names from Outlook are mapped. */
+#ifndef LORD_MAIL_ICAL_H
+#define LORD_MAIL_ICAL_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include "../doc/wire.h"
+
+#define IC_MAX_LINES 200000
+#define IC_MAX_DEPTH 8
+#define IC_MAX_PROPS 4000
+
+typedef struct {
+ char name[48]; /* upper case, without the vCard group ("item1.") */
+ char group[24];
+ char *params; /* raw "TZID=Europe/Madrid;VALUE=DATE" (may be "") */
+ char *value; /* raw value (still escaped) */
+} IcProp;
+
+typedef struct IcComp IcComp;
+struct IcComp {
+ char name[24]; /* "VCALENDAR", "VEVENT", "VCARD", ... ("" for the root) */
+ IcProp *props;
+ int nprops, capprops;
+ IcComp *kid, *last, *next, *parent;
+};
+
+/* Content lines → component tree. NULL on error (err set). */
+IcComp *ic_parse(const char *text, size_t len, const char **err);
+void ic_free(IcComp *root);
+IcProp *ic_prop(const IcComp *c, const char *name); /* first one */
+IcProp *ic_prop_next(const IcComp *c, const IcProp *after, const char *name);
+int ic_param(const IcProp *p, const char *name, char *out, size_t cap); /* 1 if present */
+/* TEXT value unescaping (\n \N \, \; \\) into out. */
+void ic_unescape(const char *in, char *out, size_t cap);
+char *ic_unescape_dup(const char *in);
+/* Escapes text for a TEXT value. malloc. */
+char *ic_escape(const char *in);
+/* Folds a content line at 75 octets (UTF-8 safe) and appends it with CRLF. */
+void ic_line(JBuf *b, const char *line);
+
+/* ---- time ---- */
+/* Sets the user's zone (IANA name, e.g. "America/Argentina/Buenos_Aires") for floating times. */
+void ic_set_local_zone(const char *zone);
+const char *ic_local_zone(void);
+/* Offset (seconds east of UTC) of a zone at instant t; "" or unknown zone = the local zone. */
+int32_t ic_zone_offset(const char *zone, int64_t t);
+/* Wall-clock seconds (as if UTC) in `zone` → Unix seconds. */
+int64_t ic_wall_to_utc(int64_t wall, const char *zone);
+/* Parses DATE / DATE-TIME. *allday = 1 for VALUE=DATE (then *t is that date's 00:00 local). */
+int ic_time(const IcProp *p, int64_t *t, int *allday, char *tzid, size_t tzcap);
+/* civil date helpers */
+int64_t ic_days_from_civil(int64_t y, int m, int d);
+void ic_civil_from_days(int64_t z, int *y, int *m, int *d);
+
+/* ---- events and to-dos ---- */
+#define IC_MAX_ATT 64
+typedef struct { char email[256]; char name[160]; char partstat[24]; char role[24]; int rsvp; } IcAttendee;
+
+typedef struct {
+ int is_todo;
+ char uid[256];
+ char summary[512];
+ char location[512];
+ char *description; /* malloc, unescaped */
+ char url[512];
+ char status[24]; /* CONFIRMED, TENTATIVE, CANCELLED, NEEDS-ACTION, COMPLETED */
+ char categories[256];
+ int64_t start, end; /* UTC; end = start (+1 day for all-day) if missing */
+ int allday;
+ int sdate, edate; /* all-day: civil days (ic_days_from_civil) */
+ char tzid[64];
+ char rrule[512];
+ int64_t exdate[64];
+ int nexdate;
+ int64_t recurrence_id; /* override of one occurrence (0 if none) */
+ int alarms[8]; /* minutes before start (or due) */
+ int nalarms;
+ char organizer[256], organizer_name[160];
+ IcAttendee *att; /* malloc, natt entries (at most IC_MAX_ATT) */
+ int natt;
+ int sequence;
+ int64_t dtstamp, modified;
+ /* VTODO */
+ int64_t due;
+ int due_allday;
+ int priority; /* 0 none, 1 high … 9 low */
+ int64_t completed; /* 0 = not completed */
+ int flagged; /* X-LORDOS-FLAGGED / X-APPLE-FLAGGED? (local extension) */
+ char parent_uid[256]; /* RELATED-TO (subtasks) */
+} IcEvent;
+
+/* All VEVENT/VTODO of a calendar text. *method gets METHOD (REQUEST, REPLY, CANCEL…) or "".
+ * Returns the count (malloc'd array in *out) or -1. */
+int ical_events(const char *text, size_t len, IcEvent **out, char *method, size_t mcap);
+void ical_events_free(IcEvent *ev, int n);
+/* Occurrences of ev that intersect [from, to): calls fn with each start (UTC). Overrides and
+ * EXDATE are the caller's job for overrides; EXDATE is applied here. Returns the count, bounded
+ * by `max`. */
+int ical_expand(const IcEvent *ev, int64_t from, int64_t to, int max, void (*fn)(void *u, int64_t start), void *u);
+/* JSON of one event/to-do (occurrence start overrides when occ != 0). */
+void ical_event_json(JBuf *b, const IcEvent *ev, int64_t occ);
+
+/* Builds a VCALENDAR with one VEVENT or VTODO from JSON-like fields. The caller frees. */
+typedef struct {
+ int is_todo;
+ const char *uid, *summary, *location, *description, *url, *rrule, *status, *categories;
+ int64_t start, end; int allday; const char *tzid;
+ const int *alarms; int nalarms;
+ int64_t due; int due_allday; int priority; int64_t completed; int flagged;
+ const char *organizer, *organizer_name;
+ const IcAttendee *att; int natt;
+ int sequence;
+ const char *method; /* NULL for a plain calendar object */
+ const char *parent_uid;
+ const int64_t *exdate; int nexdate;
+} IcBuild;
+char *ical_build(const IcBuild *b, size_t *olen);
+/* iTIP REPLY for an invitation: the original event with only `attendee`'s PARTSTAT. */
+char *ical_reply(const IcEvent *ev, const char *attendee, const char *name, const char *partstat, size_t *olen);
+
+#endif
diff --git a/server/src/mail/imap.c b/server/src/mail/imap.c
new file mode 100644
index 0000000..fa86121
--- /dev/null
+++ b/server/src/mail/imap.c
@@ -0,0 +1,1025 @@
+/* imap.c — IMAP4rev1 client and the per-account worker of lord-maild (see maild.h).
+ *
+ * Per account: connect (implicit TLS on 993, or STARTTLS on 143), authenticate (AUTHENTICATE
+ * PLAIN or LOGIN with an app password; XOAUTH2 is prepared but disabled until the user registers
+ * a client ID, see docs/MAIL.md), list folders (SPECIAL-USE), sync each folder into the cache
+ * (UIDVALIDITY, UID SEARCH, header + preview fetch in chunks, newest first; CONDSTORE for cheap
+ * flag updates), then wait in IDLE on the inbox for new mail. Jobs from the UI (open a message,
+ * flags, move, delete, drafts) interrupt the IDLE through an eventfd. */
+#include "maild.h"
+#include "imapp.h"
+#include "mime.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <poll.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <time.h>
+#include <unistd.h>
+
+#define LINE_MAX_BYTES ((size_t)16 << 20)
+#define CHUNK 250
+
+typedef struct {
+ Account *a;
+ Conn *c;
+ int tag;
+ char caps[4096];
+ int idle, condstore, move, uidplus, literalplus, special_use, sasl_ir, auth_plain;
+ char selected[512];
+ uint32_t exists;
+ char text[512]; /* text of the last tagged reply */
+ char code[128]; /* [CODE] of the last tagged reply */
+} Imap;
+
+static int has_cap(const Imap *im, const char *cap) {
+ size_t n = strlen(cap);
+ for (const char *p = im->caps; (p = strcasestr(p, cap)); p += n)
+ if ((p == im->caps || p[-1] == ' ') && (p[n] == ' ' || p[n] == 0 || p[n] == '\r' || p[n] == '\n')) return 1;
+ return 0;
+}
+
+static void parse_caps(Imap *im, const char *line) {
+ const char *c = strcasestr(line, "CAPABILITY");
+ if (!c) return;
+ c += 10;
+ snprintf(im->caps, sizeof im->caps, "%s", c);
+ for (char *p = im->caps; *p; p++) if (*p == ']' || *p == '\r' || *p == '\n') { *p = 0; break; }
+ im->idle = has_cap(im, "IDLE");
+ im->condstore = has_cap(im, "CONDSTORE") || has_cap(im, "QRESYNC");
+ im->move = has_cap(im, "MOVE");
+ im->uidplus = has_cap(im, "UIDPLUS");
+ im->literalplus = has_cap(im, "LITERAL+");
+ im->special_use = has_cap(im, "SPECIAL-USE");
+ im->sasl_ir = has_cap(im, "SASL-IR");
+ im->auth_plain = has_cap(im, "AUTH=PLAIN");
+}
+
+/* One complete response (line + literals) as raw bytes. NULL on I/O error. */
+static char *read_raw(Imap *im, size_t *len) {
+ size_t n = 0, cap = 0;
+ char *buf = NULL;
+ for (;;) {
+ size_t ll;
+ char *line = conn_line(im->c, &ll, LINE_MAX_BYTES);
+ if (!line) { free(buf); return NULL; }
+ if (n + ll + 1 > cap) { cap = (n + ll + 1) * 2; char *nb = realloc(buf, cap); if (!nb) { free(line); free(buf); return NULL; } buf = nb; }
+ memcpy(buf + n, line, ll);
+ n += ll;
+ buf[n] = 0;
+ free(line);
+ /* "{123}\r\n" or "{123+}\r\n" at the end: a literal follows */
+ size_t e = n;
+ if (e >= 2 && buf[e - 1] == '\n') e--;
+ if (e >= 1 && buf[e - 1] == '\r') e--;
+ if (e < 3 || buf[e - 1] != '}') break;
+ size_t s = e - 1;
+ while (s > 0 && buf[s - 1] != '{') s--;
+ if (!s) break;
+ char *endp;
+ unsigned long long lit = strtoull(buf + s, &endp, 10);
+ if (endp == buf + s || (*endp != '}' && *endp != '+')) break;
+ if (lit > LINE_MAX_BYTES * 4) { free(buf); snprintf(im->text, sizeof im->text, "literal too big"); return NULL; }
+ if (conn_read_n(im->c, (size_t)lit, &buf, &n, &cap)) { free(buf); return NULL; }
+ }
+ *len = n;
+ return buf;
+}
+
+typedef void (*Untagged)(Imap *im, IResp *r, void *u);
+
+/* Waits for the tagged reply of `tag`, handing untagged responses to cb. 0 OK, 1 NO, 2 BAD, -1 I/O. */
+static int wait_tag(Imap *im, int tag, Untagged cb, void *u) {
+ char want[16];
+ snprintf(want, sizeof want, "A%04d", tag);
+ for (;;) {
+ size_t len;
+ char *raw = read_raw(im, &len);
+ if (!raw) return -1;
+ IResp r;
+ if (imap_parse(raw, len, &r)) { dbg("unparsable IMAP response: %.120s", raw); free(raw); continue; }
+ if (!strcmp(r.tag, "*")) {
+ if (iv_is(r.first, "CAPABILITY") || (r.first && r.first->type == IV_ATOM && r.first->n > 12 && !strncasecmp(r.first->s, "[CAPABILITY", 11))) parse_caps(im, raw);
+ if (r.first && r.first->next && iv_is(r.first->next, "EXISTS")) im->exists = (uint32_t)iv_num(r.first, 0);
+ if (cb) cb(im, &r, u);
+ } else if (!strcmp(r.tag, want)) {
+ int st = iv_is(r.first, "OK") ? 0 : iv_is(r.first, "NO") ? 1 : 2;
+ /* keep the human text and a response code */
+ const char *t = raw + strlen(want) + 1;
+ snprintf(im->text, sizeof im->text, "%s", t);
+ for (char *p = im->text; *p; p++) if (*p == '\r' || *p == '\n') { *p = 0; break; }
+ im->code[0] = 0;
+ IVal *c = r.first ? r.first->next : NULL;
+ if (c && c->type == IV_ATOM && c->n && c->s[0] == '[') snprintf(im->code, sizeof im->code, "%.*s", (int)(c->n < 127 ? c->n : 127), c->s);
+ if (strcasestr(raw, "[CAPABILITY")) parse_caps(im, raw);
+ imap_resp_free(&r);
+ free(raw);
+ return st;
+ }
+ imap_resp_free(&r);
+ free(raw);
+ }
+}
+
+static int cmd(Imap *im, Untagged cb, void *u, const char *fmt, ...) __attribute__((format(printf, 4, 5)));
+static int cmd(Imap *im, Untagged cb, void *u, const char *fmt, ...) {
+ int tag = ++im->tag;
+ char head[16];
+ snprintf(head, sizeof head, "A%04d ", tag);
+ va_list ap;
+ va_start(ap, fmt);
+ char small[8192];
+ int k = vsnprintf(small, sizeof small, fmt, ap);
+ va_end(ap);
+ if (k < 0 || (size_t)k >= sizeof small) return -1;
+ dbg("%s> %.*s", im->a->id, strncasecmp(small, "LOGIN", 5) && strncasecmp(small, "AUTHENTICATE", 12) ? k : 12, small);
+ if (conn_write(im->c, head, strlen(head)) || conn_write(im->c, small, (size_t)k) || conn_write(im->c, "\r\n", 2)) return -1;
+ return wait_tag(im, tag, cb, u);
+}
+
+static void imap_close(Imap *im) {
+ if (im->c) { conn_printf(im->c, "A%04d LOGOUT\r\n", ++im->tag); conn_close(im->c); }
+ im->c = NULL;
+ im->selected[0] = 0;
+}
+
+/* ---- connect + login ---- */
+
+static void need_auth(Account *a) {
+ if (a->need_auth_sent) return;
+ a->need_auth_sent = 1;
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"need-auth\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"user\":"); jb_str(&b, a->user);
+ jb_raw(&b, "}");
+ send_event(&b);
+}
+
+static int imap_open(Imap *im, char *err, size_t ecap) {
+ Account *a = im->a;
+ memset((char *)im + sizeof(Account *), 0, sizeof *im - sizeof(Account *));
+ pthread_mutex_lock(&G);
+ char *pw = a->password ? strdup(a->password) : NULL;
+ pthread_mutex_unlock(&G);
+ if (!strcmp(a->auth, "oauth2")) { free(pw); snprintf(err, ecap, "oauth-disabled"); return -2; }
+ if (!pw) { need_auth(a); snprintf(err, ecap, "no-password"); return -2; }
+ TlsInfo ti;
+ char why[64];
+ im->c = open_conn(a->id, a->imap.host, a->imap.port, a->imap.sec == SEC_SSL, a->pin_imap, &ti, why, sizeof why);
+ if (!im->c) { free(pw); snprintf(err, ecap, "%s", why); return !strcmp(why, "cert") ? -3 : -1; }
+ size_t len;
+ char *greet = read_raw(im, &len);
+ if (!greet) { free(pw); snprintf(err, ecap, "greeting"); imap_close(im); return -1; }
+ parse_caps(im, greet);
+ free(greet);
+ if (a->imap.sec == SEC_STARTTLS) {
+ if (!im->caps[0]) cmd(im, NULL, NULL, "CAPABILITY");
+ if (!has_cap(im, "STARTTLS") || cmd(im, NULL, NULL, "STARTTLS")) { free(pw); snprintf(err, ecap, "no-starttls"); imap_close(im); return -1; }
+ if (conn_tls(im->c, a->pin_imap, &ti)) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"cert\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"host\":"); jb_str(&b, a->imap.host);
+ jb_printf(&b, ",\"port\":%d,\"reason\":", a->imap.port); jb_str(&b, ti.reason);
+ jb_raw(&b, ",\"subject\":"); jb_str(&b, ti.subject);
+ jb_raw(&b, ",\"issuer\":"); jb_str(&b, ti.issuer);
+ jb_raw(&b, ",\"sha256\":"); jb_str(&b, ti.sha256);
+ jb_raw(&b, "}");
+ if (ti.code) send_event(&b); else jb_free(&b);
+ free(pw);
+ snprintf(err, ecap, "%s", ti.code ? "cert" : "tls");
+ conn_close(im->c);
+ im->c = NULL;
+ return ti.code ? -3 : -1;
+ }
+ im->caps[0] = 0;
+ } else if (a->imap.sec == SEC_NONE) {
+ /* never send a password in the clear */
+ free(pw);
+ snprintf(err, ecap, "insecure");
+ imap_close(im);
+ return -1;
+ }
+ if (!im->caps[0] || !strcasestr(im->caps, "AUTH")) cmd(im, NULL, NULL, "CAPABILITY");
+ int r;
+ if (im->auth_plain) {
+ size_t ul = strlen(a->user), pl = strlen(pw);
+ unsigned char *raw = malloc(ul + pl + 3);
+ if (!raw) { free(pw); imap_close(im); return -1; }
+ raw[0] = 0;
+ memcpy(raw + 1, a->user, ul);
+ raw[1 + ul] = 0;
+ memcpy(raw + 2 + ul, pw, pl);
+ size_t el;
+ char *e = b64_encode(raw, ul + pl + 2, 0, &el);
+ explicit_bzero(raw, ul + pl + 2);
+ free(raw);
+ if (!e) { free(pw); imap_close(im); return -1; }
+ if (im->sasl_ir) r = cmd(im, NULL, NULL, "AUTHENTICATE PLAIN %s", e);
+ else {
+ int tag = ++im->tag;
+ conn_printf(im->c, "A%04d AUTHENTICATE PLAIN\r\n", tag);
+ size_t ll;
+ char *plus = read_raw(im, &ll);
+ if (plus && plus[0] == '+') { conn_write(im->c, e, el); conn_write(im->c, "\r\n", 2); }
+ free(plus);
+ r = wait_tag(im, tag, NULL, NULL);
+ }
+ explicit_bzero(e, el);
+ free(e);
+ } else {
+ int l1, l2;
+ char *qu = imap_quote(a->user, im->literalplus, &l1), *qp = imap_quote(pw, im->literalplus, &l2);
+ if ((l1 || l2) && !im->literalplus) r = 2; /* non-ASCII without LITERAL+: use PLAIN */
+ else r = qu && qp ? cmd(im, NULL, NULL, "LOGIN %s %s", qu, qp) : -1;
+ if (qp) { explicit_bzero(qp, strlen(qp)); free(qp); }
+ free(qu);
+ }
+ explicit_bzero(pw, strlen(pw));
+ free(pw);
+ if (r) {
+ snprintf(err, ecap, r < 0 ? "io" : "auth: %s", im->text);
+ imap_close(im);
+ if (r > 0) {
+ /* wrong password: ask again (from the keyring prompt) */
+ pthread_mutex_lock(&G);
+ if (a->password) { explicit_bzero(a->password, strlen(a->password)); free(a->password); a->password = NULL; }
+ pthread_mutex_unlock(&G);
+ a->need_auth_sent = 0;
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"auth-failed\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"detail\":"); jb_str(&b, im->text);
+ jb_raw(&b, "}");
+ send_event(&b);
+ return -2;
+ }
+ return -1;
+ }
+ if (!strcasestr(im->caps, "IMAP4")) cmd(im, NULL, NULL, "CAPABILITY");
+ if (im->condstore && has_cap(im, "ENABLE")) cmd(im, NULL, NULL, "ENABLE CONDSTORE");
+ return 0;
+}
+
+/* ---- folders ---- */
+
+typedef struct { Account *a; char seen[512][160]; int nseen; int gmail; } ListCtx;
+
+static void on_list(Imap *im, IResp *r, void *u) {
+ ListCtx *lc = u;
+ if (!iv_is(r->first, "LIST") && !iv_is(r->first, "XLIST")) return;
+ IVal *flags = iv_at(r->first, 1), *delim = iv_at(r->first, 2), *name = iv_at(r->first, 3);
+ if (!flags || flags->type != IV_LIST || !name) return;
+ char fl[512] = "", nm[512], d[8];
+ size_t o = 0;
+ for (IVal *k = flags->kid; k; k = k->next) { o += (size_t)snprintf(fl + o, sizeof fl - o, "%.*s ", (int)k->n, k->s); if (o >= sizeof fl) break; }
+ iv_copy(name, nm, sizeof nm);
+ iv_copy(delim, d, sizeof d);
+ if (!nm[0]) return;
+ if (!strncasecmp(nm, "[Gmail]", 7) || !strncasecmp(nm, "[Google Mail]", 13)) lc->gmail = 1;
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(im->a, !strcasecmp(nm, "INBOX") ? "INBOX" : nm, 1);
+ if (f) {
+ char disp[512];
+ imap_utf7_decode(f->name, disp, sizeof disp);
+ /* show the last level ("[Gmail]/Sent Mail" → "Sent Mail") */
+ const char *last = d[0] ? strrchr(disp, d[0]) : NULL;
+ snprintf(f->display, sizeof f->display, "%s", !strcasecmp(f->name, "INBOX") ? "INBOX" : last ? last + 1 : disp);
+ snprintf(f->special, sizeof f->special, "%s", special_of(f->name, fl));
+ f->delim = d[0];
+ f->noselect = strcasestr(fl, "\\Noselect") || strcasestr(fl, "\\NonExistent");
+ }
+ pthread_mutex_unlock(&G);
+ if (lc->nseen < 512) snprintf(lc->seen[lc->nseen++], sizeof lc->seen[0], "%s", !strcasecmp(nm, "INBOX") ? "INBOX" : nm);
+}
+
+static int sync_folder_list(Imap *im) {
+ ListCtx *lc = calloc(1, sizeof *lc);
+ if (!lc) return -1;
+ lc->a = im->a;
+ int r = im->special_use ? cmd(im, on_list, lc, "LIST \"\" \"*\" RETURN (SPECIAL-USE)") : cmd(im, on_list, lc, "LIST \"\" \"*\"");
+ if (r == 0) {
+ pthread_mutex_lock(&G);
+ FolderList *fl = store_folders(im->a);
+ for (int i = 0; fl && i < fl->n; i++) {
+ int found = 0;
+ for (int k = 0; k < lc->nseen; k++) if (!strcmp(lc->seen[k], fl->f[i]->name)) { found = 1; break; }
+ if (!found && lc->nseen < 512) { store_clear(im->a, fl->f[i]); free(fl->f[i]->msgs); free(fl->f[i]); fl->f[i] = fl->f[--fl->n]; i--; }
+ }
+ /* Gmail files sent mail itself */
+ if (lc->gmail) im->a->sent_saved = 1;
+ store_save_folders(im->a);
+ pthread_mutex_unlock(&G);
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"folders\",\"acct\":"); jb_str(&b, im->a->id); jb_raw(&b, "}");
+ send_event(&b);
+ }
+ free(lc);
+ return r;
+}
+
+/* ---- messages ---- */
+
+static uint32_t parse_flags(const IVal *list) {
+ uint32_t f = 0;
+ for (const IVal *k = list && list->type == IV_LIST ? list->kid : NULL; k; k = k->next) {
+ if (iv_is(k, "\\Seen")) f |= F_SEEN;
+ else if (iv_is(k, "\\Flagged")) f |= F_FLAGGED;
+ else if (iv_is(k, "\\Answered")) f |= F_ANSWERED;
+ else if (iv_is(k, "\\Deleted")) f |= F_DELETED;
+ else if (iv_is(k, "\\Draft")) f |= F_DRAFT;
+ else if (iv_is(k, "$Forwarded") || iv_is(k, "Forwarded")) f |= F_FORWARDED;
+ else if (iv_is(k, "$Junk") || iv_is(k, "Junk")) f |= F_JUNK;
+ else if (k->type == IV_ATOM && k->n == 7 && !strncasecmp(k->s, "$label", 6) && k->s[6] >= '1' && k->s[6] <= '6') f |= F_LABEL1 << (k->s[6] - '1');
+ }
+ return f;
+}
+
+static time_t internaldate(const IVal *v) {
+ char d[64];
+ iv_copy(v, d, sizeof d);
+ for (char *p = d; *p; p++) if (*p == '-' && p - d < 12) *p = ' ';
+ return mime_date(d);
+}
+
+typedef struct { Account *a; Folder *f; uint32_t old_uidnext; int added, fresh; JBuf news; int nnews; } FetchCtx;
+
+static void addr_list_text(const char *raw, char *out, size_t cap) {
+ char dec[2048];
+ out[0] = 0;
+ MimeAddr ad[24];
+ int n = mime_addrs(raw, ad, 24);
+ size_t o = 0;
+ for (int i = 0; i < n && o + 4 < cap; i++) {
+ mime_decode_words(ad[i].name, dec, sizeof dec);
+ o += (size_t)snprintf(out + o, cap - o, "%s%s <%s>", i ? ", " : "", dec[0] ? dec : "", ad[i].email);
+ }
+ if (o >= cap) out[cap - 1] = 0;
+}
+
+static void on_fetch(Imap *im, IResp *r, void *u) {
+ FetchCtx *fc = u;
+ if (!r->first || !iv_is(r->first->next, "FETCH")) return;
+ IVal *list = r->first->next->next;
+ if (!list || list->type != IV_LIST) return;
+ uint32_t uid = (uint32_t)iv_num(imap_fetch_item(list, "UID"), 0);
+ if (!uid) return;
+ IVal *hdr = imap_fetch_item(list, "BODY[HEADER");
+ IVal *flags = imap_fetch_item(list, "FLAGS");
+ IVal *ms = imap_fetch_item(list, "MODSEQ");
+ (void)ms;
+ if (!hdr) {
+ /* flags only */
+ pthread_mutex_lock(&G);
+ Msg *m = store_msg(fc->f, uid);
+ if (m && flags) {
+ uint32_t nf = (m->flags & ~(uint32_t)(F_SEEN | F_FLAGGED | F_ANSWERED | F_DELETED | F_DRAFT | F_FORWARDED | F_JUNK | F_LABELS)) | parse_flags(flags);
+ if (nf != m->flags) {
+ if ((nf ^ m->flags) & F_SEEN) fc->f->unread += (nf & F_SEEN) ? -1 : 1;
+ m->flags = nf;
+ fc->f->dirty = 1;
+ fc->f->version++;
+ fc->added++;
+ }
+ }
+ pthread_mutex_unlock(&G);
+ return;
+ }
+ IVal *text = imap_fetch_item(list, "BODY[TEXT]");
+ const char *h = hdr->type == IV_STR ? hdr->s : "";
+ size_t hl = hdr->type == IV_STR ? hdr->n : 0;
+ char v[4096], dec[2048];
+ Msg m;
+ memset(&m, 0, sizeof m);
+ m.uid = uid;
+ m.flags = parse_flags(flags);
+ m.size = (uint32_t)iv_num(imap_fetch_item(list, "RFC822.SIZE"), 0);
+ char from_name[512] = "", from_email[512] = "", to[1024] = "", cc[1024] = "", subject[1024] = "", msgid[512] = "", irt[512] = "";
+ if (mime_header(h, hl, "From", v, sizeof v)) {
+ MimeAddr ad[1];
+ if (mime_addrs(v, ad, 1) == 1) { snprintf(from_name, sizeof from_name, "%s", ad[0].name); snprintf(from_email, sizeof from_email, "%s", ad[0].email); }
+ }
+ if (mime_header(h, hl, "To", v, sizeof v)) addr_list_text(v, to, sizeof to);
+ if (mime_header(h, hl, "Cc", v, sizeof v)) addr_list_text(v, cc, sizeof cc);
+ if (mime_header(h, hl, "Subject", v, sizeof v)) { mime_decode_words(v, dec, sizeof dec); snprintf(subject, sizeof subject, "%s", dec); }
+ mime_header(h, hl, "Message-ID", msgid, sizeof msgid);
+ mime_header(h, hl, "In-Reply-To", irt, sizeof irt);
+ char *refs = mime_header_dup(h, hl, "References");
+ if (refs && strlen(refs) > 2000) {
+ /* keep the root and the last few ids */
+ char *last = refs + strlen(refs) - 1200;
+ char *lt = strchr(last, '<');
+ char *e = strchr(refs, '>');
+ if (lt && e && e < lt) { size_t a1 = (size_t)(e - refs + 1); memmove(refs + a1 + 1, lt, strlen(lt) + 1); refs[a1] = ' '; }
+ }
+ m.date = mime_header(h, hl, "Date", v, sizeof v) ? mime_date(v) : 0;
+ if (!m.date) m.date = internaldate(imap_fetch_item(list, "INTERNALDATE"));
+ if (!m.date) m.date = time(NULL);
+ char preview[400] = "";
+ int att = 0;
+ msg_preview(h, hl, text && text->type == IV_STR ? text->s : "", text && text->type == IV_STR ? text->n : 0, preview, sizeof preview, &att);
+ m.att = (uint16_t)att;
+ m.from_name = from_name; m.from_email = from_email; m.to = to; m.cc = cc; m.subject = subject;
+ m.msgid = msgid; m.inreplyto = irt; m.refs = refs ? refs : (char *)""; m.preview = preview;
+ pthread_mutex_lock(&G);
+ int is_new = !store_msg(fc->f, uid);
+ store_add(fc->a, fc->f, &m);
+ fc->added++;
+ pthread_mutex_unlock(&G);
+ /* new mail notification: new since the last sync, unread, recent */
+ if (is_new && fc->fresh && uid >= fc->old_uidnext && !(m.flags & F_SEEN) && m.date > time(NULL) - 86400 && fc->nnews < 5) {
+ if (fc->nnews) jb_raw(&fc->news, ",");
+ jb_raw(&fc->news, "{\"from\":"); jb_str(&fc->news, from_name[0] ? from_name : from_email);
+ jb_raw(&fc->news, ",\"subject\":"); jb_str(&fc->news, subject);
+ jb_raw(&fc->news, ",\"preview\":"); jb_str(&fc->news, preview);
+ jb_printf(&fc->news, ",\"uid\":%u}", uid);
+ fc->nnews++;
+ } else if (is_new && fc->fresh && uid >= fc->old_uidnext && !(m.flags & F_SEEN)) fc->nnews++;
+ free(refs);
+}
+
+typedef struct { uint32_t *u; size_t n, cap; } Uids;
+
+static void on_search(Imap *im, IResp *r, void *u) {
+ (void)im;
+ Uids *s = u;
+ if (!iv_is(r->first, "SEARCH") && !iv_is(r->first, "ESEARCH")) return;
+ for (IVal *k = r->first->next; k; k = k->next) {
+ if (k->type == IV_ATOM && iv_is(k, "ALL") && k->next) { /* ESEARCH ... ALL 1:5,7 */
+ char set[1 << 16];
+ iv_copy(k->next, set, sizeof set);
+ uint32_t tmp[8192];
+ size_t c = imap_parse_uidset(set, tmp, 8192);
+ for (size_t i = 0; i < c; i++) { if (s->n == s->cap) { s->cap = s->cap ? s->cap * 2 : 1024; uint32_t *nu = realloc(s->u, s->cap * sizeof *nu); if (!nu) return; s->u = nu; } s->u[s->n++] = tmp[i]; }
+ break;
+ }
+ long long x = iv_num(k, -1);
+ if (x <= 0 || x > 4294967295LL) continue;
+ if (s->n == s->cap) { s->cap = s->cap ? s->cap * 2 : 1024; uint32_t *nu = realloc(s->u, s->cap * sizeof *nu); if (!nu) return; s->u = nu; }
+ s->u[s->n++] = (uint32_t)x;
+ }
+}
+
+static int cmp_u32(const void *a, const void *b) { uint32_t x = *(const uint32_t *)a, y = *(const uint32_t *)b; return x < y ? -1 : x > y; }
+
+typedef struct { uint32_t uidvalidity, uidnext; uint64_t hms; int nomodseq; } SelInfo;
+
+static void on_select(Imap *im, IResp *r, void *u) {
+ (void)im;
+ SelInfo *si = u;
+ unsigned long long v;
+ if (imap_code_num(r, "UIDVALIDITY", &v)) si->uidvalidity = (uint32_t)v;
+ if (imap_code_num(r, "UIDNEXT", &v)) si->uidnext = (uint32_t)v;
+ if (imap_code_num(r, "HIGHESTMODSEQ", &v)) si->hms = v;
+ for (IVal *k = r->first; k; k = k->next) if (k->type == IV_ATOM && k->n >= 9 && !strncasecmp(k->s, "[NOMODSEQ", 9)) si->nomodseq = 1;
+}
+
+static int select_folder(Imap *im, const char *name, SelInfo *si, int readonly) {
+ SelInfo tmp;
+ if (!si) si = &tmp;
+ memset(si, 0, sizeof *si);
+ if (!strcmp(im->selected, name) && si == &tmp) return 0;
+ int lit;
+ char *q = imap_quote(name, im->literalplus, &lit);
+ if (!q) return -1;
+ im->exists = 0;
+ int r = cmd(im, on_select, si, "%s %s%s", readonly ? "EXAMINE" : "SELECT", q, im->condstore ? " (CONDSTORE)" : "");
+ free(q);
+ if (r == 0) snprintf(im->selected, sizeof im->selected, "%s", name);
+ else im->selected[0] = 0;
+ return r;
+}
+
+static void folder_event(Account *a, Folder *f, const char *ev) {
+ JBuf b;
+ jb_init(&b);
+ jb_printf(&b, "{\"ev\":\"%s\",\"acct\":", ev);
+ jb_str(&b, a->id);
+ jb_raw(&b, ",\"folder\":");
+ jb_str(&b, f->name);
+ jb_printf(&b, ",\"total\":%d,\"unread\":%d}", f->n, f->unread);
+ send_event(&b);
+}
+
+static int sync_folder(Imap *im, Folder *f) {
+ Account *a = im->a;
+ if (f->noselect) return 0;
+ SelInfo si;
+ int r = select_folder(im, f->name, &si, 0);
+ if (r) return r < 0 ? -1 : 0;
+ pthread_mutex_lock(&G);
+ uint32_t old_next = f->uidnext;
+ int known = f->uidvalidity != 0;
+ if (f->uidvalidity && si.uidvalidity && f->uidvalidity != si.uidvalidity) { store_clear(a, f); known = 0; }
+ if (si.uidvalidity) f->uidvalidity = si.uidvalidity;
+ int unchanged = f->synced && si.uidnext && f->uidnext == si.uidnext && si.hms && f->modseq == si.hms && (uint32_t)f->n == im->exists;
+ int cached = f->n;
+ pthread_mutex_unlock(&G);
+ if (unchanged) return 0;
+ /* which uids exist on the server */
+ Uids s = { 0 };
+ if (im->exists) {
+ if (cmd(im, on_search, &s, "UID SEARCH ALL")) { free(s.u); return -1; }
+ qsort(s.u, s.n, sizeof *s.u, cmp_u32);
+ }
+ /* gone from the server */
+ pthread_mutex_lock(&G);
+ for (int i = f->n - 1; i >= 0; i--) {
+ uint32_t u = f->msgs[i].uid;
+ if (!bsearch(&u, s.u, s.n, sizeof *s.u, cmp_u32)) store_remove(a, f, u);
+ }
+ /* new ones, newest first */
+ uint32_t *want = malloc((s.n ? s.n : 1) * sizeof *want);
+ size_t nw = 0;
+ for (size_t i = s.n; want && i-- > 0;) if (!store_msg(f, s.u[i])) want[nw++] = s.u[i];
+ pthread_mutex_unlock(&G);
+ FetchCtx fc;
+ memset(&fc, 0, sizeof fc);
+ fc.a = a; fc.f = f; fc.old_uidnext = old_next; fc.fresh = known && !strcmp(f->special, "inbox");
+ jb_init(&fc.news);
+ int rc = 0;
+ for (size_t off = 0; want && off < nw && !a->stop; off += CHUNK) {
+ size_t n = nw - off < CHUNK ? nw - off : CHUNK;
+ uint32_t chunk[CHUNK];
+ for (size_t i = 0; i < n; i++) chunk[i] = want[off + n - 1 - i]; /* ascending for a compact set */
+ char set[CHUNK * 12];
+ imap_uidset(chunk, n, set, sizeof set);
+ rc = cmd(im, on_fetch, &fc, "UID FETCH %s (UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[HEADER.FIELDS (FROM TO CC SUBJECT DATE MESSAGE-ID IN-REPLY-TO "
+ "REFERENCES CONTENT-TYPE)] BODY.PEEK[TEXT]<0.2048>)", set);
+ if (rc < 0) break;
+ pthread_mutex_lock(&G);
+ store_save(a, f);
+ pthread_mutex_unlock(&G);
+ folder_event(a, f, "changed");
+ /* a waiting job (opening a message) goes first */
+ pthread_mutex_lock(&a->qmu);
+ int urgent = a->jobs && a->jobs->prio >= 5;
+ pthread_mutex_unlock(&a->qmu);
+ if (urgent) break;
+ }
+ int complete = !want || fc.added >= (int)nw || rc < 0 ? (rc >= 0) : 0;
+ free(want);
+ /* flags of what we already had */
+ if (rc >= 0 && cached) {
+ if (im->condstore && f->modseq && si.hms && !si.nomodseq)
+ rc = cmd(im, on_fetch, &fc, "UID FETCH 1:* (UID FLAGS) (CHANGEDSINCE %llu)", (unsigned long long)f->modseq);
+ else if (s.n <= 6000) rc = cmd(im, on_fetch, &fc, "UID FETCH 1:* (UID FLAGS)");
+ else {
+ char set[64];
+ snprintf(set, sizeof set, "%u:*", s.u[s.n - 2000]);
+ rc = cmd(im, on_fetch, &fc, "UID FETCH %s (UID FLAGS)", set);
+ }
+ }
+ free(s.u);
+ pthread_mutex_lock(&G);
+ if (rc >= 0 && complete) {
+ if (si.uidnext) f->uidnext = si.uidnext;
+ if (si.hms) f->modseq = si.hms;
+ f->synced = 1;
+ }
+ f->dirty = 1;
+ store_save(a, f);
+ pthread_mutex_unlock(&G);
+ folder_event(a, f, "changed");
+ if (fc.nnews) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"new\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"name\":"); jb_str(&b, a->name[0] ? a->name : a->email);
+ jb_raw(&b, ",\"folder\":"); jb_str(&b, f->name);
+ jb_printf(&b, ",\"count\":%d,\"msgs\":[", fc.nnews);
+ if (fc.news.p) jb_raw(&b, fc.news.p);
+ jb_raw(&b, "]}");
+ send_event(&b);
+ }
+ jb_free(&fc.news);
+ return rc < 0 ? -1 : 0;
+}
+
+/* ---- bodies ---- */
+
+typedef struct { char *raw; size_t len; } BodyCtx;
+static void on_body(Imap *im, IResp *r, void *u) {
+ (void)im;
+ BodyCtx *bc = u;
+ if (!r->first || !iv_is(r->first->next, "FETCH")) return;
+ IVal *list = r->first->next->next;
+ IVal *b = imap_fetch_item(list, "BODY[]");
+ if (b && b->type == IV_STR && !bc->raw) { bc->raw = malloc(b->n + 1); if (bc->raw) { memcpy(bc->raw, b->s, b->n); bc->raw[b->n] = 0; bc->len = b->n; } }
+}
+
+static int fetch_body(Imap *im, Folder *f, uint32_t uid) {
+ if (select_folder(im, f->name, NULL, 0)) return -1;
+ BodyCtx bc = { 0 };
+ int r = cmd(im, on_body, &bc, "UID FETCH %u (BODY.PEEK[])", uid);
+ if (r || !bc.raw) { free(bc.raw); return r < 0 ? -1 : 1; }
+ char rel[800];
+ store_body_path(im->a, f, uid, rel, sizeof rel);
+ int ok = fs_write(rel, bc.raw, bc.len) == 0;
+ char *text = msg_body_text(bc.raw, bc.len);
+ if (text) {
+ char tr[800];
+ snprintf(tr, sizeof tr, "%s/f/%s/t/%u", im->a->id, f->dir, uid);
+ size_t tl = strlen(text) > 16000 ? 16000 : strlen(text);
+ fs_write(tr, text, tl);
+ }
+ pthread_mutex_lock(&G);
+ Msg *m = store_msg(f, uid);
+ if (m && ok) {
+ m->body = 1;
+ if (text) { text[strlen(text) > 16000 ? 16000 : strlen(text)] = 0; store_msg_text(m, text); store_reindex(im->a, f, m); }
+ f->dirty = 1;
+ }
+ store_save(im->a, f);
+ pthread_mutex_unlock(&G);
+ free(text);
+ free(bc.raw);
+ return ok ? 0 : -1;
+}
+
+/* ---- jobs ---- */
+
+static const char *flag_atom(const char *n) {
+ static const struct { const char *n, *a; } t[] = {
+ { "seen", "\\Seen" }, { "flagged", "\\Flagged" }, { "answered", "\\Answered" }, { "forwarded", "$Forwarded" }, { "junk", "$Junk" },
+ { "label1", "$label1" }, { "label2", "$label2" }, { "label3", "$label3" }, { "label4", "$label4" }, { "label5", "$label5" }, { "label6", "$label6" },
+ };
+ for (size_t i = 0; i < sizeof t / sizeof t[0]; i++) if (!strcmp(n, t[i].n)) return t[i].a;
+ return NULL;
+}
+
+static void flags_text(const JVal *arr, char *out, size_t cap) {
+ size_t o = 0;
+ out[0] = 0;
+ for (const JVal *x = arr && arr->type == J_ARR ? arr->kid : NULL; x; x = x->next) {
+ const char *a = x->type == J_STR ? flag_atom(x->str) : NULL;
+ if (a && o + strlen(a) + 2 < cap) o += (size_t)snprintf(out + o, cap - o, "%s%s", o ? " " : "", a);
+ }
+}
+
+static Folder *special_folder(Account *a, const char *sp) {
+ FolderList *fl = store_folders(a);
+ for (int i = 0; fl && i < fl->n; i++) if (!strcmp(fl->f[i]->special, sp)) return fl->f[i];
+ return NULL;
+}
+
+static int do_expunge(Imap *im, const char *set) {
+ return im->uidplus ? cmd(im, NULL, NULL, "UID EXPUNGE %s", set) : cmd(im, NULL, NULL, "EXPUNGE");
+}
+
+static void reply_ok(uint32_t req, const char *extra) {
+ if (!req) return;
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ok\":true");
+ if (extra) jb_raw(&b, extra);
+ jb_raw(&b, "}");
+ reply_done(req, &b);
+}
+
+static int run_move(Imap *im, Job *j, const char *dest) {
+ Account *a = im->a;
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, j->folder, 0);
+ pthread_mutex_unlock(&G);
+ if (!f) return 1;
+ qsort(j->uids, (size_t)j->nuids, sizeof *j->uids, cmp_u32);
+ char *set = malloc((size_t)j->nuids * 12 + 16);
+ if (!set) return -1;
+ imap_uidset(j->uids, (size_t)j->nuids, set, (size_t)j->nuids * 12 + 16);
+ if (select_folder(im, f->name, NULL, 0)) { free(set); return -1; }
+ int r;
+ if (dest) {
+ int lit;
+ char *q = imap_quote(dest, im->literalplus, &lit);
+ if (!q) { free(set); return -1; }
+ if (im->move) r = cmd(im, NULL, NULL, "UID MOVE %s %s", set, q);
+ else {
+ r = cmd(im, NULL, NULL, "UID COPY %s %s", set, q);
+ if (!r) r = cmd(im, NULL, NULL, "UID STORE %s +FLAGS.SILENT (\\Deleted)", set);
+ if (!r) r = do_expunge(im, set);
+ }
+ free(q);
+ } else {
+ r = cmd(im, NULL, NULL, "UID STORE %s +FLAGS.SILENT (\\Deleted)", set);
+ if (!r) r = do_expunge(im, set);
+ }
+ free(set);
+ if (r == 0) {
+ pthread_mutex_lock(&G);
+ for (int i = 0; i < j->nuids; i++) store_remove(a, f, j->uids[i]);
+ store_save(a, f);
+ Folder *df = dest ? store_folder(a, dest, 0) : NULL;
+ pthread_mutex_unlock(&G);
+ folder_event(a, f, "changed");
+ if (df) sync_folder(im, df);
+ }
+ return r;
+}
+
+static void run_job(Imap *im, Job *j) {
+ Account *a = im->a;
+ JDoc d;
+ int have = j->arg && !json_parse(j->arg, j->arglen, &d, NULL, 0);
+ const JVal *args = have ? d.root : NULL;
+ int r = 0;
+ switch (j->kind) {
+ case J_SYNC_ALL: {
+ r = sync_folder_list(im);
+ if (r < 0) break;
+ /* inbox first, then the rest (the "all mail" archive only when opened) */
+ pthread_mutex_lock(&G);
+ FolderList *fl = store_folders(a);
+ int n = fl ? fl->n : 0;
+ char (*names)[512] = n ? malloc((size_t)n * 512) : NULL;
+ int k = 0;
+ for (int pass = 0; names && pass < 2; pass++)
+ for (int i = 0; i < n; i++) {
+ Folder *f = fl->f[i];
+ int inbox = !strcmp(f->special, "inbox");
+ if ((pass == 0) != inbox || !strcmp(f->special, "all") || f->noselect) continue;
+ snprintf(names[k++], 512, "%s", f->name);
+ }
+ pthread_mutex_unlock(&G);
+ for (int i = 0; i < k && !a->stop; i++) {
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, names[i], 0);
+ pthread_mutex_unlock(&G);
+ if (f && sync_folder(im, f) < 0) { r = -1; break; }
+ /* let urgent jobs through between folders */
+ pthread_mutex_lock(&a->qmu);
+ Job *urgent = a->jobs && a->jobs->prio >= 5 ? a->jobs : NULL;
+ if (urgent) a->jobs = urgent->next;
+ pthread_mutex_unlock(&a->qmu);
+ if (urgent) { run_job(im, urgent); job_free(urgent); }
+ }
+ free(names);
+ if (r >= 0) {
+ a->last_sync = time(NULL);
+ a->initial_done = 1;
+ /* download the newest bodies of the inbox for offline reading and full-text search */
+ pthread_mutex_lock(&G);
+ Folder *in = store_folder(a, "INBOX", 0);
+ uint32_t pre[40];
+ int np = 0;
+ for (int i = in ? in->n - 1 : -1; i >= 0 && np < 40; i--) if (!in->msgs[i].body && in->msgs[i].size < (2u << 20)) pre[np++] = in->msgs[i].uid;
+ pthread_mutex_unlock(&G);
+ for (int i = 0; i < np; i++) { Job *pj = job_new(J_FETCH_BODY, 0, 0); if (pj) { snprintf(pj->folder, sizeof pj->folder, "INBOX"); pj->uid = pre[i]; job_push(a, pj); } }
+ }
+ break;
+ }
+ case J_SYNC_FOLDER: {
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, j->folder, 0);
+ pthread_mutex_unlock(&G);
+ if (f) r = sync_folder(im, f);
+ break;
+ }
+ case J_FETCH_BODY: {
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, j->folder, 0);
+ Msg *m = f ? store_msg(f, j->uid) : NULL;
+ int have_body = m && m->body;
+ pthread_mutex_unlock(&G);
+ if (!f || !m) { if (j->req) reply_err(j->req, "not-found", ""); break; }
+ if (!have_body) r = fetch_body(im, f, j->uid);
+ if (j->req) {
+ if (r == 0) msg_open_cached(j->req, a, f, j->uid);
+ else reply_err(j->req, r < 0 ? "offline" : "not-found", im->text);
+ }
+ if (r > 0) r = 0;
+ break;
+ }
+ case J_FLAGS: {
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, j->folder, 0);
+ pthread_mutex_unlock(&G);
+ if (!f) { if (j->req) reply_err(j->req, "no-folder", ""); break; }
+ char add[256], rem[256];
+ flags_text(json_get(args, "add"), add, sizeof add);
+ flags_text(json_get(args, "remove"), rem, sizeof rem);
+ qsort(j->uids, (size_t)j->nuids, sizeof *j->uids, cmp_u32);
+ char *set = malloc((size_t)j->nuids * 12 + 16);
+ if (!set) break;
+ imap_uidset(j->uids, (size_t)j->nuids, set, (size_t)j->nuids * 12 + 16);
+ r = select_folder(im, f->name, NULL, 0);
+ if (!r && add[0]) r = cmd(im, NULL, NULL, "UID STORE %s +FLAGS.SILENT (%s)", set, add);
+ if (!r && rem[0]) r = cmd(im, NULL, NULL, "UID STORE %s -FLAGS.SILENT (%s)", set, rem);
+ free(set);
+ if (r > 0) { if (j->req) reply_err(j->req, "server", im->text); r = 0; break; }
+ if (!r) reply_ok(j->req, NULL);
+ break;
+ }
+ case J_MOVE: {
+ const char *to = json_str(args, "to");
+ if (!to) { reply_err(j->req, "no-target", ""); break; }
+ r = run_move(im, j, to);
+ if (r > 0) { reply_err(j->req, "server", im->text); r = 0; } else if (!r) reply_ok(j->req, NULL);
+ break;
+ }
+ case J_DELETE: {
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, j->folder, 0);
+ Folder *trash = special_folder(a, "trash");
+ char tname[512] = "";
+ if (trash && trash != f) snprintf(tname, sizeof tname, "%s", trash->name);
+ pthread_mutex_unlock(&G);
+ r = run_move(im, j, tname[0] && !json_bool(args, "permanent", 0) ? tname : NULL);
+ if (r > 0) { reply_err(j->req, "server", im->text); r = 0; } else if (!r) reply_ok(j->req, NULL);
+ break;
+ }
+ case J_CREATE_FOLDER: {
+ char enc[600];
+ imap_utf7_encode(j->folder, enc, sizeof enc);
+ int lit;
+ char *q = imap_quote(enc, im->literalplus, &lit);
+ r = q ? cmd(im, NULL, NULL, "CREATE %s", q) : -1;
+ if (!r) cmd(im, NULL, NULL, "SUBSCRIBE %s", q);
+ free(q);
+ if (!r) { sync_folder_list(im); reply_ok(j->req, NULL); }
+ else if (r > 0) { reply_err(j->req, "server", im->text); r = 0; }
+ break;
+ }
+ case J_APPEND_DRAFT: {
+ /* a draft (from the UI) or a sent copy (from the sender): append the raw message */
+ char msgid[300] = "", err[200] = "";
+ size_t ml = 0;
+ char *msg = NULL;
+ const char *target = "drafts";
+ if (args && json_get(args, "raw")) { target = json_str(args, "target") ? json_str(args, "target") : "sent"; }
+ if (args && json_str(args, "raw")) { msg = strdup(json_str(args, "raw")); ml = msg ? strlen(msg) : 0; }
+ else msg = compose_message(a, args, j->fds, j->nfds, &ml, msgid, sizeof msgid, err, sizeof err);
+ if (!msg) { reply_err(j->req, "compose", err); break; }
+ pthread_mutex_lock(&G);
+ Folder *dest = special_folder(a, target);
+ char dname[512] = "";
+ if (dest) snprintf(dname, sizeof dname, "%s", dest->name);
+ pthread_mutex_unlock(&G);
+ if (!dname[0]) snprintf(dname, sizeof dname, "%s", !strcmp(target, "drafts") ? "Drafts" : "Sent");
+ int lit;
+ char *q = imap_quote(dname, im->literalplus, &lit);
+ int tag = ++im->tag;
+ const char *fl = !strcmp(target, "drafts") ? "(\\Draft \\Seen)" : "(\\Seen)";
+ if (im->literalplus) conn_printf(im->c, "A%04d APPEND %s %s {%zu+}\r\n", tag, q ? q : "\"Drafts\"", fl, ml);
+ else {
+ conn_printf(im->c, "A%04d APPEND %s %s {%zu}\r\n", tag, q ? q : "\"Drafts\"", fl, ml);
+ size_t ll;
+ char *plus = read_raw(im, &ll);
+ int go = plus && plus[0] == '+';
+ free(plus);
+ if (!go) { free(q); free(msg); r = wait_tag(im, tag, NULL, NULL); reply_err(j->req, "append", im->text); break; }
+ }
+ conn_write(im->c, msg, ml);
+ conn_write(im->c, "\r\n", 2);
+ r = wait_tag(im, tag, NULL, NULL);
+ free(q);
+ free(msg);
+ if (r == 0) {
+ unsigned long long nu = 0;
+ const char *ap = strcasestr(im->code, "APPENDUID");
+ if (ap) { unsigned long long v1; if (sscanf(ap, "APPENDUID %llu %llu", &v1, &nu) != 2) nu = 0; }
+ /* replace the previous version of a draft */
+ double old = json_num(args, "replace", 0);
+ if (old >= 1 && old < 4294967296.0) {
+ Job tmp = { 0 };
+ uint32_t u = (uint32_t)old;
+ tmp.uids = &u; tmp.nuids = 1;
+ snprintf(tmp.folder, sizeof tmp.folder, "%s", dname);
+ run_move(im, &tmp, NULL);
+ tmp.uids = NULL;
+ }
+ pthread_mutex_lock(&G);
+ Folder *df = store_folder(a, dname, 0);
+ pthread_mutex_unlock(&G);
+ if (df) sync_folder(im, df);
+ char extra[64];
+ snprintf(extra, sizeof extra, ",\"uid\":%llu", nu);
+ reply_ok(j->req, extra);
+ } else if (r > 0) { reply_err(j->req, "append", im->text); r = 0; }
+ break;
+ }
+ default: break;
+ }
+ if (r < 0 && j->req && j->kind != J_FETCH_BODY) reply_err(j->req, "offline", im->c ? conn_error(im->c) : "connection lost");
+ if (have) json_free(&d);
+}
+
+/* ---- the worker ---- */
+
+static int idle_wait(Imap *im, int *need_sync) {
+ Account *a = im->a;
+ *need_sync = 0;
+ if (strcmp(im->selected, "INBOX") && select_folder(im, "INBOX", NULL, 0)) return -1;
+ if (!im->idle) {
+ int w = conn_wait(im->c, a->wake, 5 * 60 * 1000);
+ if (w < 0) return -1;
+ if (w == 1) { size_t l; char *x = read_raw(im, &l); if (!x) return -1; free(x); }
+ *need_sync = w != 2;
+ return 0;
+ }
+ int tag = ++im->tag;
+ if (conn_printf(im->c, "A%04d IDLE\r\n", tag)) return -1;
+ size_t len;
+ char *plus = read_raw(im, &len);
+ if (!plus) return -1;
+ int ok = plus[0] == '+';
+ free(plus);
+ if (!ok) return wait_tag(im, tag, NULL, NULL) < 0 ? -1 : 0;
+ acct_status(a, "idle", "");
+ for (;;) {
+ int w = conn_wait(im->c, a->wake, 25 * 60 * 1000);
+ if (w < 0) return -1;
+ if (w == 1) {
+ char *x = read_raw(im, &len);
+ if (!x) return -1;
+ if (strcasestr(x, "EXISTS") || strcasestr(x, "EXPUNGE") || strcasestr(x, "FETCH")) *need_sync = 1;
+ int bye = !strncasecmp(x, "* BYE", 5);
+ free(x);
+ if (bye) return -1;
+ if (!*need_sync) continue;
+ }
+ break; /* new mail, a job, or the 25-minute refresh */
+ }
+ if (conn_write(im->c, "DONE\r\n", 6)) return -1;
+ return wait_tag(im, tag, NULL, NULL) < 0 ? -1 : 0;
+}
+
+void *mail_worker(void *arg) {
+ Account *a = arg;
+ Imap im;
+ memset(&im, 0, sizeof im);
+ im.a = a;
+ int backoff = 5;
+ Job *first = job_new(J_SYNC_ALL, 0, 1);
+ if (first) job_push(a, first);
+ time_t last_full = 0;
+ while (!a->stop) {
+ if (!im.c) {
+ char err[200];
+ acct_status(a, "connecting", "");
+ int r = imap_open(&im, err, sizeof err);
+ if (r) {
+ acct_status(a, r == -2 ? "auth" : r == -3 ? "cert" : "offline", err);
+ /* fail the queued requests that need the server, keep the rest */
+ Job *j;
+ while ((j = job_pop(a))) { if (j->req) { if (j->kind == J_FETCH_BODY) reply_err(j->req, "offline", err); else reply_err(j->req, r == -2 ? "auth" : "offline", err); } job_free(j); }
+ struct pollfd p = { a->wake, POLLIN, 0 };
+ poll(&p, 1, r == -2 || r == -3 ? -1 : backoff * 1000); /* auth/cert: until something changes */
+ uint64_t v;
+ if (read(a->wake, &v, sizeof v) < 0) { /* timeout */ }
+ if (r == -1 && backoff < 300) backoff *= 2;
+ if (!a->jobs) { Job *s = job_new(J_SYNC_ALL, 0, 1); if (s) job_push(a, s); }
+ continue;
+ }
+ backoff = 5;
+ acct_status(a, "sync", "");
+ last_full = time(NULL);
+ }
+ uint64_t v;
+ if (read(a->wake, &v, sizeof v) < 0) { /* nothing signalled */ }
+ Job *j = job_pop(a);
+ if (j) {
+ if (j->kind == J_SYNC_ALL) acct_status(a, "sync", "");
+ run_job(&im, j);
+ job_free(j);
+ if (im.c && conn_error(im.c)[0] && (strstr(conn_error(im.c), "closed") || strstr(conn_error(im.c), "timeout") || strstr(conn_error(im.c), "write"))) {
+ conn_close(im.c); im.c = NULL;
+ acct_status(a, "offline", "connection lost");
+ }
+ continue;
+ }
+ if (time(NULL) - last_full > 15 * 60) { Job *s = job_new(J_SYNC_ALL, 0, 1); if (s) job_push(a, s); last_full = time(NULL); continue; }
+ int need_sync;
+ if (idle_wait(&im, &need_sync)) { conn_close(im.c); im.c = NULL; continue; }
+ if (need_sync) {
+ pthread_mutex_lock(&G);
+ Folder *in = store_folder(a, "INBOX", 0);
+ pthread_mutex_unlock(&G);
+ if (in && sync_folder(&im, in) < 0) { conn_close(im.c); im.c = NULL; }
+ }
+ }
+ if (im.c) imap_close(&im);
+ return NULL;
+}
+
+int imap_append_sent(Account *a, const char *msg, size_t len) {
+ /* the sender hands the copy to the account's worker */
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"raw\":");
+ jb_strn(&b, msg, len);
+ jb_raw(&b, ",\"target\":\"sent\"}");
+ if (b.oom) { jb_free(&b); return -1; }
+ Job *j = job_new(J_APPEND_DRAFT, 0, 6);
+ if (!j) { jb_free(&b); return -1; }
+ j->arg = b.p;
+ j->arglen = b.n;
+ job_push(a, j);
+ return 0;
+}
diff --git a/server/src/mail/imapp.c b/server/src/mail/imapp.c
new file mode 100644
index 0000000..ca4d47a
--- /dev/null
+++ b/server/src/mail/imapp.c
@@ -0,0 +1,348 @@
+/* imapp.c — see imapp.h. */
+#include "imapp.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+
+typedef struct {
+ const char *s;
+ size_t len, i;
+ IVal *vals;
+ size_t nvals, maxvals;
+ char *strs;
+ size_t nstr;
+} P;
+
+static IVal *newval(P *p, IvType t) {
+ if (p->nvals >= p->maxvals) return NULL;
+ IVal *v = &p->vals[p->nvals++];
+ memset(v, 0, sizeof *v);
+ v->type = t;
+ return v;
+}
+
+static int atom_char(unsigned char c) {
+ return c > 0x20 && c < 0x7f && c != '(' && c != ')' && c != '{' && c != '"' && c != '%';
+}
+
+/* One value at p->i. Returns NULL at end of the current list or on error (*err set). */
+static IVal *value(P *p, int *err) {
+ while (p->i < p->len && p->s[p->i] == ' ') p->i++;
+ if (p->i >= p->len) return NULL;
+ char c = p->s[p->i];
+ if (c == '\r' || c == '\n') { p->i = p->len; return NULL; }
+ if (c == ')') return NULL;
+ if (c == '"') {
+ IVal *v = newval(p, IV_STR);
+ if (!v) { *err = 1; return NULL; }
+ p->i++;
+ char *o = p->strs + p->nstr;
+ size_t n = 0;
+ while (p->i < p->len && p->s[p->i] != '"') {
+ char ch = p->s[p->i];
+ if (ch == '\\' && p->i + 1 < p->len) { p->i++; ch = p->s[p->i]; }
+ else if (ch == '\r' || ch == '\n') { *err = 1; return NULL; }
+ o[n++] = ch;
+ p->i++;
+ }
+ if (p->i >= p->len) { *err = 1; return NULL; }
+ p->i++;
+ o[n] = 0;
+ p->nstr += n + 1;
+ v->s = o; v->n = n;
+ return v;
+ }
+ if (c == '{') {
+ size_t k = p->i + 1;
+ unsigned long long n = 0;
+ size_t d0 = k;
+ while (k < p->len && isdigit((unsigned char)p->s[k])) { n = n * 10 + (unsigned)(p->s[k] - '0'); if (n > (1ull << 31)) { *err = 1; return NULL; } k++; }
+ if (k == d0) { *err = 1; return NULL; }
+ if (k < p->len && p->s[k] == '+') k++;
+ if (k >= p->len || p->s[k] != '}') { *err = 1; return NULL; }
+ k++;
+ if (k + 1 < p->len && p->s[k] == '\r' && p->s[k + 1] == '\n') k += 2;
+ else if (k < p->len && p->s[k] == '\n') k += 1;
+ else { *err = 1; return NULL; }
+ if (n > p->len - k) { *err = 1; return NULL; }
+ IVal *v = newval(p, IV_STR);
+ if (!v) { *err = 1; return NULL; }
+ v->s = p->s + k; v->n = (size_t)n;
+ p->i = k + (size_t)n;
+ return v;
+ }
+ if (c == '(') {
+ IVal *v = newval(p, IV_LIST);
+ if (!v) { *err = 1; return NULL; }
+ p->i++;
+ IVal *last = NULL;
+ for (;;) {
+ IVal *k = value(p, err);
+ if (*err) return NULL;
+ if (!k) break;
+ if (last) last->next = k; else v->kid = k;
+ last = k;
+ }
+ if (p->i >= p->len || p->s[p->i] != ')') { *err = 1; return NULL; }
+ p->i++;
+ return v;
+ }
+ /* atom, possibly with [section] (spaces and parens allowed inside) and <partial> */
+ size_t a = p->i;
+ int depth = 0;
+ while (p->i < p->len) {
+ unsigned char ch = (unsigned char)p->s[p->i];
+ if (ch == '[') { depth++; p->i++; continue; }
+ if (ch == ']' && depth) { depth--; p->i++; continue; }
+ if (depth) { if (ch == '\r' || ch == '\n') break; p->i++; continue; }
+ if (!atom_char(ch) && ch != '%') break;
+ p->i++;
+ }
+ if (depth) { *err = 1; return NULL; }
+ if (p->i == a) { *err = 1; return NULL; }
+ IVal *v = newval(p, IV_ATOM);
+ if (!v) { *err = 1; return NULL; }
+ v->s = p->s + a; v->n = p->i - a;
+ if (v->n == 3 && !strncasecmp(v->s, "NIL", 3)) { v->type = IV_NIL; }
+ return v;
+}
+
+int imap_parse(const char *buf, size_t len, IResp *out) {
+ memset(out, 0, sizeof *out);
+ P p = { 0 };
+ p.s = buf; p.len = len;
+ p.maxvals = len + 2 < IMAP_MAX_VALUES ? len + 2 : IMAP_MAX_VALUES;
+ size_t vbytes = p.maxvals * sizeof(IVal);
+ out->arena = malloc(vbytes + len + 2);
+ if (!out->arena) return -1;
+ p.vals = (IVal *)(void *)out->arena;
+ p.strs = out->arena + vbytes;
+ /* tag */
+ size_t k = 0;
+ while (k < len && buf[k] != ' ' && buf[k] != '\r' && buf[k] != '\n' && k + 1 < sizeof out->tag) { out->tag[k] = buf[k]; k++; }
+ out->tag[k] = 0;
+ if (!k) { imap_resp_free(out); return -1; }
+ p.i = k;
+ IVal *last = NULL;
+ int err = 0;
+ for (;;) {
+ IVal *v = value(&p, &err);
+ if (err) { imap_resp_free(out); return -1; }
+ if (!v) {
+ if (p.i < p.len && p.s[p.i] == ')') { imap_resp_free(out); return -1; } /* stray ')' */
+ break;
+ }
+ if (last) last->next = v; else out->first = v;
+ last = v;
+ }
+ return 0;
+}
+
+void imap_resp_free(IResp *r) { free(r->arena); r->arena = NULL; r->first = NULL; }
+
+int iv_is(const IVal *v, const char *atom) {
+ size_t n = strlen(atom);
+ return v && v->type == IV_ATOM && v->n == n && !strncasecmp(v->s, atom, n);
+}
+
+long long iv_num(const IVal *v, long long def) {
+ if (!v || (v->type != IV_ATOM && v->type != IV_STR) || !v->n || v->n > 20) return def;
+ long long x = 0;
+ for (size_t i = 0; i < v->n; i++) { if (!isdigit((unsigned char)v->s[i])) return def; x = x * 10 + (v->s[i] - '0'); }
+ return x;
+}
+
+IVal *iv_at(IVal *first, int idx) {
+ while (first && idx-- > 0) first = first->next;
+ return first;
+}
+
+int iv_count(const IVal *first) { int n = 0; while (first) { n++; first = first->next; } return n; }
+
+IVal *imap_fetch_item(IVal *list, const char *key) {
+ if (!list) return NULL;
+ IVal *k = list->type == IV_LIST ? list->kid : list;
+ size_t kl = strlen(key);
+ int prefix = memchr(key, '[', kl) != NULL; /* BODY[...] sections: prefix match */
+ for (; k && k->next; k = k->next->next) {
+ if (k->type != IV_ATOM) return NULL;
+ if (prefix ? (k->n >= kl && !strncasecmp(k->s, key, kl)) : iv_is(k, key)) return k->next;
+ }
+ return NULL;
+}
+
+size_t iv_copy(const IVal *v, char *out, size_t cap) {
+ if (!cap) return 0;
+ out[0] = 0;
+ if (!v || v->type == IV_NIL || v->type == IV_LIST) return 0;
+ size_t n = v->n < cap - 1 ? v->n : cap - 1;
+ memcpy(out, v->s, n);
+ out[n] = 0;
+ return n;
+}
+
+int imap_code_num(const IResp *r, const char *code, unsigned long long *out) {
+ size_t cl = strlen(code);
+ for (const IVal *v = r->first; v; v = v->next) {
+ if (v->type != IV_ATOM || v->n < cl + 2 || v->s[0] != '[') continue;
+ if (strncasecmp(v->s + 1, code, cl) || (v->s[1 + cl] != ' ' && v->s[1 + cl] != ']')) continue;
+ const char *p = v->s + 1 + cl;
+ while (*p == ' ') p++;
+ unsigned long long x = 0;
+ int any = 0;
+ while (p < v->s + v->n && isdigit((unsigned char)*p)) { x = x * 10 + (unsigned)(*p - '0'); p++; any = 1; }
+ if (!any) return 0;
+ *out = x;
+ return 1;
+ }
+ return 0;
+}
+
+char *imap_quote(const char *s, int nonsync, int *is_literal) {
+ if (!s) s = "";
+ size_t n = strlen(s);
+ int lit = 0;
+ for (size_t i = 0; i < n; i++) { unsigned char c = (unsigned char)s[i]; if (c == '\r' || c == '\n' || c >= 0x80 || c == 0) lit = 1; }
+ if (is_literal) *is_literal = lit;
+ if (lit) {
+ char *o = malloc(n + 32);
+ if (!o) return NULL;
+ int h = snprintf(o, 32, "{%zu%s}\r\n", n, nonsync ? "+" : "");
+ memcpy(o + h, s, n);
+ o[(size_t)h + n] = 0;
+ return o;
+ }
+ char *o = malloc(n * 2 + 3);
+ if (!o) return NULL;
+ size_t k = 0;
+ o[k++] = '"';
+ for (size_t i = 0; i < n; i++) { if (s[i] == '"' || s[i] == '\\') o[k++] = '\\'; o[k++] = s[i]; }
+ o[k++] = '"';
+ o[k] = 0;
+ return o;
+}
+
+/* ---- modified UTF-7 ---- */
+
+static const char b64m[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
+
+static int put_utf8(char *o, size_t room, unsigned cp) {
+ char t[4];
+ int k;
+ if (cp < 0x80) { t[0] = (char)cp; k = 1; }
+ else if (cp < 0x800) { t[0] = (char)(0xc0 | (cp >> 6)); t[1] = (char)(0x80 | (cp & 0x3f)); k = 2; }
+ else if (cp < 0x10000) { t[0] = (char)(0xe0 | (cp >> 12)); t[1] = (char)(0x80 | ((cp >> 6) & 0x3f)); t[2] = (char)(0x80 | (cp & 0x3f)); k = 3; }
+ else { t[0] = (char)(0xf0 | (cp >> 18)); t[1] = (char)(0x80 | ((cp >> 12) & 0x3f)); t[2] = (char)(0x80 | ((cp >> 6) & 0x3f)); t[3] = (char)(0x80 | (cp & 0x3f)); k = 4; }
+ if ((size_t)k > room) return 0;
+ memcpy(o, t, (size_t)k);
+ return k;
+}
+
+void imap_utf7_decode(const char *in, char *out, size_t cap) {
+ if (!cap) return;
+ size_t o = 0;
+ for (size_t i = 0; in[i] && o + 1 < cap;) {
+ if (in[i] != '&') { out[o++] = in[i++]; continue; }
+ i++;
+ if (in[i] == '-') { out[o++] = '&'; i++; continue; }
+ unsigned acc = 0, bits = 0, hi = 0;
+ while (in[i] && in[i] != '-') {
+ const char *p = strchr(b64m, in[i]);
+ if (!p) break;
+ acc = (acc << 6) | (unsigned)(p - b64m);
+ bits += 6;
+ if (bits >= 16) {
+ bits -= 16;
+ unsigned u = (acc >> bits) & 0xffff;
+ if (u >= 0xd800 && u <= 0xdbff) hi = u;
+ else {
+ unsigned cp = u;
+ if (u >= 0xdc00 && u <= 0xdfff && hi) cp = 0x10000 + ((hi - 0xd800) << 10) + (u - 0xdc00);
+ else if (u >= 0xdc00 && u <= 0xdfff) cp = 0xfffd;
+ hi = 0;
+ o += (size_t)put_utf8(out + o, cap - 1 - o, cp);
+ }
+ }
+ i++;
+ }
+ if (in[i] == '-') i++;
+ }
+ out[o] = 0;
+}
+
+void imap_utf7_encode(const char *in, char *out, size_t cap) {
+ if (!cap) return;
+ size_t o = 0;
+ const unsigned char *s = (const unsigned char *)in;
+ for (size_t i = 0; s[i] && o + 1 < cap;) {
+ if (s[i] >= 0x20 && s[i] < 0x7f) {
+ if (s[i] == '&') { if (o + 2 >= cap) break; out[o++] = '&'; out[o++] = '-'; }
+ else out[o++] = (char)s[i];
+ i++;
+ continue;
+ }
+ if (o + 1 >= cap) break;
+ out[o++] = '&';
+ unsigned acc = 0, bits = 0;
+ while (s[i] && (s[i] < 0x20 || s[i] >= 0x7f)) {
+ unsigned cp = s[i], k = 1;
+ if (cp >= 0xf0 && s[i + 1] && s[i + 2] && s[i + 3]) { cp = ((cp & 7u) << 18) | ((s[i + 1] & 0x3fu) << 12) | ((s[i + 2] & 0x3fu) << 6) | (s[i + 3] & 0x3fu); k = 4; }
+ else if (cp >= 0xe0 && s[i + 1] && s[i + 2]) { cp = ((cp & 15u) << 12) | ((s[i + 1] & 0x3fu) << 6) | (s[i + 2] & 0x3fu); k = 3; }
+ else if (cp >= 0xc0 && s[i + 1]) { cp = ((cp & 31u) << 6) | (s[i + 1] & 0x3fu); k = 2; }
+ i += k;
+ unsigned units[2], nu = 0;
+ if (cp >= 0x10000) { cp -= 0x10000; units[nu++] = 0xd800 + (cp >> 10); units[nu++] = 0xdc00 + (cp & 0x3ff); }
+ else units[nu++] = cp;
+ for (unsigned u = 0; u < nu; u++) {
+ acc = (acc << 16) | units[u];
+ bits += 16;
+ while (bits >= 6) { bits -= 6; if (o + 2 < cap) out[o++] = b64m[(acc >> bits) & 63]; }
+ }
+ }
+ if (bits && o + 2 < cap) out[o++] = b64m[(acc << (6 - bits)) & 63];
+ if (o + 1 < cap) out[o++] = '-';
+ }
+ out[o] = 0;
+}
+
+size_t imap_uidset(const uint32_t *u, size_t n, char *out, size_t cap) {
+ size_t o = 0;
+ if (!cap) return 0;
+ out[0] = 0;
+ for (size_t i = 0; i < n;) {
+ size_t j = i;
+ while (j + 1 < n && u[j + 1] == u[j] + 1) j++;
+ char t[32];
+ int k = j > i ? snprintf(t, sizeof t, "%s%u:%u", o ? "," : "", u[i], u[j]) : snprintf(t, sizeof t, "%s%u", o ? "," : "", u[i]);
+ if (o + (size_t)k + 1 > cap) break;
+ memcpy(out + o, t, (size_t)k);
+ o += (size_t)k;
+ out[o] = 0;
+ i = j + 1;
+ }
+ return o;
+}
+
+size_t imap_parse_uidset(const char *s, uint32_t *out, size_t max) {
+ size_t n = 0;
+ while (*s && n < max) {
+ char *e;
+ unsigned long a = strtoul(s, &e, 10);
+ if (e == s) { while (*s && *s != ',') s++; if (*s) s++; continue; }
+ unsigned long b = a;
+ s = e;
+ if (*s == ':') {
+ s++;
+ b = strtoul(s, &e, 10);
+ if (e == s) { b = a; while (*s && *s != ',') s++; }
+ else s = e;
+ }
+ if (b < a) { unsigned long t = a; a = b; b = t; }
+ for (unsigned long x = a; x <= b && n < max; x++) out[n++] = (uint32_t)x;
+ if (*s == ',') s++;
+ }
+ return n;
+}
diff --git a/server/src/mail/imapp.h b/server/src/mail/imapp.h
new file mode 100644
index 0000000..1dcbd98
--- /dev/null
+++ b/server/src/mail/imapp.h
@@ -0,0 +1,61 @@
+/* imapp.h — IMAP4rev1 response parser (RFC 3501) for lord-maild, pure and bounds-checked.
+ *
+ * The connection layer (imap.c) assembles one complete response: the line plus any literals,
+ * kept inline exactly as on the wire ("{N}\r\n" followed by N bytes). imap_parse() turns it into
+ * a small tree of values (atoms, strings, NIL, lists) that live in one arena. Bracketed sections
+ * ("BODY[HEADER.FIELDS (FROM)]<0>", "[UIDVALIDITY 7]") stay a single atom, as clients expect. */
+#ifndef LORD_MAIL_IMAPP_H
+#define LORD_MAIL_IMAPP_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define IMAP_MAX_VALUES 200000
+#define IMAP_MAX_NEST 32
+
+typedef enum { IV_ATOM, IV_STR, IV_NIL, IV_LIST } IvType;
+
+typedef struct IVal IVal;
+struct IVal {
+ IvType type;
+ const char *s; /* IV_ATOM / IV_STR: bytes (points into the response or the arena) */
+ size_t n;
+ IVal *kid, *next; /* IV_LIST children; next sibling */
+};
+
+typedef struct {
+ char tag[32]; /* "*", "+" or the command tag */
+ IVal *first; /* tokens after the tag */
+ char *arena; /* owns values and unescaped strings */
+} IResp;
+
+/* 0 ok, -1 malformed (unbalanced lists, bad literal, too many values). */
+int imap_parse(const char *buf, size_t len, IResp *out);
+void imap_resp_free(IResp *r);
+
+/* Helpers */
+int iv_is(const IVal *v, const char *atom); /* case-insensitive atom match */
+long long iv_num(const IVal *v, long long def);
+IVal *iv_at(IVal *first, int idx); /* n-th sibling */
+int iv_count(const IVal *first);
+/* In a FETCH list ("UID 5 FLAGS (\Seen) BODY[...] {12}..."), the value after `key`.
+ * The key match is case-insensitive; a key with "[" (e.g. "BODY[HEADER") matches by prefix. */
+IVal *imap_fetch_item(IVal *list, const char *key);
+/* Copies a string/atom value (NIL → "") into out; returns length. */
+size_t iv_copy(const IVal *v, char *out, size_t cap);
+/* Response code number from an "[CODE n]" atom anywhere in the response (e.g. UIDVALIDITY). */
+int imap_code_num(const IResp *r, const char *code, unsigned long long *out);
+
+/* IMAP quoted string for a command, or a literal "{n}\r\n…" when needed. The caller frees.
+ * nonsync = 1 uses "{n+}" (LITERAL+). For literals, *needs_cont is set when the server must
+ * answer "+" before the bytes are sent (synchronizing literal). */
+char *imap_quote(const char *s, int nonsync, int *is_literal);
+/* Modified UTF-7 (RFC 3501 §5.1.3) mailbox names. */
+void imap_utf7_decode(const char *in, char *out, size_t cap);
+void imap_utf7_encode(const char *in, char *out, size_t cap);
+/* Compact UID set ("1:5,7,9:12") from an ascending array; returns bytes written. */
+size_t imap_uidset(const uint32_t *uids, size_t n, char *out, size_t cap);
+/* Splits "1:5,7" into the uids (ascending, up to max; "*" is ignored). Returns the count. */
+size_t imap_parse_uidset(const char *s, uint32_t *out, size_t max);
+
+#endif
diff --git a/server/src/mail/mailc.c b/server/src/mail/mailc.c
new file mode 100644
index 0000000..8482d17
--- /dev/null
+++ b/server/src/mail/mailc.c
@@ -0,0 +1,623 @@
+/* mailc.c — see mailc.h. */
+#include "mailc.h"
+#include "proto.h"
+#include "../doc/proto.h"
+#include "../doc/wire.h"
+#include "../sec/json.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <poll.h>
+#include <pthread.h>
+#include <signal.h>
+#include <spawn.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/eventfd.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+extern char **environ;
+
+#define MAX_IMG 256
+#define IMG_BUDGET ((size_t)96 << 20)
+#define MAX_ALLOW 128
+#define MAX_GRANT 64
+
+typedef struct { char host[256]; int port; int suffix; } Allow;
+typedef struct { char host[256]; int port; time_t until; } Grant;
+typedef struct { int handle, w, h; uint32_t *px; uint64_t seq; } Img;
+
+static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t send_mu = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t img_mu = PTHREAD_MUTEX_INITIALIZER;
+static pthread_t thread;
+static int running, sock = -1, wakefd = -1;
+static pid_t child;
+static int next_id = 1, pending;
+static JBuf events;
+static char helper[PATH_MAX], cfg_path[PATH_MAX], cache_path[PATH_MAX];
+static Allow allow[MAX_ALLOW];
+static int nallow;
+static Grant grants[MAX_GRANT];
+static Img imgs[MAX_IMG];
+static size_t img_bytes;
+static uint64_t img_seq;
+static int next_handle = 1;
+static double last_crash;
+
+static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
+
+static void paths(void) {
+ if (cfg_path[0]) return;
+ const char *h = getenv("HOME");
+ if (!h) h = "/nonexistent";
+ snprintf(cfg_path, sizeof cfg_path, "%s/.config/lordos/mail/accounts.json", h);
+ snprintf(cache_path, sizeof cache_path, "%s/.local/share/lordos/mail", h);
+}
+
+const char *mail_config_path(void) { paths(); return cfg_path; }
+const char *mail_cache_path(void) { paths(); return cache_path; }
+
+int mail_available(void) {
+ if (!helper[0]) {
+ char self[PATH_MAX];
+ ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
+ if (n <= 0) return -1;
+ self[n] = 0;
+ char *slash = strrchr(self, '/');
+ if (!slash) return -1;
+ *slash = 0;
+ if (strlen(self) + 12 > sizeof helper) return -1;
+ snprintf(helper, sizeof helper, "%s/lord-maild", self);
+ }
+ struct stat st, me;
+ if (stat(helper, &st) || !S_ISREG(st.st_mode) || !(st.st_mode & S_IXUSR)) return -1;
+ /* owned by root or by lord-server's owner, and not writable by anyone else */
+ if (stat("/proc/self/exe", &me) || (st.st_uid != 0 && st.st_uid != me.st_uid) || (st.st_mode & 022)) return -1;
+ return 0;
+}
+
+/* ---- allowed endpoints ---- */
+
+static int host_ok(const char *h) {
+ size_t n = strlen(h);
+ if (!n || n > 253) return 0;
+ for (size_t i = 0; i < n; i++) {
+ unsigned char c = (unsigned char)h[i];
+ if (!(isalnum(c) || c == '-' || c == '.' || c == ':' || c == '[' || c == ']')) return 0;
+ }
+ return 1;
+}
+
+/* "https://host:port/path" → host, port */
+static int url_host(const char *url, char *host, size_t cap, int *port) {
+ host[0] = 0;
+ *port = 0;
+ if (!url) return 0;
+ int https = !strncasecmp(url, "https://", 8), http = !strncasecmp(url, "http://", 7);
+ if (!https && !http) return 0;
+ const char *p = url + (https ? 8 : 7);
+ const char *e = p + strcspn(p, "/?#");
+ const char *at = memchr(p, '@', (size_t)(e - p));
+ if (at) p = at + 1;
+ const char *colon = NULL;
+ if (*p == '[') { const char *rb = memchr(p, ']', (size_t)(e - p)); if (!rb) return 0; colon = rb + 1 < e && rb[1] == ':' ? rb + 1 : NULL; }
+ else colon = memchr(p, ':', (size_t)(e - p));
+ size_t hl = (size_t)((colon ? colon : e) - p);
+ if (!hl || hl >= cap) return 0;
+ for (size_t i = 0; i < hl; i++) host[i] = (char)tolower((unsigned char)p[i]);
+ host[hl] = 0;
+ *port = colon ? atoi(colon + 1) : (https ? 443 : 80);
+ if (*port <= 0 || *port > 65535) return 0;
+ return host_ok(host);
+}
+
+static void add_allow(Allow *list, int *n, const char *host, int port, int suffix) {
+ if (*n >= MAX_ALLOW || !host || !host_ok(host) || port <= 0 || port > 65535) return;
+ Allow *a = &list[(*n)++];
+ snprintf(a->host, sizeof a->host, "%s", host);
+ for (char *c = a->host; *c; c++) *c = (char)tolower((unsigned char)*c);
+ a->port = port;
+ a->suffix = suffix;
+}
+
+static void allow_server(Allow *list, int *n, const JVal *srv) {
+ if (!srv || srv->type != J_OBJ) return;
+ const char *h = json_str(srv, "host");
+ int port = (int)json_num(srv, "port", 0);
+ if (h) add_allow(list, n, h, port, 0);
+}
+
+static void allow_url(Allow *list, int *n, const char *url) {
+ char host[256];
+ int port;
+ if (!url_host(url, host, sizeof host, &port)) return;
+ add_allow(list, n, host, port, 0);
+ /* CalDAV/CardDAV discovery redirects inside the same provider (iCloud → pNN-caldav.icloud.com):
+ * allow other hosts of the same domain, HTTPS only */
+ const char *dot1 = strrchr(host, '.');
+ if (!dot1) return;
+ const char *dot2 = dot1;
+ while (dot2 > host && dot2[-1] != '.') dot2--;
+ if (dot2 > host && strchr(host, '.') != dot1) add_allow(list, n, dot2, 443, 1);
+}
+
+static int build_allow(const char *json, size_t len, Allow *list) {
+ int n = 0;
+ if (!json || !len) return 0;
+ JDoc d;
+ if (json_parse(json, len, &d, NULL, 0)) return 0;
+ const JVal *acc = json_get(d.root, "accounts");
+ for (const JVal *a = acc && acc->type == J_ARR ? acc->kid : NULL; a; a = a->next) {
+ allow_server(list, &n, json_get(a, "imap"));
+ allow_server(list, &n, json_get(a, "smtp"));
+ allow_url(list, &n, json_str(a, "url")); /* CalDAV/CardDAV accounts */
+ allow_url(list, &n, json_str(a, "caldav"));
+ allow_url(list, &n, json_str(a, "carddav"));
+ }
+ json_free(&d);
+ return n;
+}
+
+static int match(const Allow *list, int n, const char *host, int port) {
+ for (int i = 0; i < n; i++) {
+ if (list[i].port != port) continue;
+ if (!strcasecmp(list[i].host, host)) return 1;
+ if (list[i].suffix) {
+ size_t hl = strlen(host), sl = strlen(list[i].host);
+ if (hl > sl && host[hl - sl - 1] == '.' && !strcasecmp(host + hl - sl, list[i].host)) return 1;
+ }
+ }
+ return 0;
+}
+
+int mail_endpoint_allowed(const char *config_json, size_t len, const char *host, int port) {
+ Allow tmp[MAX_ALLOW];
+ int n = build_allow(config_json, len, tmp);
+ return match(tmp, n, host, port);
+}
+
+static char *read_config(size_t *len) {
+ paths();
+ *len = 0;
+ int fd = open(cfg_path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return NULL;
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size > MAIL_CONFIG_MAX) { close(fd); return NULL; }
+ char *b = malloc((size_t)st.st_size + 1);
+ if (!b) { close(fd); return NULL; }
+ ssize_t r = read(fd, b, (size_t)st.st_size);
+ close(fd);
+ if (r < 0) { free(b); return NULL; }
+ b[r] = 0;
+ JDoc d;
+ if (json_parse(b, (size_t)r, &d, NULL, 0)) { free(b); return NULL; }
+ json_free(&d);
+ *len = (size_t)r;
+ return b;
+}
+
+void mail_allow_hosts(const char *const *urls, int n, int seconds) {
+ time_t until = time(NULL) + (seconds > 0 && seconds < 3600 ? seconds : 600);
+ pthread_mutex_lock(&mu);
+ for (int i = 0; i < n; i++) {
+ char host[256];
+ int port;
+ if (!url_host(urls[i], host, sizeof host, &port)) continue;
+ if (port != 80 && port != 443) continue; /* remote images: plain web ports only */
+ int slot = -1;
+ for (int k = 0; k < MAX_GRANT; k++) {
+ if (grants[k].host[0] && !strcmp(grants[k].host, host) && grants[k].port == port) { slot = k; break; }
+ if (slot < 0 && (!grants[k].host[0] || grants[k].until < time(NULL))) slot = k;
+ }
+ if (slot < 0) slot = 0;
+ snprintf(grants[slot].host, sizeof grants[slot].host, "%s", host);
+ grants[slot].port = port;
+ grants[slot].until = until;
+ }
+ pthread_mutex_unlock(&mu);
+}
+
+static int allowed_now(const char *host, int port) {
+ int ok = 0;
+ pthread_mutex_lock(&mu);
+ if (match(allow, nallow, host, port)) ok = 1;
+ time_t now = time(NULL);
+ for (int k = 0; !ok && k < MAX_GRANT; k++)
+ if (grants[k].host[0] && grants[k].until >= now && grants[k].port == port && !strcasecmp(grants[k].host, host)) ok = 2;
+ pthread_mutex_unlock(&mu);
+ return ok;
+}
+
+/* ---- events ---- */
+
+static void ev_push(int id, const char *type, const char *data, size_t dlen) {
+ pthread_mutex_lock(&mu);
+ if (events.n) jb_raw(&events, ",");
+ jb_printf(&events, "{\"id\":%d,\"type\":\"%s\"", id, type);
+ if (data && dlen) {
+ jb_raw(&events, ",\"data\":");
+ /* the helper's JSON is re-validated before JS sees it */
+ JDoc d;
+ if (!json_parse(data, dlen, &d, NULL, 0)) { json_free(&d); char *tmp = malloc(dlen + 1); if (tmp) { memcpy(tmp, data, dlen); tmp[dlen] = 0; jb_raw(&events, tmp); free(tmp); } else jb_raw(&events, "null"); }
+ else jb_raw(&events, "{\"error\":\"bad-json\"}");
+ }
+ jb_raw(&events, "}");
+ if (strcmp(type, "evt") && pending > 0) pending--;
+ pthread_mutex_unlock(&mu);
+}
+
+char *mail_poll(void) {
+ pthread_mutex_lock(&mu);
+ char *r = NULL;
+ if (events.n) {
+ size_t n = events.n;
+ r = malloc(n + 3);
+ if (r) { r[0] = '['; memcpy(r + 1, events.p, n); r[n + 1] = ']'; r[n + 2] = 0; }
+ events.n = 0;
+ }
+ pthread_mutex_unlock(&mu);
+ return r;
+}
+
+int mail_pending(void) { pthread_mutex_lock(&mu); int p = pending; pthread_mutex_unlock(&mu); return p; }
+
+/* ---- images ---- */
+
+static int img_store(int w, int h, int fd) {
+ size_t bytes = (size_t)w * (size_t)h * 4;
+ void *m = mmap(NULL, bytes, PROT_READ, MAP_SHARED, fd, 0);
+ if (m == MAP_FAILED) return -1;
+ uint32_t *px = malloc(bytes);
+ if (!px) { munmap(m, bytes); return -1; }
+ memcpy(px, m, bytes);
+ munmap(m, bytes);
+ pthread_mutex_lock(&img_mu);
+ /* make room: oldest first */
+ while (img_bytes + bytes > IMG_BUDGET) {
+ int old = -1;
+ for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && (old < 0 || imgs[i].seq < imgs[old].seq)) old = i;
+ if (old < 0) break;
+ img_bytes -= (size_t)imgs[old].w * (size_t)imgs[old].h * 4;
+ free(imgs[old].px);
+ memset(&imgs[old], 0, sizeof imgs[old]);
+ }
+ int slot = -1;
+ for (int i = 0; i < MAX_IMG; i++) if (!imgs[i].px) { slot = i; break; }
+ if (slot < 0) {
+ slot = 0;
+ for (int i = 1; i < MAX_IMG; i++) if (imgs[i].seq < imgs[slot].seq) slot = i;
+ img_bytes -= (size_t)imgs[slot].w * (size_t)imgs[slot].h * 4;
+ free(imgs[slot].px);
+ }
+ imgs[slot] = (Img){ next_handle++, w, h, px, ++img_seq };
+ img_bytes += bytes;
+ int handle = imgs[slot].handle;
+ pthread_mutex_unlock(&img_mu);
+ return handle;
+}
+
+const uint32_t *mail_image_lock(int handle, int *w, int *h) {
+ pthread_mutex_lock(&img_mu);
+ for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].handle == handle) { *w = imgs[i].w; *h = imgs[i].h; imgs[i].seq = ++img_seq; return imgs[i].px; }
+ return NULL;
+}
+void mail_image_unlock(void) { pthread_mutex_unlock(&img_mu); }
+void mail_image_release(int handle) {
+ pthread_mutex_lock(&img_mu);
+ for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].handle == handle) {
+ img_bytes -= (size_t)imgs[i].w * (size_t)imgs[i].h * 4;
+ free(imgs[i].px);
+ memset(&imgs[i], 0, sizeof imgs[i]);
+ }
+ pthread_mutex_unlock(&img_mu);
+}
+
+/* ---- connector ---- */
+
+static int v4_public(uint32_t a) { /* host byte order */
+ uint8_t b0 = (uint8_t)(a >> 24), b1 = (uint8_t)(a >> 16);
+ if (b0 == 0 || b0 == 10 || b0 == 127) return 0; /* this net, private, loopback */
+ if (b0 == 100 && (b1 & 0xc0) == 64) return 0; /* 100.64/10 carrier NAT */
+ if (b0 == 169 && b1 == 254) return 0; /* link-local, cloud metadata */
+ if (b0 == 172 && (b1 & 0xf0) == 16) return 0; /* 172.16/12 */
+ if (b0 == 192 && b1 == 168) return 0; /* 192.168/16 */
+ if (b0 == 192 && b1 == 0 && (uint8_t)(a >> 8) == 0) return 0; /* 192.0.0/24 IETF */
+ if (b0 == 198 && (b1 & 0xfe) == 18) return 0; /* 198.18/15 benchmarking */
+ if (b0 >= 224) return 0; /* multicast, reserved, broadcast */
+ return 1;
+}
+
+int mail_addr_public(const struct sockaddr *sa) {
+ if (sa->sa_family == AF_INET) return v4_public(ntohl(((const struct sockaddr_in *)(const void *)sa)->sin_addr.s_addr));
+ if (sa->sa_family != AF_INET6) return 0;
+ const uint8_t *b = ((const struct sockaddr_in6 *)(const void *)sa)->sin6_addr.s6_addr;
+ static const uint8_t zero[16];
+ if (!memcmp(b, zero, 16)) return 0; /* :: */
+ if (!memcmp(b, zero, 15) && b[15] == 1) return 0; /* ::1 */
+ if (b[0] == 0xfe && (b[1] & 0xc0) == 0x80) return 0; /* fe80::/10 link-local */
+ if (b[0] == 0xfe && (b[1] & 0xc0) == 0xc0) return 0; /* fec0::/10 site-local (old) */
+ if ((b[0] & 0xfe) == 0xfc) return 0; /* fc00::/7 unique local */
+ if (b[0] == 0xff) return 0; /* multicast */
+ uint32_t v4 = (uint32_t)b[12] << 24 | (uint32_t)b[13] << 16 | (uint32_t)b[14] << 8 | b[15];
+ /* v4-mapped ::ffff:a.b.c.d and v4-compatible ::a.b.c.d */
+ if (!memcmp(b, zero, 10) && b[10] == 0xff && b[11] == 0xff) return v4_public(v4);
+ if (!memcmp(b, zero, 12)) return 0;
+ /* NAT64 64:ff9b::/96 (and the local-use 64:ff9b:1::/48): judge the embedded IPv4 */
+ if (b[0] == 0 && b[1] == 0x64 && b[2] == 0xff && b[3] == 0x9b) { if (b[4] == 0 && b[5] == 1) return 0; return v4_public(v4); }
+ if (b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x0d && b[3] == 0xb8) return 0; /* 2001:db8::/32 documentation */
+ if (b[0] == 0x20 && b[1] == 0x02) return v4_public((uint32_t)b[2] << 24 | (uint32_t)b[3] << 16 | (uint32_t)b[4] << 8 | b[5]); /* 6to4 */
+ return 1;
+}
+
+typedef struct { uint32_t cid; char host[256]; int port; int image; } ConnReq;
+
+static int send_msg(uint32_t op, uint32_t id, const char *json, int fd) {
+ pthread_mutex_lock(&send_mu);
+ int s = sock;
+ int r = s >= 0 ? doc_send(s, op, id, json, json ? strlen(json) : 0, fd >= 0 ? &fd : NULL, fd >= 0 ? 1 : 0) : -1;
+ pthread_mutex_unlock(&send_mu);
+ return r;
+}
+
+static int connect_timeout(const struct addrinfo *ai, int ms) {
+ int fd = socket(ai->ai_family, ai->ai_socktype | SOCK_CLOEXEC | SOCK_NONBLOCK, ai->ai_protocol);
+ if (fd < 0) return -1;
+ int r = connect(fd, ai->ai_addr, ai->ai_addrlen);
+ if (r && errno != EINPROGRESS) { close(fd); return -1; }
+ if (r) {
+ struct pollfd p = { fd, POLLOUT, 0 };
+ if (poll(&p, 1, ms) != 1) { close(fd); return -1; }
+ int err = 0;
+ socklen_t el = sizeof err;
+ if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el) || err) { close(fd); return -1; }
+ }
+ int fl = fcntl(fd, F_GETFL);
+ fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
+ return fd;
+}
+
+static void *connector(void *arg) {
+ ConnReq *q = arg;
+ char port[8];
+ snprintf(port, sizeof port, "%d", q->port);
+ struct addrinfo hints = { 0 }, *res = NULL;
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = AI_ADDRCONFIG;
+ int fd = -1;
+ const char *why = "dns";
+ if (!getaddrinfo(q->host, port, &hints, &res)) {
+ why = "connect";
+ for (struct addrinfo *a = res; a && fd < 0; a = a->ai_next) {
+ /* image hosts (chosen by whoever sent the mail): never loopback, LAN or link-local,
+ * judged on the resolved address we actually connect to (no DNS rebinding) */
+ if (q->image && !mail_addr_public(a->ai_addr)) { why = "denied"; continue; }
+ fd = connect_timeout(a, 10000);
+ }
+ freeaddrinfo(res);
+ }
+ if (fd >= 0) { send_msg(MQ_SOCK, q->cid, "{}", fd); close(fd); }
+ else { char j[64]; snprintf(j, sizeof j, "{\"error\":\"%s\"}", why); send_msg(MQ_SOCK, q->cid, j, -1); }
+ free(q);
+ return NULL;
+}
+
+static void on_connect(uint32_t cid, const char *json, size_t len) {
+ JDoc d;
+ char host[256] = "";
+ int port = 0;
+ if (json && !json_parse(json, len, &d, NULL, 0)) {
+ const char *h = json_str(d.root, "host");
+ if (h && strlen(h) < sizeof host) { snprintf(host, sizeof host, "%s", h); for (char *c = host; *c; c++) *c = (char)tolower((unsigned char)*c); }
+ port = (int)json_num(d.root, "port", 0);
+ json_free(&d);
+ }
+ int how = host_ok(host) && port > 0 && port <= 65535 ? allowed_now(host, port) : 0;
+ if (!how) {
+ fprintf(stderr, "lord-server: lord-maild asked for %s:%d, which is not a configured server: denied\n", host, port);
+ send_msg(MQ_SOCK, cid, "{\"error\":\"denied\"}", -1);
+ return;
+ }
+ ConnReq *q = malloc(sizeof *q);
+ if (!q) { send_msg(MQ_SOCK, cid, "{\"error\":\"connect\"}", -1); return; }
+ q->cid = cid;
+ snprintf(q->host, sizeof q->host, "%s", host);
+ q->port = port;
+ q->image = how == 2;
+ pthread_t t;
+ pthread_attr_t at;
+ pthread_attr_init(&at);
+ pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
+ if (pthread_create(&t, &at, connector, q)) { free(q); send_msg(MQ_SOCK, cid, "{\"error\":\"connect\"}", -1); }
+ pthread_attr_destroy(&at);
+}
+
+/* ---- the helper process ---- */
+
+static void *loop(void *arg) {
+ (void)arg;
+ for (;;) {
+ struct pollfd p[2] = { { sock, POLLIN, 0 }, { wakefd, POLLIN, 0 } };
+ int r = poll(p, 2, -1);
+ if (r < 0) { if (errno == EINTR) continue; break; }
+ if (p[1].revents & POLLIN) { uint64_t v; if (read(wakefd, &v, sizeof v) < 0) { /* nothing */ } }
+ if (!(p[0].revents & (POLLIN | POLLHUP | POLLERR))) continue;
+ DocMsg m;
+ int k = doc_recv(sock, &m);
+ if (k) {
+ /* the helper is gone: every pending request fails, and the next one restarts it */
+ pthread_mutex_lock(&send_mu);
+ close(sock);
+ sock = -1;
+ pthread_mutex_unlock(&send_mu);
+ if (child > 0) { kill(child, SIGKILL); waitpid(child, NULL, 0); child = 0; }
+ pthread_mutex_lock(&mu);
+ int np = pending;
+ pending = 0;
+ running = 0;
+ pthread_mutex_unlock(&mu);
+ (void)np;
+ ev_push(0, "crash", NULL, 0);
+ last_crash = now_ms();
+ break;
+ }
+ switch (m.h.op) {
+ case MR_DONE: ev_push((int)m.h.id, "done", m.json, m.len); break;
+ case MR_ERR: ev_push((int)m.h.id, "err", m.json, m.len); break;
+ case MR_EVT: ev_push(0, "evt", m.json, m.len); break;
+ case MR_CONNECT: on_connect(m.h.id, m.json, m.len); break;
+ case MR_IMG: {
+ JDoc d;
+ int w = 0, h = 0;
+ if (m.json && !json_parse(m.json, m.len, &d, NULL, 0)) { w = (int)json_num(d.root, "w", 0); h = (int)json_num(d.root, "h", 0); json_free(&d); }
+ int handle = -1;
+ if (m.nfds == 1 && w > 0 && h > 0 && w <= 8192 && h <= 8192 && doc_check_sealed(m.fds[0], (size_t)w * (size_t)h * 4) >= 0)
+ handle = img_store(w, h, m.fds[0]);
+ char j[96];
+ if (handle > 0) snprintf(j, sizeof j, "{\"image\":%d,\"w\":%d,\"h\":%d}", handle, w, h);
+ else snprintf(j, sizeof j, "{\"error\":\"image\"}");
+ ev_push((int)m.h.id, handle > 0 ? "done" : "err", j, strlen(j));
+ break;
+ }
+ default: break;
+ }
+ doc_msg_free(&m);
+ }
+ return NULL;
+}
+
+static int local_zone(char *out, size_t cap) {
+ char l[PATH_MAX];
+ ssize_t n = readlink("/etc/localtime", l, sizeof l - 1);
+ out[0] = 0;
+ if (n <= 0) return 0;
+ l[n] = 0;
+ const char *z = strstr(l, "zoneinfo/");
+ if (!z) return 0;
+ snprintf(out, cap, "%s", z + 9);
+ return 1;
+}
+
+static int mkdirs(const char *p, mode_t mode) {
+ char tmp[PATH_MAX];
+ snprintf(tmp, sizeof tmp, "%s", p);
+ for (char *s = tmp + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(tmp, mode); *s = '/'; }
+ return mkdir(tmp, mode) && errno != EEXIST ? -1 : 0;
+}
+
+int mail_start(void) {
+ pthread_mutex_lock(&mu);
+ int r = running;
+ pthread_mutex_unlock(&mu);
+ if (r) return 0;
+ if (mail_available()) return -1;
+ if (last_crash && now_ms() - last_crash < 3000) return -1; /* do not spin on a crash loop */
+ if (thread) { pthread_join(thread, NULL); thread = 0; }
+ paths();
+ if (mkdirs(cache_path, 0700)) return -1;
+ int dfd = open(cache_path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
+ if (dfd < 0) return -1;
+ int sv[2];
+ if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sv)) { close(dfd); return -1; }
+ posix_spawn_file_actions_t fa;
+ posix_spawn_file_actions_init(&fa);
+ posix_spawn_file_actions_adddup2(&fa, sv[1], 3);
+ posix_spawnattr_t at;
+ posix_spawnattr_init(&at);
+ sigset_t none, all;
+ sigemptyset(&none);
+ sigfillset(&all);
+ posix_spawnattr_setsigmask(&at, &none);
+ posix_spawnattr_setsigdefault(&at, &all);
+ posix_spawnattr_setflags(&at, POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF);
+ char henv[PATH_MAX + 8], *envp[6];
+ int ne = 0;
+ const char *home = getenv("HOME");
+ if (home) { snprintf(henv, sizeof henv, "HOME=%s", home); envp[ne++] = henv; }
+ envp[ne++] = "LANG=C.UTF-8";
+ if (getenv("LORD_MAIL_DEBUG")) envp[ne++] = "LORD_MAIL_DEBUG=1";
+ envp[ne] = NULL;
+ char *argv[] = { "lord-maild", NULL };
+ pid_t pid;
+ int e = posix_spawn(&pid, helper, &fa, &at, argv, envp);
+ posix_spawn_file_actions_destroy(&fa);
+ posix_spawnattr_destroy(&at);
+ close(sv[1]);
+ if (e) { close(sv[0]); close(dfd); return -1; }
+ size_t clen;
+ char *cfg = read_config(&clen);
+ pthread_mutex_lock(&mu);
+ nallow = build_allow(cfg, clen, allow);
+ pthread_mutex_unlock(&mu);
+ char zone[128];
+ local_zone(zone, sizeof zone);
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"config\":");
+ jb_raw(&b, cfg ? cfg : "{}");
+ jb_raw(&b, ",\"zone\":");
+ jb_str(&b, zone);
+ jb_raw(&b, "}");
+ free(cfg);
+ int ok = !b.oom && doc_send(sv[0], MQ_INIT, 0, b.p, b.n, &dfd, 1) == 0;
+ jb_free(&b);
+ close(dfd);
+ if (!ok) { close(sv[0]); kill(pid, SIGKILL); waitpid(pid, NULL, 0); return -1; }
+ if (wakefd < 0) wakefd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
+ pthread_mutex_lock(&send_mu);
+ sock = sv[0];
+ pthread_mutex_unlock(&send_mu);
+ child = pid;
+ pthread_mutex_lock(&mu);
+ running = 1;
+ pthread_mutex_unlock(&mu);
+ if (pthread_create(&thread, NULL, loop, NULL)) { pthread_mutex_lock(&mu); running = 0; pthread_mutex_unlock(&mu); return -1; }
+ return 0;
+}
+
+int mail_request(const char *json, size_t len, int *fds, int nfds) {
+ if (mail_start()) { for (int i = 0; i < nfds; i++) close(fds[i]); return -1; }
+ pthread_mutex_lock(&mu);
+ int id = next_id++;
+ if (next_id > 1 << 30) next_id = 1;
+ pending++;
+ pthread_mutex_unlock(&mu);
+ pthread_mutex_lock(&send_mu);
+ int r = sock >= 0 ? doc_send(sock, MQ_REQ, (uint32_t)id, json, len, nfds ? fds : NULL, nfds) : -1;
+ pthread_mutex_unlock(&send_mu);
+ for (int i = 0; i < nfds; i++) close(fds[i]);
+ if (r) { pthread_mutex_lock(&mu); pending--; pthread_mutex_unlock(&mu); return -1; }
+ return id;
+}
+
+void mail_reload_config(void) {
+ size_t clen;
+ char *cfg = read_config(&clen);
+ pthread_mutex_lock(&mu);
+ nallow = build_allow(cfg, clen, allow);
+ int r = running;
+ pthread_mutex_unlock(&mu);
+ if (r) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"config\":");
+ jb_raw(&b, cfg ? cfg : "{}");
+ jb_raw(&b, "}");
+ if (!b.oom) send_msg(MQ_CONFIG, 0, b.p, -1);
+ jb_free(&b);
+ }
+ free(cfg);
+}
diff --git a/server/src/mail/mailc.h b/server/src/mail/mailc.h
new file mode 100644
index 0000000..fe6e550
--- /dev/null
+++ b/server/src/mail/mailc.h
@@ -0,0 +1,43 @@
+/* mailc.h — lord-server's side of lord-maild (see proto.h and docs/MAIL.md).
+ *
+ * One lord-maild per session, started on first use with a fixed path (next to this binary), no
+ * arguments and a minimal environment. A thread of ours talks to it, so the compositor never
+ * waits: results and events queue up and JS reads them with mail_poll() (lord.mail.poll).
+ *
+ * This side also owns the network policy: lord-maild cannot open sockets, and asks us for a
+ * connection to host:port. We connect only to the servers of the configured accounts (read from
+ * ~/.config/lordos/mail/accounts.json, which only lord.mail.saveConfig can write) and, for ten
+ * minutes, to the image hosts of a message whose remote images the user chose to load. */
+#ifndef LORD_MAIL_MAILC_H
+#define LORD_MAIL_MAILC_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+int mail_available(void); /* 0 if the helper binary is there */
+int mail_start(void); /* 0 if running (starts it if needed) */
+/* Request: JSON text + fds of files (mail_request takes ownership). id > 0 or -1. */
+int mail_request(const char *json, size_t len, int *fds, int nfds);
+char *mail_poll(void); /* JSON array of events (malloc) or NULL */
+int mail_pending(void);
+/* Re-reads the accounts file, rebuilds the allowed endpoints and tells lord-maild. */
+void mail_reload_config(void);
+/* Remote images of one message: allow these http(s) hosts for a while. */
+void mail_allow_hosts(const char *const *urls, int n, int seconds);
+const char *mail_config_path(void); /* ~/.config/lordos/mail/accounts.json */
+const char *mail_cache_path(void); /* ~/.local/share/lordos/mail */
+
+/* Decoded images (ARGB32 premultiplied) returned by lord-maild. */
+const uint32_t *mail_image_lock(int handle, int *w, int *h);
+void mail_image_unlock(void);
+void mail_image_release(int handle);
+
+/* Pure check used by the connector and its test: is host:port allowed by this config JSON? */
+int mail_endpoint_allowed(const char *config_json, size_t len, const char *host, int port);
+
+/* Is this resolved address on the public Internet? (Remote-image hosts must be: no loopback,
+ * private, link-local, CGNAT, multicast or reserved ranges, also behind v4-mapped/NAT64/6to4.) */
+struct sockaddr;
+int mail_addr_public(const struct sockaddr *sa);
+
+#endif
diff --git a/server/src/mail/maild.c b/server/src/mail/maild.c
new file mode 100644
index 0000000..8937ab0
--- /dev/null
+++ b/server/src/mail/maild.c
@@ -0,0 +1,670 @@
+/* maild.c — lord-maild: the helper that speaks IMAP, SMTP, CalDAV and CardDAV for Mail,
+ * Calendar, Contacts and Reminders (see maild.h, proto.h and docs/MAIL.md).
+ *
+ * lord-server starts it with a fixed path, no arguments, a minimal environment and the channel on
+ * fd 3. Before reading anything from the network it:
+ * - dies with lord-server (PR_SET_PDEATHSIG) and never dumps core;
+ * - loads the system CA bundle and the local time zone;
+ * - receives the cache folder as an open fd (MQ_INIT) and locks itself in with the shared
+ * helper sandbox (sandbox_apply_helper): Landlock with read-only /usr and the zoneinfo, write
+ * access only below the cache folder; seccomp without socket/connect/bind/exec/fork; no
+ * capabilities. It cannot open a single socket: every connection comes from lord-server,
+ * which only connects to the servers of the configured accounts. */
+#include "maild.h"
+#include "proto.h"
+#include "ical.h"
+#include "../doc/proto.h"
+#include "../sec/sandbox.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/eventfd.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <time.h>
+#include <unistd.h>
+
+#define SOCK 3
+
+pthread_mutex_t G = PTHREAD_MUTEX_INITIALIZER;
+int cache_fd = -1;
+Account *accounts[MAIL_MAX_ACCOUNTS * 2];
+int naccounts;
+static pthread_mutex_t send_mu = PTHREAD_MUTEX_INITIALIZER;
+static int debug;
+
+void dbg(const char *fmt, ...) {
+ if (!debug) return;
+ va_list ap;
+ va_start(ap, fmt);
+ fprintf(stderr, "lord-maild: ");
+ vfprintf(stderr, fmt, ap);
+ fprintf(stderr, "\n");
+ va_end(ap);
+}
+
+/* ---- channel ---- */
+
+static void send_raw(uint32_t op, uint32_t id, const char *json, size_t len, const int *fds, int nfds) {
+ pthread_mutex_lock(&send_mu);
+ if (doc_send(SOCK, op, id, json, len, fds, nfds)) dbg("send failed: %s", strerror(errno));
+ pthread_mutex_unlock(&send_mu);
+}
+
+void reply_done(uint32_t id, JBuf *b) {
+ if (b->oom) { jb_free(b); reply_err(id, "too-big", ""); return; }
+ send_raw(MR_DONE, id, b->p ? b->p : "{}", b->p ? b->n : 2, NULL, 0);
+ jb_free(b);
+}
+
+void reply_err(uint32_t id, const char *code, const char *detail) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"error\":");
+ jb_str(&b, code);
+ jb_raw(&b, ",\"detail\":");
+ jb_str(&b, detail ? detail : "");
+ jb_raw(&b, "}");
+ send_raw(MR_ERR, id, b.p, b.n, NULL, 0);
+ jb_free(&b);
+}
+
+void send_event(JBuf *b) {
+ if (!b->oom && b->p) send_raw(MR_EVT, 0, b->p, b->n, NULL, 0);
+ jb_free(b);
+}
+
+void reply_image(uint32_t id, const uint32_t *argb, int w, int h) {
+ size_t bytes = (size_t)w * (size_t)h * 4;
+ int fd = doc_memfd("lord-maild-img", argb, bytes);
+ if (fd < 0) { reply_err(id, "image", "memfd"); return; }
+ char j[64];
+ snprintf(j, sizeof j, "{\"w\":%d,\"h\":%d}", w, h);
+ send_raw(MR_IMG, id, j, strlen(j), &fd, 1);
+ close(fd);
+}
+
+/* ---- connections through lord-server ---- */
+
+typedef struct { uint32_t cid; int done, fd; char why[24]; } Pend;
+static Pend pend[64];
+static pthread_mutex_t pend_mu = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t pend_cv = PTHREAD_COND_INITIALIZER;
+static uint32_t next_cid = 1;
+
+int net_connect(const char *host, int port, char *why, size_t wcap) {
+ pthread_mutex_lock(&pend_mu);
+ int slot = -1;
+ for (int i = 0; i < 64; i++) if (!pend[i].cid) { slot = i; break; }
+ if (slot < 0) { pthread_mutex_unlock(&pend_mu); snprintf(why, wcap, "busy"); return -1; }
+ uint32_t cid = next_cid++;
+ pend[slot] = (Pend){ cid, 0, -1, "" };
+ pthread_mutex_unlock(&pend_mu);
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"host\":");
+ jb_str(&b, host);
+ jb_printf(&b, ",\"port\":%d}", port);
+ send_raw(MR_CONNECT, cid, b.p, b.n, NULL, 0);
+ jb_free(&b);
+ struct timespec dl;
+ clock_gettime(CLOCK_REALTIME, &dl);
+ dl.tv_sec += 40;
+ pthread_mutex_lock(&pend_mu);
+ while (!pend[slot].done) if (pthread_cond_timedwait(&pend_cv, &pend_mu, &dl) == ETIMEDOUT) break;
+ int fd = pend[slot].done ? pend[slot].fd : -1;
+ snprintf(why, wcap, "%s", pend[slot].done ? pend[slot].why : "timeout");
+ pend[slot].cid = 0;
+ pthread_mutex_unlock(&pend_mu);
+ return fd;
+}
+
+static void on_sock(DocMsg *m) {
+ pthread_mutex_lock(&pend_mu);
+ for (int i = 0; i < 64; i++) {
+ if (pend[i].cid != m->h.id) continue;
+ pend[i].done = 1;
+ if (m->nfds >= 1) { pend[i].fd = m->fds[0]; m->fds[0] = -1; }
+ else {
+ JDoc d;
+ snprintf(pend[i].why, sizeof pend[i].why, "connect");
+ if (m->json && !json_parse(m->json, m->len, &d, NULL, 0)) {
+ const char *e = json_str(d.root, "error");
+ if (e) snprintf(pend[i].why, sizeof pend[i].why, "%s", e);
+ json_free(&d);
+ }
+ }
+ }
+ pthread_cond_broadcast(&pend_cv);
+ pthread_mutex_unlock(&pend_mu);
+}
+
+Conn *open_conn(const char *acct, const char *host, int port, int tls_now, const char *pin, TlsInfo *ti, char *why, size_t wcap) {
+ int fd = net_connect(host, port, why, wcap);
+ if (fd < 0) return NULL;
+ Conn *c = conn_new(fd, host, 60000);
+ if (!c) { close(fd); snprintf(why, wcap, "memory"); return NULL; }
+ if (tls_now) {
+ if (conn_tls(c, pin, ti)) {
+ snprintf(why, wcap, "%s", ti->code ? "cert" : "tls");
+ if (ti->code) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"cert\",\"acct\":"); jb_str(&b, acct);
+ jb_raw(&b, ",\"host\":"); jb_str(&b, host);
+ jb_printf(&b, ",\"port\":%d,\"reason\":", port); jb_str(&b, ti->reason);
+ jb_raw(&b, ",\"subject\":"); jb_str(&b, ti->subject);
+ jb_raw(&b, ",\"issuer\":"); jb_str(&b, ti->issuer);
+ jb_raw(&b, ",\"sha256\":"); jb_str(&b, ti->sha256);
+ jb_raw(&b, ",\"notAfter\":"); jb_str(&b, ti->not_after);
+ jb_raw(&b, "}");
+ send_event(&b);
+ }
+ conn_close(c);
+ return NULL;
+ }
+ }
+ return c;
+}
+
+/* ---- files ---- */
+
+int fs_mkdirs(const char *rel) {
+ char tmp[1024];
+ snprintf(tmp, sizeof tmp, "%s", rel);
+ for (char *s = tmp + 1; *s; s++) if (*s == '/') { *s = 0; mkdirat(cache_fd, tmp, 0700); *s = '/'; }
+ return mkdirat(cache_fd, tmp, 0700) && errno != EEXIST ? -1 : 0;
+}
+
+char *fs_read(const char *rel, size_t *len, size_t max) {
+ *len = 0;
+ int fd = openat(cache_fd, rel, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return NULL;
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || (size_t)st.st_size > max) { close(fd); return NULL; }
+ char *b = malloc((size_t)st.st_size + 1);
+ if (!b) { close(fd); return NULL; }
+ size_t got = 0;
+ while (got < (size_t)st.st_size) {
+ ssize_t r = read(fd, b + got, (size_t)st.st_size - got);
+ if (r <= 0) { if (r < 0 && errno == EINTR) continue; break; }
+ got += (size_t)r;
+ }
+ close(fd);
+ b[got] = 0;
+ *len = got;
+ return b;
+}
+
+int fs_write(const char *rel, const void *data, size_t len) {
+ char tmp[1100];
+ static unsigned seq;
+ snprintf(tmp, sizeof tmp, "%s.%u.%u.tmp", rel, (unsigned)getpid(), __atomic_add_fetch(&seq, 1, __ATOMIC_RELAXED));
+ int fd = openat(cache_fd, tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600);
+ if (fd < 0) {
+ /* parent folder missing: create it */
+ char dir[1024];
+ snprintf(dir, sizeof dir, "%s", rel);
+ char *sl = strrchr(dir, '/');
+ if (sl) { *sl = 0; fs_mkdirs(dir); }
+ fd = openat(cache_fd, tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600);
+ if (fd < 0) return -1;
+ }
+ const char *p = data;
+ size_t off = 0;
+ while (off < len) {
+ ssize_t w = write(fd, p + off, len - off);
+ if (w <= 0) { if (w < 0 && errno == EINTR) continue; close(fd); unlinkat(cache_fd, tmp, 0); return -1; }
+ off += (size_t)w;
+ }
+ close(fd);
+ if (renameat(cache_fd, tmp, cache_fd, rel)) { unlinkat(cache_fd, tmp, 0); return -1; }
+ return 0;
+}
+
+int fs_exists(const char *rel) { struct stat st; return fstatat(cache_fd, rel, &st, AT_SYMLINK_NOFOLLOW) == 0; }
+int fs_unlink(const char *rel) { return unlinkat(cache_fd, rel, 0); }
+
+/* Files only: the sandbox lets us create folders but not remove them (no REMOVE_DIR). */
+int fs_rmtree(const char *rel) {
+ int dfd = openat(cache_fd, rel, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
+ if (dfd < 0) return -1;
+ DIR *d = fdopendir(dfd);
+ if (!d) { close(dfd); return -1; }
+ struct dirent *e;
+ while ((e = readdir(d))) {
+ if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
+ char sub[1200];
+ snprintf(sub, sizeof sub, "%s/%s", rel, e->d_name);
+ if (e->d_type == DT_DIR) fs_rmtree(sub);
+ else unlinkat(cache_fd, sub, 0);
+ }
+ closedir(d);
+ return 0;
+}
+
+void fs_safe_name(const char *in, char *out, size_t cap) {
+ size_t o = 0;
+ for (const char *s = in ? in : ""; *s && o + 1 < cap; s++) {
+ unsigned char c = (unsigned char)*s;
+ if (c == '/' || c == '\\' || c < 0x20 || c == 0x7f) c = '_';
+ out[o++] = (char)c;
+ }
+ out[o] = 0;
+ while (out[0] == '.') out[0] = '_';
+ if (!out[0]) snprintf(out, cap, "file");
+}
+
+void fs_hash(const char *s, char *out) {
+ uint64_t h = 1469598103934665603ull;
+ for (; *s; s++) { h ^= (unsigned char)*s; h *= 1099511628211ull; }
+ snprintf(out, 17, "%016llx", (unsigned long long)h);
+}
+
+/* ---- jobs ---- */
+
+Job *job_new(int kind, uint32_t req, int prio) {
+ Job *j = calloc(1, sizeof *j);
+ if (j) { j->kind = kind; j->req = req; j->prio = prio; }
+ return j;
+}
+
+void job_free(Job *j) {
+ if (!j) return;
+ for (int i = 0; i < j->nfds; i++) if (j->fds[i] >= 0) close(j->fds[i]);
+ free(j->uids);
+ free(j->arg);
+ free(j);
+}
+
+void job_push(Account *a, Job *j) {
+ pthread_mutex_lock(&a->qmu);
+ /* higher priority first; same priority in order */
+ Job **p = &a->jobs;
+ while (*p && (*p)->prio >= j->prio) p = &(*p)->next;
+ j->next = *p;
+ *p = j;
+ pthread_mutex_unlock(&a->qmu);
+ uint64_t one = 1;
+ if (write(a->wake, &one, sizeof one) < 0) { /* already signalled */ }
+}
+
+Job *job_pop(Account *a) {
+ pthread_mutex_lock(&a->qmu);
+ Job *j = a->jobs;
+ if (j) a->jobs = j->next;
+ pthread_mutex_unlock(&a->qmu);
+ return j;
+}
+
+/* ---- accounts ---- */
+
+Account *acct_get(const char *id) {
+ if (!id) return NULL;
+ for (int i = 0; i < naccounts; i++) if (accounts[i] && !accounts[i]->stop && !strcmp(accounts[i]->id, id)) return accounts[i];
+ return NULL;
+}
+
+void acct_status(Account *a, const char *status, const char *err) {
+ pthread_mutex_lock(&G);
+ snprintf(a->status, sizeof a->status, "%s", status);
+ if (err) snprintf(a->last_error, sizeof a->last_error, "%s", err);
+ pthread_mutex_unlock(&G);
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"status\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"status\":"); jb_str(&b, status);
+ jb_raw(&b, ",\"error\":"); jb_str(&b, err ? err : "");
+ jb_raw(&b, "}");
+ send_event(&b);
+}
+
+void acct_set_password(Account *a, const char *pw) {
+ pthread_mutex_lock(&G);
+ if (a->password) { explicit_bzero(a->password, strlen(a->password)); free(a->password); }
+ a->password = pw ? strdup(pw) : NULL;
+ a->need_auth_sent = 0;
+ pthread_mutex_unlock(&G);
+ Job *j = job_new(a->kind[0] == 'd' ? J_DAV_SYNC : J_SYNC_ALL, 0, 1);
+ if (j) job_push(a, j);
+}
+
+static int valid_id(const char *s) {
+ if (!s || !*s || strlen(s) > 32) return 0;
+ for (; *s; s++) if (!((*s >= 'a' && *s <= 'z') || (*s >= '0' && *s <= '9') || *s == '-' || *s == '_')) return 0;
+ return 1;
+}
+
+static void server_from(const JVal *o, Server *s, int defport) {
+ memset(s, 0, sizeof *s);
+ if (!o) return;
+ const char *h = json_str(o, "host");
+ if (h) snprintf(s->host, sizeof s->host, "%s", h);
+ s->port = (int)json_num(o, "port", defport);
+ if (s->port <= 0 || s->port > 65535) s->port = defport;
+ const char *sec = json_str(o, "security");
+ s->sec = sec && !strcmp(sec, "starttls") ? SEC_STARTTLS : sec && !strcmp(sec, "none") ? SEC_NONE : SEC_SSL;
+}
+
+#define CPY(dst, src) snprintf(dst, sizeof dst, "%s", (src) ? (src) : "")
+
+void accounts_apply_config(const JVal *cfg) {
+ const JVal *acc = json_get(cfg, "accounts");
+ int seen[MAIL_MAX_ACCOUNTS * 2] = { 0 };
+ for (const JVal *a = acc && acc->type == J_ARR ? acc->kid : NULL; a; a = a->next) {
+ const char *id = json_str(a, "id");
+ if (!valid_id(id)) continue;
+ const char *kind = json_str(a, "kind");
+ Account tmp;
+ memset(&tmp, 0, sizeof tmp);
+ CPY(tmp.id, id);
+ CPY(tmp.kind, kind && !strcmp(kind, "dav") ? "dav" : "mail");
+ CPY(tmp.name, json_str(a, "name"));
+ CPY(tmp.email, json_str(a, "email"));
+ CPY(tmp.full_name, json_str(a, "fullName"));
+ CPY(tmp.user, json_str(a, "user"));
+ CPY(tmp.auth, json_str(a, "auth") ? json_str(a, "auth") : "password");
+ server_from(json_get(a, "imap"), &tmp.imap, 993);
+ server_from(json_get(a, "smtp"), &tmp.smtp, 465);
+ tmp.sent_saved = json_bool(a, "sentSaved", 0);
+ const JVal *trust = json_get(a, "trust");
+ CPY(tmp.pin_imap, json_str(trust, "imap"));
+ CPY(tmp.pin_smtp, json_str(trust, "smtp"));
+ CPY(tmp.pin_dav, json_str(trust, "dav"));
+ CPY(tmp.url, json_str(a, "url"));
+ tmp.cal = json_bool(a, "cal", 1);
+ tmp.card = json_bool(a, "card", 1);
+ Account *cur = acct_get(id);
+ int same = cur && !strcmp(cur->kind, tmp.kind) && !strcmp(cur->user, tmp.user) && !strcmp(cur->imap.host, tmp.imap.host) &&
+ cur->imap.port == tmp.imap.port && cur->imap.sec == tmp.imap.sec && !strcmp(cur->url, tmp.url) &&
+ !strcmp(cur->pin_imap, tmp.pin_imap) && !strcmp(cur->pin_dav, tmp.pin_dav);
+ if (cur && same) {
+ /* light changes (name, signature, SMTP): in place */
+ pthread_mutex_lock(&G);
+ CPY(cur->name, tmp.name); CPY(cur->email, tmp.email); CPY(cur->full_name, tmp.full_name);
+ cur->smtp = tmp.smtp; cur->sent_saved = tmp.sent_saved; CPY(cur->pin_smtp, tmp.pin_smtp);
+ cur->cal = tmp.cal; cur->card = tmp.card;
+ pthread_mutex_unlock(&G);
+ for (int i = 0; i < naccounts; i++) if (accounts[i] == cur) seen[i] = 1;
+ continue;
+ }
+ char *keep_pw = NULL;
+ if (cur) {
+ /* server settings changed: retire the old worker (it exits on its own) */
+ if (cur->password && !strcmp(cur->user, tmp.user)) keep_pw = strdup(cur->password);
+ cur->stop = 1;
+ uint64_t one = 1;
+ if (write(cur->wake, &one, sizeof one) < 0) { /* signalled */ }
+ }
+ if (naccounts >= (int)(sizeof accounts / sizeof accounts[0])) { free(keep_pw); continue; }
+ Account *n = calloc(1, sizeof *n);
+ if (!n) { free(keep_pw); continue; }
+ *n = tmp;
+ n->password = keep_pw;
+ n->wake = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
+ pthread_mutex_init(&n->qmu, NULL);
+ snprintf(n->status, sizeof n->status, "idle");
+ pthread_mutex_lock(&G);
+ accounts[naccounts] = n;
+ seen[naccounts] = 1;
+ naccounts++;
+ if (!strcmp(n->kind, "mail")) store_load(n);
+ pthread_mutex_unlock(&G);
+ if (pthread_create(&n->thread, NULL, !strcmp(n->kind, "mail") ? mail_worker : dav_worker, n) == 0) { n->started = 1; pthread_detach(n->thread); }
+ }
+ /* accounts no longer in the file */
+ for (int i = 0; i < naccounts; i++) {
+ if (seen[i] || !accounts[i] || accounts[i]->stop) continue;
+ Account *a = accounts[i];
+ a->stop = 1;
+ uint64_t one = 1;
+ if (write(a->wake, &one, sizeof one) < 0) { /* signalled */ }
+ pthread_mutex_lock(&G);
+ if (a->password) { explicit_bzero(a->password, strlen(a->password)); free(a->password); a->password = NULL; }
+ pthread_mutex_unlock(&G);
+ store_drop_account(a->id);
+ pim_account_removed(a->id);
+ }
+}
+
+static void status_json(JBuf *b) {
+ jb_raw(b, "{\"accounts\":[");
+ int first = 1;
+ pthread_mutex_lock(&G);
+ for (int i = 0; i < naccounts; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop) continue;
+ if (!first) jb_raw(b, ",");
+ first = 0;
+ jb_raw(b, "{\"id\":"); jb_str(b, a->id);
+ jb_raw(b, ",\"kind\":"); jb_str(b, a->kind);
+ jb_raw(b, ",\"status\":"); jb_str(b, a->status);
+ jb_raw(b, ",\"error\":"); jb_str(b, a->last_error);
+ jb_printf(b, ",\"hasPassword\":%s,\"lastSync\":%lld}", a->password ? "true" : "false", (long long)a->last_sync * 1000);
+ }
+ pthread_mutex_unlock(&G);
+ jb_raw(b, "]}");
+}
+
+/* ---- requests ---- */
+
+static Account *req_acct(uint32_t id, const JVal *args) {
+ Account *a = acct_get(json_str(args, "acct"));
+ if (!a) reply_err(id, "no-account", json_str(args, "acct"));
+ return a;
+}
+
+static uint32_t *uids_of(const JVal *args, int *n) {
+ *n = 0;
+ const JVal *u = json_get(args, "uids");
+ if (!u || u->type != J_ARR || !u->len || u->len > 100000) return NULL;
+ uint32_t *out = malloc(u->len * sizeof *out);
+ if (!out) return NULL;
+ for (const JVal *k = u->kid; k; k = k->next) if (k->type == J_NUM && k->num >= 1 && k->num <= 4294967295.0) out[(*n)++] = (uint32_t)k->num;
+ return out;
+}
+
+static void handle_request(uint32_t id, const char *json, size_t len, int *fds, int nfds) {
+ JDoc d;
+ char perr[96];
+ if (!json || json_parse(json, len, &d, perr, sizeof perr)) { reply_err(id, "bad-json", perr); return; }
+ const JVal *args = d.root;
+ const char *op = json_str(args, "op");
+ if (!op) op = "";
+ JBuf b;
+ jb_init(&b);
+ if (!strcmp(op, "ping")) { jb_raw(&b, "{\"ok\":true}"); reply_done(id, &b); }
+ else if (!strcmp(op, "status")) { status_json(&b); reply_done(id, &b); }
+ else if (!strcmp(op, "auth")) {
+ Account *a = req_acct(id, args);
+ const char *pw = json_str(args, "password");
+ if (a) { acct_set_password(a, pw); jb_raw(&b, "{\"ok\":true}"); reply_done(id, &b); }
+ } else if (!strcmp(op, "folders")) { pthread_mutex_lock(&G); store_folders_json(&b); pthread_mutex_unlock(&G); reply_done(id, &b); }
+ else if (!strcmp(op, "counts")) { pthread_mutex_lock(&G); store_counts_json(&b); pthread_mutex_unlock(&G); reply_done(id, &b); }
+ else if (!strcmp(op, "list")) { pthread_mutex_lock(&G); store_list_json(&b, args); pthread_mutex_unlock(&G); reply_done(id, &b); }
+ else if (!strcmp(op, "thread")) { pthread_mutex_lock(&G); store_thread_json(&b, args); pthread_mutex_unlock(&G); reply_done(id, &b); }
+ else if (!strcmp(op, "search")) { pthread_mutex_lock(&G); store_search_json(&b, args); pthread_mutex_unlock(&G); reply_done(id, &b); }
+ else if (!strcmp(op, "open")) msg_open_json(id, args);
+ else if (!strcmp(op, "attachment")) msg_attachment(id, args);
+ else if (!strcmp(op, "image")) msg_image(id, args);
+ else if (!strcmp(op, "invite")) msg_invite(id, args);
+ else if (!strcmp(op, "invite-respond")) msg_invite_respond(id, args);
+ else if (!strcmp(op, "autocomplete")) {
+ const char *q = json_str(args, "q");
+ int count = 0;
+ jb_raw(&b, "{\"items\":[");
+ pthread_mutex_lock(&G);
+ pim_autocomplete(q ? q : "", &b, &count, 12);
+ store_autocomplete(q ? q : "", &b, &count, 12);
+ pthread_mutex_unlock(&G);
+ jb_raw(&b, "]}");
+ reply_done(id, &b);
+ } else if (!strcmp(op, "sync")) {
+ const char *acct = json_str(args, "acct");
+ const char *folder = json_str(args, "folder");
+ for (int i = 0; i < naccounts; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop || (acct && strcmp(acct, a->id))) continue;
+ Job *j = job_new(a->kind[0] == 'd' ? J_DAV_SYNC : folder ? J_SYNC_FOLDER : J_SYNC_ALL, 0, folder ? 5 : 1);
+ if (!j) continue;
+ if (folder) snprintf(j->folder, sizeof j->folder, "%s", folder);
+ job_push(a, j);
+ }
+ jb_raw(&b, "{\"ok\":true}");
+ reply_done(id, &b);
+ } else if (!strcmp(op, "flag") || !strcmp(op, "move") || !strcmp(op, "delete")) {
+ Account *a = req_acct(id, args);
+ const char *folder = json_str(args, "folder");
+ if (a && folder) {
+ int n;
+ uint32_t *uids = uids_of(args, &n);
+ if (!uids || !n) { free(uids); reply_err(id, "no-messages", ""); json_free(&d); return; }
+ Job *j = job_new(!strcmp(op, "flag") ? J_FLAGS : !strcmp(op, "move") ? J_MOVE : J_DELETE, id, 8);
+ if (!j) { free(uids); reply_err(id, "memory", ""); json_free(&d); return; }
+ snprintf(j->folder, sizeof j->folder, "%s", folder);
+ j->uids = uids;
+ j->nuids = n;
+ j->arg = strndup(json, len);
+ j->arglen = len;
+ /* flags change locally right away: the list updates without waiting for the server */
+ if (j->kind == J_FLAGS) {
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, folder, 0);
+ const JVal *add = json_get(args, "add"), *rem = json_get(args, "remove");
+ static const struct { const char *n; uint32_t bit; } fl[] = {
+ { "seen", F_SEEN }, { "flagged", F_FLAGGED }, { "answered", F_ANSWERED }, { "forwarded", F_FORWARDED }, { "junk", F_JUNK },
+ { "label1", F_LABEL1 }, { "label2", F_LABEL1 << 1 }, { "label3", F_LABEL1 << 2 }, { "label4", F_LABEL1 << 3 }, { "label5", F_LABEL1 << 4 }, { "label6", F_LABEL1 << 5 } };
+ for (int k = 0; f && k < n; k++) {
+ Msg *m = store_msg(f, uids[k]);
+ if (!m) continue;
+ uint32_t old = m->flags;
+ for (const JVal *x = add && add->type == J_ARR ? add->kid : NULL; x; x = x->next)
+ for (size_t q = 0; q < sizeof fl / sizeof fl[0]; q++) if (x->type == J_STR && !strcmp(x->str, fl[q].n)) m->flags |= fl[q].bit;
+ for (const JVal *x = rem && rem->type == J_ARR ? rem->kid : NULL; x; x = x->next)
+ for (size_t q = 0; q < sizeof fl / sizeof fl[0]; q++) if (x->type == J_STR && !strcmp(x->str, fl[q].n)) m->flags &= ~fl[q].bit;
+ if ((old ^ m->flags) & F_SEEN) f->unread += (m->flags & F_SEEN) ? -1 : 1;
+ if (old != m->flags) { f->dirty = 1; f->version++; }
+ }
+ if (f) store_save(a, f);
+ pthread_mutex_unlock(&G);
+ JBuf e;
+ jb_init(&e);
+ jb_raw(&e, "{\"ev\":\"changed\",\"acct\":"); jb_str(&e, a->id);
+ jb_raw(&e, ",\"folder\":"); jb_str(&e, folder);
+ jb_raw(&e, "}");
+ send_event(&e);
+ }
+ job_push(a, j);
+ } else if (a) reply_err(id, "no-folder", "");
+ } else if (!strcmp(op, "send") || !strcmp(op, "draft")) {
+ Account *a = req_acct(id, args);
+ if (a) {
+ Job *j = job_new(!strcmp(op, "send") ? J_SEND : J_APPEND_DRAFT, id, 9);
+ if (!j) { reply_err(id, "memory", ""); }
+ else {
+ j->arg = strndup(json, len);
+ j->arglen = len;
+ for (int i = 0; i < nfds && i < 15; i++) { j->fds[j->nfds++] = fds[i]; fds[i] = -1; }
+ snprintf(j->folder, sizeof j->folder, "%s", a->id);
+ if (j->kind == J_SEND) sender_queue(j); else job_push(a, j);
+ }
+ }
+ } else if (!strcmp(op, "create-folder")) {
+ Account *a = req_acct(id, args);
+ const char *name = json_str(args, "name");
+ if (a && name && *name && strlen(name) < 200) {
+ Job *j = job_new(J_CREATE_FOLDER, id, 7);
+ if (j) { snprintf(j->folder, sizeof j->folder, "%s", name); job_push(a, j); }
+ } else if (a) reply_err(id, "bad-name", "");
+ } else if (!strcmp(op, "alarms")) {
+ double from = json_num(args, "from", 0) / 1000, to = json_num(args, "to", 0) / 1000;
+ pim_alarms_json(&b, (int64_t)from, (int64_t)to);
+ reply_done(id, &b);
+ } else if (!strncmp(op, "cal-", 4) || !strncmp(op, "ev-", 3) || !strncmp(op, "todo-", 5) || !strncmp(op, "book-", 5) || !strncmp(op, "contact-", 8)) {
+ pim_handle(id, op, args, fds, nfds);
+ } else reply_err(id, "unknown-op", op);
+ jb_free(&b);
+ json_free(&d);
+}
+
+/* ---- start ---- */
+
+static void enter_sandbox(void) {
+ static const char *ro[] = { "/usr/share/zoneinfo", NULL };
+ int rw[] = { cache_fd, -1 };
+ SandboxHelperCfg cfg = {
+ .name = "lord-maild",
+ .ro_paths = ro,
+ .extra_syscalls = (int[]){ SYS_getcpu, SYS_membarrier, -1 },
+ .allow_ioctl_classes = 0,
+ .mem_max_mb = 768,
+ .ro_dir_fds = NULL,
+ .rw_dir_fds = rw,
+ };
+ int mask = sandbox_apply_helper(&cfg);
+ dbg("sandbox mask %#x", (unsigned)mask);
+}
+
+int main(void) {
+ prctl(PR_SET_PDEATHSIG, SIGKILL);
+ prctl(PR_SET_DUMPABLE, 0);
+ struct rlimit nocore = { 0, 0 };
+ setrlimit(RLIMIT_CORE, &nocore);
+ signal(SIGPIPE, SIG_IGN);
+ debug = getenv("LORD_MAIL_DEBUG") != NULL;
+ struct stat st;
+ if (fstat(SOCK, &st) || !S_ISSOCK(st.st_mode)) { fprintf(stderr, "lord-maild: started by lord-server only\n"); return 2; }
+ if (net_init()) { fprintf(stderr, "lord-maild: TLS init failed\n"); return 3; }
+ tzset();
+ DocMsg m;
+ if (doc_recv(SOCK, &m) || m.h.op != MQ_INIT || m.nfds != 1) { fprintf(stderr, "lord-maild: bad start\n"); return 4; }
+ cache_fd = m.fds[0];
+ m.fds[0] = -1;
+ JDoc init;
+ int have_init = m.json && !json_parse(m.json, m.len, &init, NULL, 0);
+ if (have_init) ic_set_local_zone(json_str(init.root, "zone"));
+ enter_sandbox();
+ pim_init();
+ sender_start();
+ if (have_init) {
+ const JVal *cfg = json_get(init.root, "config");
+ if (cfg) accounts_apply_config(cfg);
+ json_free(&init);
+ }
+ doc_msg_free(&m);
+ JBuf ready;
+ jb_init(&ready);
+ jb_raw(&ready, "{\"ev\":\"ready\"}");
+ send_event(&ready);
+ for (;;) {
+ DocMsg q;
+ int r = doc_recv(SOCK, &q);
+ if (r) break;
+ switch (q.h.op) {
+ case MQ_REQ: handle_request(q.h.id, q.json, q.len, q.fds, q.nfds); break;
+ case MQ_SOCK: on_sock(&q); break;
+ case MQ_CONFIG: {
+ JDoc d;
+ if (q.json && !json_parse(q.json, q.len, &d, NULL, 0)) {
+ const JVal *cfg = json_get(d.root, "config");
+ if (cfg) accounts_apply_config(cfg);
+ json_free(&d);
+ }
+ break;
+ }
+ default: break;
+ }
+ doc_msg_free(&q);
+ }
+ return 0;
+}
diff --git a/server/src/mail/maild.h b/server/src/mail/maild.h
new file mode 100644
index 0000000..4e5ef42
--- /dev/null
+++ b/server/src/mail/maild.h
@@ -0,0 +1,225 @@
+/* maild.h — internals of lord-maild, the sandboxed Mail/Calendar/Contacts helper (docs/MAIL.md).
+ *
+ * Threads:
+ * - main: reads the channel with lord-server, answers local requests (lists, search, opening a
+ * cached message, calendars and contacts) and queues network work;
+ * - one worker per mail account: IMAP sync, IDLE on the inbox, flag changes, moves, appends;
+ * - one sender: SMTP (and the "send later" outbox);
+ * - one worker per CalDAV/CardDAV account.
+ * One coarse lock (G) protects the in-memory cache; network I/O never holds it.
+ *
+ * Files: everything lives under the cache folder lord-server opened for us (cache_fd):
+ * <acct>/folders folder list
+ * <acct>/f/<dir>/state uidvalidity uidnext highestmodseq
+ * <acct>/f/<dir>/index one line per message (headers, flags, preview)
+ * <acct>/f/<dir>/m/<uid> the raw message, once downloaded (Maildir-like: one file each)
+ * pim/… calendars (.ics) and address books (.vcf), see pim.c
+ * att/… attachments saved for opening
+ * img/… remote images the user loaded
+ * outbox/… messages scheduled with "send later" */
+#ifndef LORD_MAIL_MAILD_H
+#define LORD_MAIL_MAILD_H
+
+#include <pthread.h>
+#include <stddef.h>
+#include <stdint.h>
+#include "../doc/wire.h"
+#include "../sec/json.h"
+#include "net.h"
+
+extern pthread_mutex_t G;
+extern int cache_fd;
+
+/* ---- channel ---- */
+void reply_done(uint32_t id, JBuf *b); /* frees b */
+void reply_err(uint32_t id, const char *code, const char *detail);
+void send_event(JBuf *b); /* frees b */
+void reply_image(uint32_t id, const uint32_t *argb, int w, int h);
+/* Asks lord-server for a TCP connection; returns a connected fd or -1 (why: denied/dns/connect). */
+int net_connect(const char *host, int port, char *why, size_t wcap);
+/* Connects and starts TLS (implicit or STARTTLS is the caller's job when starttls=1).
+ * On a certificate problem emits a "cert" event for that account. */
+Conn *open_conn(const char *acct, const char *host, int port, int tls_now, const char *pin, TlsInfo *ti, char *why, size_t wcap);
+void dbg(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
+
+/* ---- files under cache_fd ---- */
+int fs_mkdirs(const char *rel);
+char *fs_read(const char *rel, size_t *len, size_t max);
+int fs_write(const char *rel, const void *data, size_t len); /* atomic (tmp + rename) */
+int fs_exists(const char *rel);
+int fs_unlink(const char *rel);
+int fs_rmtree(const char *rel);
+/* safe file/dir name component from any text (no '/', no leading '.') */
+void fs_safe_name(const char *in, char *out, size_t cap);
+/* 16 hex chars from a string (for folder dirs) */
+void fs_hash(const char *s, char *out17);
+
+/* ---- accounts ---- */
+enum { SEC_SSL, SEC_STARTTLS, SEC_NONE };
+typedef struct {
+ char host[256];
+ int port, sec;
+} Server;
+
+typedef struct Account Account;
+struct Account {
+ char id[40];
+ char kind[8]; /* "mail" | "dav" */
+ char name[128], email[256], full_name[160], user[256];
+ char auth[16]; /* "password" | "oauth2" (prepared, disabled) */
+ Server imap, smtp;
+ int sent_saved; /* the server files sent mail itself (Gmail, Outlook.com) */
+ char pin_imap[96], pin_smtp[96], pin_dav[96];
+ char url[512]; /* DAV: base URL */
+ int cal, card; /* DAV: sync calendars / contacts */
+ char *password; /* in memory only (from the keyring); never written */
+ int need_auth_sent;
+ /* worker */
+ pthread_t thread;
+ int started, stop;
+ int wake; /* eventfd */
+ pthread_mutex_t qmu;
+ struct Job *jobs;
+ /* state */
+ char status[24]; /* "idle" | "sync" | "offline" | "auth" | "cert" | "error" */
+ char last_error[200];
+ int64_t last_sync;
+ int initial_done;
+};
+
+extern Account *accounts[];
+extern int naccounts;
+Account *acct_get(const char *id);
+void accounts_apply_config(const JVal *cfg); /* (re)creates workers */
+void acct_set_password(Account *a, const char *pw);
+void acct_status(Account *a, const char *status, const char *err); /* + event */
+
+/* ---- jobs ---- */
+typedef struct Job {
+ int kind;
+ uint32_t req; /* request id to answer (0 = none) */
+ int prio;
+ char folder[512];
+ uint32_t uid;
+ uint32_t *uids; int nuids;
+ char *arg; /* JSON or text */
+ size_t arglen;
+ int fds[15]; int nfds;
+ struct Job *next;
+} Job;
+enum { J_SYNC_ALL = 1, J_SYNC_FOLDER, J_FETCH_BODY, J_FLAGS, J_MOVE, J_DELETE, J_APPEND_DRAFT, J_EXPUNGE_DRAFT,
+ J_SEND, J_DAV_SYNC, J_DAV_PUT, J_DAV_DELETE, J_DAV_COLLECTION, J_TEST, J_IMAGE, J_CREATE_FOLDER };
+void job_push(Account *a, Job *j); /* takes ownership */
+Job *job_new(int kind, uint32_t req, int prio);
+void job_free(Job *j);
+Job *job_pop(Account *a);
+
+/* ---- mail cache (store.c) ---- */
+enum { F_SEEN = 1, F_FLAGGED = 2, F_ANSWERED = 4, F_DELETED = 8, F_DRAFT = 16, F_FORWARDED = 32, F_JUNK = 64,
+ F_LABEL1 = 256 }; /* $label1..$label6 → F_LABEL1 << 0..5 */
+#define F_LABELS (63u << 8)
+
+typedef struct {
+ uint32_t uid;
+ uint32_t flags;
+ int64_t date;
+ uint32_t size;
+ uint16_t att; /* has attachments */
+ uint16_t body; /* the raw message is cached */
+ char *from_name, *from_email, *to, *cc, *subject, *msgid, *inreplyto, *refs, *preview;
+ char *text; /* folded words for search (subject, people, preview, body) */
+ int doc; /* id in the search index */
+} Msg;
+
+typedef struct Folder {
+ char name[512]; /* IMAP name (modified UTF-7) */
+ char display[512]; /* UTF-8 */
+ char special[12]; /* inbox sent drafts trash junk archive all flagged "" */
+ char delim;
+ int noselect;
+ char dir[20];
+ uint32_t uidvalidity, uidnext;
+ uint64_t modseq;
+ Msg *msgs;
+ int n, cap;
+ int unread;
+ uint32_t version;
+ int dirty;
+ int sorted;
+ int synced; /* synced at least once in this run */
+} Folder;
+
+typedef struct {
+ Folder **f;
+ int n;
+} FolderList;
+
+FolderList *store_folders(Account *a); /* G held */
+Folder *store_folder(Account *a, const char *name, int create);
+void store_load(Account *a);
+void store_save(Account *a, Folder *f); /* writes index/state if dirty */
+void store_save_folders(Account *a);
+Msg *store_msg(Folder *f, uint32_t uid);
+Msg *store_add(Account *a, Folder *f, const Msg *m); /* copies strings */
+void store_remove(Account *a, Folder *f, uint32_t uid);
+void store_clear(Account *a, Folder *f);
+void store_msg_text(Msg *m, const char *body_text);
+void store_reindex(Account *a, Folder *f, Msg *m); /* after store_msg_text */ /* (re)builds m->text and the search index */
+char *store_body_path(Account *a, Folder *f, uint32_t uid, char *out, size_t cap);
+const char *special_of(const char *name, const char *flags);
+void store_drop_account(const char *id);
+
+/* JSON for the UI */
+void store_folders_json(JBuf *b);
+/* list a folder or the unified inbox ("*:inbox"): threads, filter, window */
+void store_list_json(JBuf *b, const JVal *args);
+void store_search_json(JBuf *b, const JVal *args);
+void store_thread_json(JBuf *b, const JVal *args); /* one conversation, oldest first */
+void store_counts_json(JBuf *b);
+void store_autocomplete(const char *q, JBuf *b, int *count, int max);
+
+/* search index (search.c) */
+int search_add(const char *text, int acct_idx, Folder *f, uint32_t uid);
+void search_remove(int doc);
+typedef struct { int acct; Folder *f; uint32_t uid; } Hit;
+int search_query(const char *q, Hit *out, int max);
+void search_fold(const char *in, char *out, size_t cap); /* lower case, no accents */
+
+/* ---- IMAP (imap.c) ---- */
+void *mail_worker(void *arg);
+int imap_append_sent(Account *a, const char *msg, size_t len);
+
+/* ---- SMTP + composing (smtp.c, compose.c) ---- */
+void sender_start(void);
+void sender_queue(Job *j);
+char *compose_message(Account *a, const JVal *m, int *fds, int nfds, size_t *olen, char *msgid, size_t mcap, char *err, size_t ecap);
+int smtp_send(Account *a, const char *from, const char **rcpt, int nrcpt, const char *msg, size_t len, char *err, size_t ecap);
+
+/* ---- opening a message (msgview.c) ---- */
+void msg_open_json(uint32_t id, const JVal *args); /* may queue a body fetch */
+void msg_open_cached(uint32_t id, Account *a, Folder *f, uint32_t uid);
+void msg_attachment(uint32_t id, const JVal *args);
+void msg_image(uint32_t id, const JVal *args);
+void msg_invite(uint32_t id, const JVal *args);
+void msg_invite_respond(uint32_t id, const JVal *args);
+char *msg_body_text(const char *raw, size_t len); /* plain text of a message (search, quoting) */
+void msg_preview(const char *hdr, size_t hlen, const char *part, size_t plen, char *out, size_t cap, int *att);
+int https_get(const char *url, char **body, size_t *blen, size_t max, char *err, size_t ecap);
+
+/* ---- images (mimg.c, stb_image) ---- */
+uint32_t *img_decode(const unsigned char *data, size_t len, int maxw, int maxh, int *w, int *h);
+unsigned char *img_thumb_jpeg(const unsigned char *data, size_t len, int max, size_t *olen);
+
+/* ---- CalDAV/CardDAV (dav.c) and the calendars/contacts store (pim.c) ---- */
+void *dav_worker(void *arg);
+void pim_init(void);
+void pim_handle(uint32_t id, const char *op, const JVal *args, int *fds, int nfds); /* cal-*, ev-*, todo-*, book-*, contact-* */
+void pim_account_removed(const char *id);
+/* DAV sync callbacks */
+void pim_dav_sync(Account *a);
+void pim_alarms_json(JBuf *b, int64_t from, int64_t to);
+int pim_add_invite(const char *cal, const char *ics, size_t len, const char *partstat, const char *me, char *err, size_t ecap);
+void pim_autocomplete(const char *q, JBuf *b, int *count, int max); /* contacts first */
+int pim_has_event(const char *uid, char *cal, size_t cap, char *partstat, size_t pcap, const char *me);
+
+#endif
diff --git a/server/src/mail/mime.c b/server/src/mail/mime.c
index 7c20a37..4d1c400 100644
--- a/server/src/mail/mime.c
+++ b/server/src/mail/mime.c
@@ -1,4 +1,4 @@
-/* mime.c — ver mime.h. */
+/* mime.c — see mime.h. */
#include "mime.h"
#include "charset_tables.h"
@@ -8,7 +8,7 @@
#include <string.h>
#include <strings.h>
-/* ---- utilidades ---- */
+/* ---- utilities ---- */
static int lc(int c) { return (c >= 'A' && c <= 'Z') ? c + 32 : c; }
@@ -21,9 +21,18 @@ static void copy_trim(char *out, size_t cap, const char *s, size_t n) {
out[n] = 0;
}
+/* Bounded copy that always terminates (no truncation warnings from snprintf). */
+static void scpy(char *d, size_t cap, const char *s) {
+ if (!cap) return;
+ size_t n = strlen(s);
+ if (n >= cap) n = cap - 1;
+ memcpy(d, s, n);
+ d[n] = 0;
+}
+
static void lower_ascii(char *s) { for (; *s; s++) *s = (char)lc((unsigned char)*s); }
-/* Corta un texto UTF-8 en cap-1 bytes sin partir un carácter. */
+/* Truncates UTF-8 text to cap-1 bytes without splitting a character. */
static void utf8_fit(char *s, size_t cap) {
size_t n = strlen(s);
if (n < cap) return;
@@ -63,7 +72,7 @@ static int put_cp(char *o, uint32_t cp) {
return 4;
}
-/* Largo de la secuencia UTF-8 válida en s (0 si es inválida). */
+/* Length of the valid UTF-8 sequence at s (0 if invalid). */
static int utf8_len(const unsigned char *s, size_t n) {
if (!n) return 0;
unsigned c = s[0];
@@ -90,31 +99,31 @@ char *utf8_clean(const char *in, size_t len, size_t *olen) {
for (size_t i = 0; i < len;) {
int k = utf8_len((const unsigned char *)in + i, len - i);
if (!k) { bput(&b, "\xef\xbf\xbd", 3); i++; continue; }
- if (k == 1 && in[i] == 0) { i++; continue; } /* sin NUL adentro */
+ if (k == 1 && in[i] == 0) { i++; continue; } /* no embedded NUL */
bput(&b, in + i, (size_t)k);
i += (size_t)k;
}
return bdone(&b, olen);
}
-/* ---- juegos de caracteres ---- */
+/* ---- character sets ---- */
static void cs_norm(const char *cs, char *out, size_t cap) {
size_t o = 0;
for (; cs && *cs && o + 1 < cap; cs++) {
unsigned char c = (unsigned char)*cs;
if (c == '"' || c == '\'' || c == '-' || c == '_' || c == ' ' || c == '.') continue;
- if (c == '*') break; /* idioma de RFC 2231 */
+ if (c == '*') break; /* RFC 2231 language */
out[o++] = (char)lc(c);
}
out[o] = 0;
- /* alias comunes */
+ /* common aliases */
if (!strncmp(out, "cp125", 5)) { char t[64]; snprintf(t, sizeof t, "windows%s", out + 2); snprintf(out, cap, "%s", t); }
else if (!strncmp(out, "xcp125", 6)) { char t[64]; snprintf(t, sizeof t, "windows%s", out + 3); snprintf(out, cap, "%s", t); }
else if (!strcmp(out, "cp850")) snprintf(out, cap, "ibm850");
else if (!strcmp(out, "cp437")) snprintf(out, cap, "ibm437");
else if (!strcmp(out, "mac") || !strcmp(out, "macroman") || !strcmp(out, "xmacroman")) snprintf(out, cap, "macintosh");
- else if (!strncmp(out, "iso8859", 7) && out[7] && out[7] != '-') { /* "iso88591" ya está bien */ }
+ else if (!strncmp(out, "iso8859", 7) && out[7] && out[7] != '-') { /* "iso88591" is already fine */ }
}
static const CsTable *cs_table(const char *norm) {
@@ -178,7 +187,7 @@ char *charset_to_utf8(const char *cs, const char *in, size_t len, size_t *olen)
cs_norm(cs, n, sizeof n);
if (is_utf8_name(n)) return utf8_clean(in, len, olen);
if (is_ascii_name(n)) {
- /* "us-ascii" con bytes de 8 bits: casi siempre es UTF-8 o windows-1252 mal declarado */
+ /* "us-ascii" with 8-bit bytes: almost always mislabeled UTF-8 or windows-1252 */
if (utf8_valid(in, len)) return utf8_clean(in, len, olen);
const CsTable *w = cs_table("windows1252");
return from_table(w ? w->hi : NULL, in, len, olen);
@@ -192,17 +201,17 @@ char *charset_to_utf8(const char *cs, const char *in, size_t len, size_t *olen)
const char *suf = n + 5;
if (!strcmp(suf, "le")) be = 0;
else if (!strcmp(suf, "be")) be = 1;
- else if (len >= 2) { /* con BOM */
+ else if (len >= 2) { /* with BOM */
unsigned char a = (unsigned char)in[0], c = (unsigned char)in[1];
if (a == 0xff && c == 0xfe) be = 0;
}
return from_utf16(in, len, be, wide, olen);
}
- /* desconocido (GB2312, Shift_JIS, …): UTF-8 si lo es, si no reemplazo */
+ /* unknown (GB2312, Shift_JIS, …): UTF-8 if it is, otherwise replacement */
return utf8_clean(in, len, olen);
}
-/* ---- base64 y quoted-printable ---- */
+/* ---- base64 and quoted-printable ---- */
static int b64v(unsigned char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
@@ -261,7 +270,7 @@ size_t qp_decode(const char *in, size_t len, char *out, int header) {
if (c != '=') { out[o++] = c; continue; }
if (i + 1 < len && in[i + 1] == '\n') { i += 1; continue; }
if (i + 2 < len && in[i + 1] == '\r' && in[i + 2] == '\n') { i += 2; continue; }
- /* "=" con espacios antes del salto (relleno de transporte) */
+ /* "=" with whitespace before the line break (transport padding) */
size_t k = i + 1;
while (k < len && (in[k] == ' ' || in[k] == '\t')) k++;
if (k < len && k > i + 1 && (in[k] == '\n' || in[k] == '\r')) { i = (in[k] == '\r' && k + 1 < len && in[k + 1] == '\n') ? k + 1 : k; continue; }
@@ -287,7 +296,7 @@ char *qp_encode(const char *in, size_t len, size_t *olen) {
size_t el;
if ((c >= 33 && c <= 126 && c != '=') || ((c == ' ' || c == '\t') && !at_eol)) { enc[0] = (char)c; el = 1; }
else { enc[0] = '='; enc[1] = hx[c >> 4]; enc[2] = hx[c & 15]; el = 3; }
- /* "." al principio de línea también se codifica (algunos servidores lo tocan) */
+ /* "." at the start of a line is also encoded (some servers mangle it) */
if (col == 0 && c == '.') { enc[0] = '='; enc[1] = '2'; enc[2] = 'E'; el = 3; }
if (col + (int)el > 75) { bput(&b, "=\r\n", 3); col = 0; }
bput(&b, enc, el);
@@ -296,7 +305,7 @@ char *qp_encode(const char *in, size_t len, size_t *olen) {
return bdone(&b, olen);
}
-/* ---- encabezados ---- */
+/* ---- headers ---- */
void mime_split(const char *m, size_t len, const char **hdr, size_t *hlen, const char **body, size_t *blen) {
*hdr = m; *hlen = 0; *body = m + len; *blen = 0;
@@ -311,7 +320,7 @@ void mime_split(const char *m, size_t len, const char **hdr, size_t *hlen, const
*hlen = len;
}
-/* Busca el encabezado y llama put con cada pedazo del valor desplegado. */
+/* Finds the header and calls put with each piece of the unfolded value. */
static int header_find(const char *h, size_t n, const char *name, Buf *b, char *out, size_t cap) {
size_t nl = strlen(name);
size_t o = 0;
@@ -337,7 +346,7 @@ static int header_find(const char *h, size_t n, const char *name, Buf *b, char *
}
if (!b && cap) {
out[o] = 0;
- /* sin espacios a los costados */
+ /* trimmed */
size_t s = 0;
while (out[s] == ' ' || out[s] == '\t') s++;
if (s) memmove(out, out + s, o - s + 1);
@@ -367,7 +376,7 @@ char *mime_header_dup(const char *hdr, size_t hlen, const char *name) {
return r;
}
-/* Texto crudo de encabezado (sin palabras codificadas) a UTF-8. */
+/* Raw header text (without encoded words) to UTF-8. */
static void raw_header_utf8(Buf *b, const char *s, size_t n) {
if (utf8_valid(s, n)) { bput(b, s, n); return; }
size_t ol;
@@ -384,7 +393,7 @@ void mime_decode_words(const char *in, char *out, size_t cap) {
int last_was_word = 0;
while (i < n) {
if (in[i] == '=' && i + 1 < n && in[i + 1] == '?') {
- /* =?charset?E?texto?= */
+ /* =?charset?E?text?= */
size_t q1 = i + 2;
while (q1 < n && in[q1] != '?' && q1 - i < 70) q1++;
if (q1 + 3 < n && in[q1] == '?' && in[q1 + 2] == '?') {
@@ -392,7 +401,7 @@ void mime_decode_words(const char *in, char *out, size_t cap) {
size_t t = q1 + 3, te = t;
while (te + 1 < n && !(in[te] == '?' && in[te + 1] == '=')) te++;
if ((enc == 'b' || enc == 'q') && te + 1 < n) {
- /* el espacio entre dos palabras codificadas no cuenta */
+ /* whitespace between two encoded words is ignored */
size_t ws = lit;
int only_ws = 1;
for (size_t k = lit; k < i; k++) if (in[k] != ' ' && in[k] != '\t' && in[k] != '\r' && in[k] != '\n') only_ws = 0;
@@ -434,7 +443,7 @@ void mime_decode_words(const char *in, char *out, size_t cap) {
}
out[o] = 0;
utf8_fit(out, cap);
- /* sin espacios a los costados */
+ /* trimmed */
size_t s = 0;
while (out[s] == ' ') s++;
if (s) memmove(out, out + s, strlen(out + s) + 1);
@@ -442,7 +451,7 @@ void mime_decode_words(const char *in, char *out, size_t cap) {
while (l && out[l - 1] == ' ') out[--l] = 0;
}
-/* RFC 2231: %XX con charset'idioma' al principio del primer pedazo */
+/* RFC 2231: %XX with charset'language' at the start of the first piece */
static void pct_decode(Buf *b, const char *s, size_t n) {
for (size_t i = 0; i < n; i++) {
if (s[i] == '%' && i + 2 < n) {
@@ -459,7 +468,7 @@ int mime_param(const char *value, const char *name, char *out, size_t cap) {
if (!value) return 0;
size_t nl = strlen(name);
const char *p = value;
- /* saltar el valor principal */
+ /* skip the main value */
int inq = 0;
while (*p && (inq || *p != ';')) { if (*p == '"') inq = !inq; else if (*p == '\\' && inq && p[1]) p++; p++; }
struct { int idx, ext; char *val; } seg[32];
@@ -548,7 +557,7 @@ int mime_param(const char *value, const char *name, char *out, size_t cap) {
return 0;
}
-/* ---- partes ---- */
+/* ---- parts ---- */
static void parse_ctype(const char *hdr, size_t hlen, MimePart *p, const MimePart *parent) {
char ct[1024], v[256];
@@ -570,10 +579,10 @@ static void parse_ctype(const char *hdr, size_t hlen, MimePart *p, const MimePar
copy_trim(p->type, sizeof p->type, main, strlen(main));
copy_trim(p->subtype, sizeof p->subtype, slash + 1, strlen(slash + 1));
}
- if (mime_param(ct, "charset", v, sizeof v)) { snprintf(p->charset, sizeof p->charset, "%s", v); lower_ascii(p->charset); }
- if (mime_param(ct, "boundary", v, sizeof v)) snprintf(p->boundary, sizeof p->boundary, "%s", v);
+ if (mime_param(ct, "charset", v, sizeof v)) { scpy(p->charset, sizeof p->charset, v); lower_ascii(p->charset); }
+ if (mime_param(ct, "boundary", v, sizeof v)) scpy(p->boundary, sizeof p->boundary, v);
if (mime_param(ct, "name", v, sizeof v)) snprintf(p->filename, sizeof p->filename, "%s", v);
- if (mime_param(ct, "method", v, sizeof v)) { snprintf(p->method, sizeof p->method, "%s", v); for (char *c = p->method; *c; c++) *c = (char)toupper((unsigned char)*c); }
+ if (mime_param(ct, "method", v, sizeof v)) { scpy(p->method, sizeof p->method, v); for (char *c = p->method; *c; c++) *c = (char)toupper((unsigned char)*c); }
}
if (mime_header(hdr, hlen, "Content-Transfer-Encoding", v, sizeof v)) { copy_trim(p->encoding, sizeof p->encoding, v, strlen(v)); lower_ascii(p->encoding); }
char cd[1024];
@@ -591,11 +600,11 @@ static void parse_ctype(const char *hdr, size_t hlen, MimePart *p, const MimePar
while (l && (a[l - 1] == '>' || a[l - 1] == ' ')) l--;
copy_trim(p->cid, sizeof p->cid, a, l);
}
- /* nombres de archivo: sin rutas ni controles */
+ /* file names: no paths or control characters */
for (char *c = p->filename; *c; c++) if (*c == '/' || *c == '\\' || (unsigned char)*c < 0x20) *c = '_';
}
-/* Busca la próxima línea "--boundary" desde from. Devuelve el inicio de la línea o (size_t)-1. */
+/* Finds the next "--boundary" line starting at from. Returns the start of the line or (size_t)-1. */
static size_t find_boundary(const char *b, size_t len, size_t from, const char *bnd, size_t bl) {
for (size_t i = from; i + 2 + bl <= len; i++) {
if ((i == 0 || b[i - 1] == '\n') && b[i] == '-' && b[i + 1] == '-' && !memcmp(b + i + 2, bnd, bl)) return i;
@@ -621,13 +630,13 @@ static void parse_part(MimeMsg *m, const char *data, size_t len, int parent, int
size_t pos = find_boundary(b, blen, 0, p->boundary, bl);
while (pos != (size_t)-1) {
size_t after = pos + 2 + bl;
- if (after + 1 < blen + 1 && after + 2 <= blen && b[after] == '-' && b[after + 1] == '-') break; /* cierre */
+ if (after + 1 < blen + 1 && after + 2 <= blen && b[after] == '-' && b[after + 1] == '-') break; /* closing */
const char *nl = memchr(b + after, '\n', blen - after);
if (!nl) break;
size_t start = (size_t)(nl - b) + 1;
size_t next = find_boundary(b, blen, start, p->boundary, bl);
size_t end = next == (size_t)-1 ? blen : next;
- /* el salto de línea antes del delimitador es del delimitador */
+ /* the line break before the delimiter belongs to the delimiter */
if (end > start && b[end - 1] == '\n') end--;
if (end > start && b[end - 1] == '\r') end--;
if (end < start) end = start;
@@ -669,14 +678,14 @@ char *mime_part_text(const MimePart *p, size_t *olen) {
return u;
}
-/* ---- direcciones ---- */
+/* ---- addresses ---- */
int mime_addrs(const char *value, MimeAddr *out, int max) {
int n = 0;
if (!value) return 0;
const char *s = value;
while (*s && n < max) {
- /* un elemento hasta la coma de nivel 0 */
+ /* one element up to the top-level comma */
Buf name = { 0 }, email = { 0 }, comment = { 0 }, bare = { 0 };
int inq = 0, angle = 0, par = 0, had_angle = 0;
for (; *s; s++) {
@@ -699,7 +708,7 @@ int mime_addrs(const char *value, MimeAddr *out, int max) {
if (c == '(') { par = 1; continue; }
if (c == '<') { angle = 1; had_angle = 1; continue; }
if (c == ',' || c == ';') { s++; break; }
- if (c == ':') { /* nombre de grupo: se descarta */
+ if (c == ':') { /* group name: discarded */
free(name.p); free(bare.p);
memset(&name, 0, sizeof name); memset(&bare, 0, sizeof bare);
continue;
@@ -718,7 +727,7 @@ int mime_addrs(const char *value, MimeAddr *out, int max) {
mime_decode_words(tmp, a.name, sizeof a.name);
} else if (br) {
copy_trim(a.email, sizeof a.email, br, strlen(br));
- /* "a@b" sin comillas pero con espacios: quedarse con la palabra que tiene @ */
+ /* unquoted "a@b" with spaces: keep the word containing @ */
if (strchr(a.email, ' ')) {
char *at = strchr(a.email, '@');
if (at) {
@@ -732,7 +741,7 @@ int mime_addrs(const char *value, MimeAddr *out, int max) {
if (cm) { char tmp[512]; copy_trim(tmp, sizeof tmp, cm, strlen(cm)); mime_decode_words(tmp, a.name, sizeof a.name); }
}
free(nm); free(em); free(cm); free(br);
- /* solo direcciones con forma de dirección */
+ /* only address-shaped addresses */
for (char *c = a.email; *c; c++) if ((unsigned char)*c < 0x21 || *c == '<' || *c == '>' || *c == '"') { *c = 0; break; }
if (a.email[0] && strchr(a.email, '@')) out[n++] = a;
while (*s == ' ' || *s == '\t' || *s == ',' || *s == '\r' || *s == '\n') s++;
@@ -740,7 +749,7 @@ int mime_addrs(const char *value, MimeAddr *out, int max) {
return n;
}
-/* ---- fechas ---- */
+/* ---- dates ---- */
static long long days_from_civil(long long y, unsigned m, unsigned d) {
y -= m <= 2;
@@ -812,7 +821,7 @@ void mime_format_date(time_t t, char *out, size_t cap) {
tm.tm_hour, tm.tm_min, tm.tm_sec, sign, off / 3600, (off % 3600) / 60);
}
-/* ---- armar encabezados ---- */
+/* ---- building headers ---- */
static int needs_encoding(const char *s) {
for (; *s; s++) if ((unsigned char)*s >= 0x7f || ((unsigned char)*s < 0x20 && *s != '\t')) return 1;
@@ -877,7 +886,7 @@ void mime_base_subject(const char *subj, char *out, size_t cap) {
const char *t = s + l;
if (*t == '[' || *t == '(') { char close = *t == '[' ? ']' : ')'; t++; while (isdigit((unsigned char)*t)) t++; if (*t != close) continue; t++; }
while (*t == ' ') t++;
- if (*t == ':' || (unsigned char)t[0] == 0xef) { /* también los dos puntos de ancho completo (:) */
+ if (*t == ':' || (unsigned char)t[0] == 0xef) { /* also the full-width colon (:) */
if (*t == ':') t++;
else if ((unsigned char)t[1] == 0xbc && (unsigned char)t[2] == 0x9a) t += 3;
else continue;
diff --git a/server/src/mail/mime.h b/server/src/mail/mime.h
index bbe8faf..3417a9e 100644
--- a/server/src/mail/mime.h
+++ b/server/src/mail/mime.h
@@ -1,8 +1,8 @@
-/* mime.h — mensajes de correo (RFC 5322, MIME 2045-2049, 2047, 2231) para lord-maild.
+/* mime.h — mail messages (RFC 5322, MIME 2045-2049, 2047, 2231) for lord-maild.
*
- * Todo trabaja sobre el mensaje crudo en memoria y verifica cada índice contra el largo:
- * un mensaje roto o malicioso da partes vacías, nunca una lectura fuera del búfer. Lo que se
- * entrega a la interfaz siempre es UTF-8 válido (lo inválido pasa a U+FFFD). */
+ * Everything works on the raw in-memory message and checks every index against the length:
+ * a broken or malicious message yields empty parts, never a read outside the buffer. What is
+ * handed to the UI is always valid UTF-8 (invalid input becomes U+FFFD). */
#ifndef LORD_MAIL_MIME_H
#define LORD_MAIL_MIME_H
@@ -14,71 +14,71 @@
#define MIME_MAX_DEPTH 16
typedef struct {
- int parent; /* índice de la parte madre (-1 la raíz) */
+ int parent; /* index of the parent part (-1 for the root) */
int depth;
- char type[48], subtype[64]; /* en minúsculas; "text"/"plain" si no hay Content-Type */
+ char type[48], subtype[64]; /* lowercase; "text"/"plain" if there is no Content-Type */
char charset[40];
char boundary[128];
- char encoding[24]; /* content-transfer-encoding en minúsculas */
+ char encoding[24]; /* content-transfer-encoding, lowercase */
char disposition[16]; /* "inline" | "attachment" | "" */
- char filename[256]; /* UTF-8 (2231/2047 ya decodificados) */
- char cid[160]; /* Content-ID sin <> */
+ char filename[256]; /* UTF-8 (2231/2047 already decoded) */
+ char cid[160]; /* Content-ID without <> */
char method[24]; /* text/calendar; method= */
- const char *hdr; size_t hlen; /* encabezado crudo de la parte */
- const char *body; size_t blen; /* cuerpo crudo (codificado) */
+ const char *hdr; size_t hlen; /* raw header of the part */
+ const char *body; size_t blen; /* raw body (encoded) */
} MimePart;
typedef struct {
MimePart parts[MIME_MAX_PARTS];
int nparts;
- int truncated; /* había más partes de las que entran */
+ int truncated; /* there were more parts than fit */
} MimeMsg;
-/* Separa encabezado y cuerpo de un mensaje o parte (CRLF o LF). */
+/* Splits header and body of a message or part (CRLF or LF). */
void mime_split(const char *m, size_t len, const char **hdr, size_t *hlen, const char **body, size_t *blen);
-/* Valor de un encabezado (primera aparición), desplegado (sin CRLF+espacios), crudo. 1 si estaba. */
+/* Value of a header (first occurrence), unfolded (no CRLF+whitespace), raw. 1 if present. */
int mime_header(const char *hdr, size_t hlen, const char *name, char *out, size_t cap);
-/* Igual pero en memoria nueva (malloc), para encabezados largos (References). NULL si no está. */
+/* Same but in newly allocated memory (malloc), for long headers (References). NULL if absent. */
char *mime_header_dup(const char *hdr, size_t hlen, const char *name);
-/* Decodifica palabras codificadas (=?cs?B|Q?...?=) a UTF-8 y limpia controles. */
+/* Decodes encoded words (=?cs?B|Q?...?=) to UTF-8 and strips control characters. */
void mime_decode_words(const char *in, char *out, size_t cap);
-/* Parámetro de un valor estructurado ("text/plain; charset=utf-8"), con RFC 2231 (name*=, name*0*=). */
+/* Parameter of a structured value ("text/plain; charset=utf-8"), with RFC 2231 (name*=, name*0*=). */
int mime_param(const char *value, const char *name, char *out, size_t cap);
-/* Arma el árbol de partes. Siempre deja al menos la raíz. */
+/* Builds the part tree. Always leaves at least the root. */
void mime_parse(const char *m, size_t len, MimeMsg *out);
-/* Cuerpo decodificado (base64, quoted-printable, 7bit/8bit/binary) en memoria nueva. */
+/* Decoded body (base64, quoted-printable, 7bit/8bit/binary) in newly allocated memory. */
char *mime_decode_body(const MimePart *p, size_t *olen);
-/* Texto de una parte text/* en UTF-8 (charset convertido). */
+/* Text of a text/... part in UTF-8 (charset converted). */
char *mime_part_text(const MimePart *p, size_t *olen);
-/* Juegos de caracteres → UTF-8 (UTF-8, ASCII, Latin-1, la familia ISO-8859 y windows-125x, KOI8,
- * UTF-16/32 con o sin BOM). Desconocido: se toma como UTF-8 con reemplazo. malloc. */
+/* Character sets → UTF-8 (UTF-8, ASCII, Latin-1, the ISO-8859 and windows-125x families, KOI8,
+ * UTF-16/32 with or without BOM). Unknown: treated as UTF-8 with replacement. malloc. */
char *charset_to_utf8(const char *cs, const char *in, size_t len, size_t *olen);
int charset_known(const char *cs);
-/* Copia UTF-8 reemplazando las secuencias inválidas por U+FFFD. malloc. */
+/* Copies UTF-8, replacing invalid sequences with U+FFFD. malloc. */
char *utf8_clean(const char *in, size_t len, size_t *olen);
-/* base64 y quoted-printable */
+/* base64 and quoted-printable */
size_t b64_decode(const char *in, size_t len, unsigned char *out); /* out ≥ len*3/4+3 */
-char *b64_encode(const unsigned char *in, size_t len, int wrap, size_t *olen); /* wrap 76 con CRLF */
+char *b64_encode(const unsigned char *in, size_t len, int wrap, size_t *olen); /* wrap at 76 with CRLF */
size_t qp_decode(const char *in, size_t len, char *out, int header); /* out ≥ len */
-char *qp_encode(const char *in, size_t len, size_t *olen); /* cuerpo, líneas ≤ 76, CRLF */
+char *qp_encode(const char *in, size_t len, size_t *olen); /* body, lines ≤ 76, CRLF */
-/* Una dirección de una lista (From, To, Cc). */
+/* One address from a list (From, To, Cc). */
typedef struct { char name[160]; char email[256]; } MimeAddr;
-/* Separa una lista de direcciones (con nombres entre comillas, comentarios y grupos). Devuelve
- * cuántas dejó en out (como mucho max). El valor ya tiene que venir con las palabras decodificadas
- * o no: se decodifican los nombres acá. */
+/* Splits an address list (with quoted names, comments and groups). Returns
+ * how many were stored in out (at most max). The value may come with encoded words
+ * decoded or not: names are decoded here. */
int mime_addrs(const char *value, MimeAddr *out, int max);
-/* Fecha RFC 5322 ("Tue, 3 Jun 2025 10:22:01 -0300") → segundos UNIX, 0 si no se entiende. */
+/* RFC 5322 date ("Tue, 3 Jun 2025 10:22:01 -0300") → UNIX seconds, 0 if unparseable. */
time_t mime_date(const char *value);
-/* Fecha para el encabezado Date (hora local con su desplazamiento). */
+/* Date for the Date header (local time with its offset). */
void mime_format_date(time_t t, char *out, size_t cap);
-/* Encabezado con palabras codificadas si hace falta (UTF-8 → =?UTF-8?B?...?=, ≤ 75 por palabra). */
+/* Header with encoded words if needed (UTF-8 → =?UTF-8?B?...?=, ≤ 75 per word). */
char *mime_encode_header(const char *utf8);
-/* Una dirección para un encabezado: "Nombre" <a@b> con el nombre codificado si hace falta. */
+/* An address for a header: "Name" <a@b> with the name encoded if needed. */
char *mime_format_addr(const char *name, const char *email);
-/* Asunto sin "Re:", "RE:", "Fwd:", "RV:", "AW:"… repetidos, para agrupar conversaciones. */
+/* Subject without repeated "Re:", "RE:", "Fwd:", "RV:", "AW:"…, for grouping conversations. */
void mime_base_subject(const char *subj, char *out, size_t cap);
#endif
diff --git a/server/src/mail/mimg.c b/server/src/mail/mimg.c
new file mode 100644
index 0000000..a396447
--- /dev/null
+++ b/server/src/mail/mimg.c
@@ -0,0 +1,102 @@
+/* mimg.c — images for Mail and Contacts, decoded inside the sandboxed lord-maild (never in
+ * lord-server): PNG, JPEG, GIF (first frame) and BMP with stb_image, scaled down to fit and
+ * returned as premultiplied ARGB32 like every image the LordOS renderer takes. */
+#define STB_IMAGE_IMPLEMENTATION
+#define STBI_ONLY_PNG
+#define STBI_ONLY_JPEG
+#define STBI_ONLY_BMP
+#define STBI_ONLY_GIF
+#define STBI_MAX_DIMENSIONS 16384
+#include "stb_image.h"
+#define STB_IMAGE_WRITE_IMPLEMENTATION
+#define STBI_WRITE_NO_STDIO
+#include "stb_image_write.h"
+#include <string.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+uint32_t *img_decode(const unsigned char *data, size_t len, int maxw, int maxh, int *ow, int *oh);
+unsigned char *img_thumb_jpeg(const unsigned char *data, size_t len, int max, size_t *olen);
+
+uint32_t *img_decode(const unsigned char *data, size_t len, int maxw, int maxh, int *ow, int *oh) {
+ if (!data || !len || len > (64u << 20)) return NULL;
+ int w, h, comp;
+ if (!stbi_info_from_memory(data, (int)len, &w, &h, &comp) || w <= 0 || h <= 0 || (long long)w * h > 40000000LL) return NULL;
+ unsigned char *px = stbi_load_from_memory(data, (int)len, &w, &h, &comp, 4);
+ if (!px) return NULL;
+ /* scale (box filter) so it fits maxw x maxh */
+ double s = 1.0;
+ if (w > maxw) s = (double)maxw / w;
+ if (h * s > maxh) s = (double)maxh / h;
+ int nw = (int)(w * s + 0.5), nh = (int)(h * s + 0.5);
+ if (nw < 1) nw = 1;
+ if (nh < 1) nh = 1;
+ uint32_t *out = malloc((size_t)nw * (size_t)nh * 4);
+ if (!out) { stbi_image_free(px); return NULL; }
+ for (int y = 0; y < nh; y++) {
+ int y0 = (int)((double)y / s), y1 = (int)((double)(y + 1) / s);
+ if (y1 <= y0) y1 = y0 + 1;
+ if (y1 > h) y1 = h;
+ for (int x = 0; x < nw; x++) {
+ int x0 = (int)((double)x / s), x1 = (int)((double)(x + 1) / s);
+ if (x1 <= x0) x1 = x0 + 1;
+ if (x1 > w) x1 = w;
+ unsigned long r = 0, g = 0, b = 0, a = 0, n = 0;
+ for (int yy = y0; yy < y1; yy += (y1 - y0 > 4 ? (y1 - y0) / 4 : 1))
+ for (int xx = x0; xx < x1; xx += (x1 - x0 > 4 ? (x1 - x0) / 4 : 1)) {
+ const unsigned char *p = px + ((size_t)yy * (size_t)w + (size_t)xx) * 4;
+ unsigned long pa = p[3];
+ r += p[0] * pa; g += p[1] * pa; b += p[2] * pa; a += pa; n++;
+ }
+ if (!n) n = 1;
+ unsigned long A = a / n;
+ unsigned long R = r / n / 255, G = g / n / 255, B = b / n / 255; /* premultiplied */
+ out[(size_t)y * (size_t)nw + (size_t)x] = (uint32_t)(A << 24 | R << 16 | G << 8 | B);
+ }
+ }
+ stbi_image_free(px);
+ *ow = nw;
+ *oh = nh;
+ return out;
+}
+
+/* A contact photo: decoded, scaled to fit max x max and re-encoded as JPEG (so a photo from
+ * anywhere becomes a small, plain JPEG before it is stored or synced). */
+typedef struct { unsigned char *p; size_t n, cap; } WBuf;
+static void wcb(void *ctx, void *data, int size) {
+ WBuf *w = ctx;
+ if (size <= 0) return;
+ if (w->n + (size_t)size > w->cap) {
+ size_t nc = w->cap ? w->cap * 2 : 65536;
+ while (nc < w->n + (size_t)size) nc *= 2;
+ unsigned char *np = realloc(w->p, nc);
+ if (!np) return;
+ w->p = np;
+ w->cap = nc;
+ }
+ memcpy(w->p + w->n, data, (size_t)size);
+ w->n += (size_t)size;
+}
+
+unsigned char *img_thumb_jpeg(const unsigned char *data, size_t len, int max, size_t *olen) {
+ int w, h;
+ uint32_t *px = img_decode(data, len, max, max, &w, &h);
+ if (!px) return NULL;
+ unsigned char *rgb = malloc((size_t)w * (size_t)h * 3);
+ if (!rgb) { free(px); return NULL; }
+ for (size_t i = 0; i < (size_t)w * (size_t)h; i++) {
+ uint32_t p = px[i];
+ unsigned a = p >> 24, r = (p >> 16) & 255, g = (p >> 8) & 255, b = p & 255;
+ /* over white (contact photos have no transparency in vCard) */
+ rgb[i * 3] = (unsigned char)(r + 255 - a);
+ rgb[i * 3 + 1] = (unsigned char)(g + 255 - a);
+ rgb[i * 3 + 2] = (unsigned char)(b + 255 - a);
+ }
+ free(px);
+ WBuf wb = { 0 };
+ int ok = stbi_write_jpg_to_func(wcb, &wb, w, h, 3, rgb, 88);
+ free(rgb);
+ if (!ok || !wb.p) { free(wb.p); return NULL; }
+ *olen = wb.n;
+ return wb.p;
+}
diff --git a/server/src/mail/msgview.c b/server/src/mail/msgview.c
new file mode 100644
index 0000000..55a83ea
--- /dev/null
+++ b/server/src/mail/msgview.c
@@ -0,0 +1,606 @@
+/* msgview.c — opening a message for the reading pane (see maild.h): headers, the plain text,
+ * the HTML turned into our safe tree (html.c), attachments, inline and remote images, and
+ * calendar invitations. The last few opened messages stay parsed for their images. */
+#include "maild.h"
+#include "mime.h"
+#include "html.h"
+#include "http.h"
+#include "ical.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <time.h>
+
+#define OPEN_CACHE 6
+#define IMG_MAX_BYTES (5u << 20) /* one remote image */
+#define IMG_DEADLINE_MS 20000
+
+typedef struct {
+ char acct[40], folder[512];
+ uint32_t uid;
+ char *raw;
+ size_t len;
+ MimeMsg *mm;
+ HtmlData data[HTML_MAX_DATA];
+ int ndata;
+ char *remote[HTML_MAX_REMOTE];
+ int nremote;
+ uint64_t used;
+} Open;
+
+static Open opened[OPEN_CACHE];
+static uint64_t open_seq;
+static pthread_mutex_t open_mu = PTHREAD_MUTEX_INITIALIZER;
+
+static void open_free(Open *o) {
+ free(o->raw);
+ free(o->mm);
+ for (int i = 0; i < o->ndata; i++) free((void *)o->data[i].p);
+ for (int i = 0; i < o->nremote; i++) free(o->remote[i]);
+ memset(o, 0, sizeof *o);
+}
+
+static Open *open_find(const char *acct, const char *folder, uint32_t uid) {
+ for (int i = 0; i < OPEN_CACHE; i++)
+ if (opened[i].raw && opened[i].uid == uid && !strcmp(opened[i].acct, acct) && !strcmp(opened[i].folder, folder)) { opened[i].used = ++open_seq; return &opened[i]; }
+ return NULL;
+}
+
+static Open *open_slot(void) {
+ int s = 0;
+ for (int i = 0; i < OPEN_CACHE; i++) { if (!opened[i].raw) { s = i; break; } if (opened[i].used < opened[s].used) s = i; }
+ open_free(&opened[s]);
+ opened[s].used = ++open_seq;
+ return &opened[s];
+}
+
+/* ---- text helpers ---- */
+
+static int is_attachment(const MimePart *p) {
+ if (!strcmp(p->type, "multipart")) return 0;
+ if (!strcmp(p->type, "message") && !strcmp(p->subtype, "rfc822")) return 1;
+ if (!strcmp(p->disposition, "attachment")) return 1;
+ if (!strcmp(p->type, "text") && (!strcmp(p->subtype, "plain") || !strcmp(p->subtype, "html")) && !p->filename[0]) return 0;
+ if (!strcmp(p->type, "text") && !strcmp(p->subtype, "calendar")) return 1;
+ return p->filename[0] || strcmp(p->type, "text");
+}
+
+static void collapse(const char *in, char *out, size_t cap) {
+ size_t o = 0;
+ int sp = 0, line_start = 1, skip_line = 0;
+ for (const char *s = in; *s && o + 4 < cap; s++) {
+ unsigned char c = (unsigned char)*s;
+ if (c == '\n') { line_start = 1; skip_line = 0; sp = o > 0; continue; }
+ if (line_start && c == '>') { skip_line = 1; } /* quoted text does not preview well */
+ if (line_start && c != ' ' && c != '\t' && c != '\r') line_start = 0;
+ if (skip_line) continue;
+ if (c == ' ' || c == '\t' || c == '\r' || c < 0x20) { sp = o > 0; continue; }
+ if (sp) { out[o++] = ' '; sp = 0; }
+ out[o++] = (char)c;
+ }
+ out[o] = 0;
+ /* do not cut a UTF-8 sequence */
+ while (o && ((unsigned char)out[o - 1] & 0xc0) == 0x80) o--;
+ if (o && (unsigned char)out[o - 1] >= 0xc0) o--;
+ out[o] = 0;
+}
+
+void msg_preview(const char *hdr, size_t hlen, const char *part, size_t plen, char *out, size_t cap, int *att) {
+ out[0] = 0;
+ *att = 0;
+ size_t n = hlen + plen + 4;
+ char *m = malloc(n);
+ if (!m) return;
+ memcpy(m, hdr, hlen);
+ size_t k = hlen;
+ if (k < 2 || m[k - 1] != '\n') { m[k++] = '\r'; m[k++] = '\n'; }
+ m[k++] = '\r'; m[k++] = '\n';
+ if (k + plen > n) plen = n - k;
+ memcpy(m + k, part, plen);
+ k += plen;
+ MimeMsg *mm = malloc(sizeof *mm);
+ if (!mm) { free(m); return; }
+ mime_parse(m, k, mm);
+ const MimePart *best = NULL;
+ for (int i = 0; i < mm->nparts; i++) {
+ const MimePart *p = &mm->parts[i];
+ if (!strcmp(p->type, "multipart") && !strcmp(p->subtype, "mixed")) *att = 1;
+ if (is_attachment(p) && strcmp(p->type, "multipart")) *att = 1;
+ if (!strcmp(p->type, "text") && !is_attachment(p)) {
+ if (!best || (!strcmp(p->subtype, "plain") && strcmp(best->subtype, "plain"))) best = p;
+ }
+ }
+ /* "multipart/mixed" with only text inside is not really an attachment */
+ if (*att) {
+ int real = 0;
+ for (int i = 0; i < mm->nparts; i++) if (is_attachment(&mm->parts[i])) real = 1;
+ if (!real && mm->nparts > 1) *att = mm->truncated;
+ }
+ if (best) {
+ size_t tl;
+ char *t = mime_part_text(best, &tl);
+ if (t) {
+ if (!strcmp(best->subtype, "html")) { size_t xl; char *x = html_to_text(t, tl, &xl); free(t); t = x; }
+ if (t) collapse(t, out, cap < 240 ? cap : 240);
+ free(t);
+ }
+ }
+ free(mm);
+ free(m);
+}
+
+char *msg_body_text(const char *raw, size_t len) {
+ MimeMsg *mm = malloc(sizeof *mm);
+ if (!mm) return NULL;
+ mime_parse(raw, len, mm);
+ JBuf b;
+ jb_init(&b);
+ const MimePart *html = NULL;
+ int plain = 0;
+ for (int i = 0; i < mm->nparts; i++) {
+ const MimePart *p = &mm->parts[i];
+ if (is_attachment(p)) { if (p->filename[0]) { jb_raw(&b, " "); jb_raw(&b, p->filename); } continue; }
+ if (strcmp(p->type, "text")) continue;
+ if (!strcmp(p->subtype, "html")) { if (!html) html = p; continue; }
+ size_t tl;
+ char *t = mime_part_text(p, &tl);
+ if (t) { jb_raw(&b, " "); jb_raw(&b, t); free(t); plain = 1; }
+ }
+ if (!plain && html) {
+ size_t tl;
+ char *t = mime_part_text(html, &tl);
+ if (t) { size_t xl; char *x = html_to_text(t, tl, &xl); free(t); if (x) { jb_raw(&b, " "); jb_raw(&b, x); free(x); } }
+ }
+ free(mm);
+ if (b.oom) { jb_free(&b); return NULL; }
+ if (!b.p) { b.p = calloc(1, 1); }
+ return b.p;
+}
+
+/* ---- opening ---- */
+
+static void addrs_json(JBuf *b, const char *key, const char *hdr, size_t hl, const char *name) {
+ char *v = mime_header_dup(hdr, hl, name);
+ jb_printf(b, ",\"%s\":[", key);
+ if (v) {
+ MimeAddr *ad = malloc(sizeof *ad * 100);
+ int n = ad ? mime_addrs(v, ad, 100) : 0;
+ for (int i = 0; i < n; i++) {
+ if (i) jb_raw(b, ",");
+ jb_raw(b, "{\"name\":"); jb_str(b, ad[i].name);
+ jb_raw(b, ",\"email\":"); jb_str(b, ad[i].email);
+ jb_raw(b, "}");
+ }
+ free(ad);
+ free(v);
+ }
+ jb_raw(b, "]");
+}
+
+static void header_str(JBuf *b, const char *key, const char *hdr, size_t hl, const char *name, int decode) {
+ char *v = mime_header_dup(hdr, hl, name);
+ jb_printf(b, ",\"%s\":", key);
+ if (!v) { jb_raw(b, "\"\""); return; }
+ if (strlen(v) > 4000) v[4000] = 0;
+ if (decode) { char d[4096]; mime_decode_words(v, d, sizeof d); jb_str(b, d); }
+ else jb_str(b, v);
+ free(v);
+}
+
+static int find_parts(const MimeMsg *mm, int *html, int *plain, int *cal) {
+ *html = *plain = *cal = -1;
+ for (int i = 0; i < mm->nparts; i++) {
+ const MimePart *p = &mm->parts[i];
+ if (!strcmp(p->type, "text") && !strcmp(p->subtype, "calendar") && *cal < 0) *cal = i;
+ if ((!strcmp(p->type, "application") && (!strcmp(p->subtype, "ics") || !strcmp(p->subtype, "x-ics"))) && *cal < 0) *cal = i;
+ if (is_attachment(p) || strcmp(p->type, "text")) continue;
+ if (!strcmp(p->subtype, "html") && *html < 0) *html = i;
+ if (!strcmp(p->subtype, "plain") && *plain < 0) *plain = i;
+ }
+ if (*cal < 0) for (int i = 0; i < mm->nparts; i++) {
+ const char *fn = mm->parts[i].filename;
+ size_t l = strlen(fn);
+ if (l > 4 && !strcasecmp(fn + l - 4, ".ics")) { *cal = i; break; }
+ }
+ return 0;
+}
+
+void msg_open_cached(uint32_t id, Account *a, Folder *f, uint32_t uid) {
+ char rel[800];
+ pthread_mutex_lock(&G);
+ store_body_path(a, f, uid, rel, sizeof rel);
+ Msg *meta = store_msg(f, uid);
+ uint32_t flags = meta ? meta->flags : 0;
+ char fname[512];
+ snprintf(fname, sizeof fname, "%s", f->name);
+ pthread_mutex_unlock(&G);
+ size_t len;
+ char *raw = fs_read(rel, &len, (size_t)64 << 20);
+ if (!raw) { reply_err(id, "not-cached", ""); return; }
+ pthread_mutex_lock(&open_mu);
+ Open *o = open_find(a->id, fname, uid);
+ if (!o) {
+ o = open_slot();
+ snprintf(o->acct, sizeof o->acct, "%s", a->id);
+ snprintf(o->folder, sizeof o->folder, "%s", fname);
+ o->uid = uid;
+ o->raw = raw;
+ o->len = len;
+ o->mm = malloc(sizeof *o->mm);
+ if (o->mm) mime_parse(o->raw, o->len, o->mm);
+ } else free(raw);
+ if (!o->mm) { pthread_mutex_unlock(&open_mu); reply_err(id, "memory", ""); return; }
+ const char *h, *bd;
+ size_t hl, bl;
+ mime_split(o->raw, o->len, &h, &hl, &bd, &bl);
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"folder\":"); jb_str(&b, fname);
+ jb_printf(&b, ",\"uid\":%u", uid);
+ header_str(&b, "subject", h, hl, "Subject", 1);
+ char dv[200];
+ time_t dt = mime_header(h, hl, "Date", dv, sizeof dv) ? mime_date(dv) : 0;
+ jb_printf(&b, ",\"date\":%lld", (long long)dt * 1000);
+ addrs_json(&b, "from", h, hl, "From");
+ addrs_json(&b, "to", h, hl, "To");
+ addrs_json(&b, "cc", h, hl, "Cc");
+ addrs_json(&b, "replyTo", h, hl, "Reply-To");
+ header_str(&b, "msgid", h, hl, "Message-ID", 0);
+ header_str(&b, "refs", h, hl, "References", 0);
+ header_str(&b, "inReplyTo", h, hl, "In-Reply-To", 0);
+ header_str(&b, "unsubscribe", h, hl, "List-Unsubscribe", 0);
+ jb_printf(&b, ",\"seen\":%s,\"flagged\":%s,\"answered\":%s,\"size\":%zu", flags & F_SEEN ? "true" : "false", flags & F_FLAGGED ? "true" : "false",
+ flags & F_ANSWERED ? "true" : "false", o->len);
+ int hi, pi, ci;
+ find_parts(o->mm, &hi, &pi, &ci);
+ if (pi >= 0) {
+ size_t tl;
+ char *t = mime_part_text(&o->mm->parts[pi], &tl);
+ if (t && tl > (2u << 20)) t[2u << 20] = 0;
+ jb_raw(&b, ",\"text\":"); jb_str(&b, t ? t : "");
+ jb_printf(&b, ",\"flowed\":%s", strcasestr(o->mm->parts[pi].hdr, "format=flowed") && o->mm->parts[pi].hlen ? "true" : "false");
+ free(t);
+ }
+ if (hi >= 0) {
+ size_t tl;
+ char *t = mime_part_text(&o->mm->parts[hi], &tl);
+ if (t) {
+ HtmlStats st;
+ for (int i = 0; i < o->ndata; i++) free((void *)o->data[i].p);
+ for (int i = 0; i < o->nremote; i++) free(o->remote[i]);
+ o->ndata = o->nremote = 0;
+ size_t jl;
+ char *j = html_sanitize(t, tl, &jl, &st, o->data, &o->ndata);
+ if (j) {
+ jb_raw(&b, ",\"html\":");
+ jb_raw(&b, j);
+ /* remember the remote URLs for the image requests */
+ const char *r = strstr(j, ",\"remote\":[");
+ if (r) {
+ r += 11;
+ while (*r == '"' && o->nremote < HTML_MAX_REMOTE) {
+ const char *e = r + 1;
+ while (*e && *e != '"') { if (*e == '\\' && e[1]) e++; e++; }
+ size_t ul = (size_t)(e - r - 1);
+ char *u = malloc(ul + 1);
+ if (u) {
+ size_t k = 0;
+ for (const char *x = r + 1; x < e; x++) { if (*x == '\\' && x + 1 < e) { x++; u[k++] = *x == '/' ? '/' : *x; continue; } u[k++] = *x; }
+ u[k] = 0;
+ o->remote[o->nremote++] = u;
+ }
+ r = *e ? e + 1 : e;
+ if (*r == ',') r++;
+ }
+ }
+ free(j);
+ }
+ if (pi < 0) {
+ size_t xl;
+ char *x = html_to_text(t, tl, &xl);
+ jb_raw(&b, ",\"text\":"); jb_str(&b, x ? x : "");
+ free(x);
+ }
+ free(t);
+ }
+ }
+ jb_raw(&b, ",\"atts\":[");
+ int first = 1;
+ for (int i = 0; i < o->mm->nparts; i++) {
+ const MimePart *p = &o->mm->parts[i];
+ if (!is_attachment(p)) continue;
+ if (!first) jb_raw(&b, ",");
+ first = 0;
+ char type[120];
+ snprintf(type, sizeof type, "%s/%s", p->type, p->subtype);
+ size_t est = !strcmp(p->encoding, "base64") ? p->blen * 3 / 4 : p->blen;
+ jb_printf(&b, "{\"idx\":%d,\"name\":", i);
+ if (p->filename[0]) jb_str(&b, p->filename);
+ else if (!strcmp(p->type, "message")) jb_str(&b, "message.eml");
+ else if (!strcmp(p->subtype, "calendar")) jb_str(&b, "invite.ics");
+ else { char nm[64]; snprintf(nm, sizeof nm, "part-%d.%s", i, p->subtype); jb_str(&b, nm); }
+ jb_raw(&b, ",\"type\":"); jb_str(&b, type);
+ jb_printf(&b, ",\"size\":%zu", est);
+ if (p->cid[0]) { jb_raw(&b, ",\"cid\":"); jb_str(&b, p->cid); }
+ jb_printf(&b, ",\"inline\":%s}", !strcmp(p->disposition, "inline") || (p->cid[0] && strcmp(p->disposition, "attachment")) ? "true" : "false");
+ }
+ jb_raw(&b, "]");
+ if (ci >= 0) {
+ jb_printf(&b, ",\"invite\":{\"idx\":%d,\"method\":", ci);
+ jb_str(&b, o->mm->parts[ci].method);
+ jb_raw(&b, "}");
+ }
+ jb_raw(&b, "}");
+ pthread_mutex_unlock(&open_mu);
+ reply_done(id, &b);
+}
+
+void msg_open_json(uint32_t id, const JVal *args) {
+ Account *a = acct_get(json_str(args, "acct"));
+ const char *folder = json_str(args, "folder");
+ double u = json_num(args, "uid", 0);
+ if (!a || !folder || u < 1 || u > 4294967295.0) { reply_err(id, "bad-args", ""); return; }
+ uint32_t uid = (uint32_t)u;
+ pthread_mutex_lock(&G);
+ Folder *f = store_folder(a, folder, 0);
+ Msg *m = f ? store_msg(f, uid) : NULL;
+ int cached = m && m->body;
+ pthread_mutex_unlock(&G);
+ if (!m) { reply_err(id, "not-found", ""); return; }
+ if (cached) { msg_open_cached(id, a, f, uid); return; }
+ Job *j = job_new(J_FETCH_BODY, id, 9);
+ if (!j) { reply_err(id, "memory", ""); return; }
+ snprintf(j->folder, sizeof j->folder, "%s", folder);
+ j->uid = uid;
+ job_push(a, j);
+}
+
+/* The parsed message for a follow-up request (attachments, images, invitation). open_mu held. */
+static Open *open_for(uint32_t id, const JVal *args) {
+ const char *acct = json_str(args, "acct"), *folder = json_str(args, "folder");
+ double u = json_num(args, "uid", 0);
+ if (!acct || !folder || u < 1 || u > 4294967295.0) { reply_err(id, "bad-args", ""); return NULL; }
+ Open *o = open_find(acct, folder, (uint32_t)u);
+ if (!o) {
+ /* not among the last opened: load it again from the cache */
+ Account *a = acct_get(acct);
+ pthread_mutex_lock(&G);
+ Folder *f = a ? store_folder(a, folder, 0) : NULL;
+ char rel[800];
+ if (f) store_body_path(a, f, (uint32_t)u, rel, sizeof rel);
+ pthread_mutex_unlock(&G);
+ if (!f) { reply_err(id, "not-found", ""); return NULL; }
+ size_t len;
+ char *raw = fs_read(rel, &len, (size_t)64 << 20);
+ if (!raw) { reply_err(id, "not-cached", ""); return NULL; }
+ o = open_slot();
+ snprintf(o->acct, sizeof o->acct, "%s", acct);
+ snprintf(o->folder, sizeof o->folder, "%s", folder);
+ o->uid = (uint32_t)u;
+ o->raw = raw;
+ o->len = len;
+ o->mm = malloc(sizeof *o->mm);
+ if (!o->mm) { reply_err(id, "memory", ""); return NULL; }
+ mime_parse(o->raw, o->len, o->mm);
+ }
+ return o;
+}
+
+void msg_attachment(uint32_t id, const JVal *args) {
+ pthread_mutex_lock(&open_mu);
+ Open *o = open_for(id, args);
+ if (!o) { pthread_mutex_unlock(&open_mu); return; }
+ int idx = (int)json_num(args, "idx", -1);
+ if (idx < 0 || idx >= o->mm->nparts) { pthread_mutex_unlock(&open_mu); reply_err(id, "bad-index", ""); return; }
+ const MimePart *p = &o->mm->parts[idx];
+ size_t n = 0;
+ char *data = mime_decode_body(p, &n);
+ char name[256];
+ fs_safe_name(p->filename[0] ? p->filename : !strcmp(p->type, "message") ? "message.eml" : !strcmp(p->subtype, "calendar") ? "invite.ics" : "attachment", name, sizeof name);
+ char rel[900];
+ snprintf(rel, sizeof rel, "att/%s/%u-%d/%s", o->acct, o->uid, idx, name);
+ pthread_mutex_unlock(&open_mu);
+ if (!data) { reply_err(id, "memory", ""); return; }
+ char dir[900];
+ snprintf(dir, sizeof dir, "%s", rel);
+ *strrchr(dir, '/') = 0;
+ fs_mkdirs(dir);
+ int ok = fs_write(rel, data, n) == 0;
+ free(data);
+ if (!ok) { reply_err(id, "write", rel); return; }
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"path\":"); jb_str(&b, rel);
+ jb_raw(&b, ",\"name\":"); jb_str(&b, name);
+ jb_printf(&b, ",\"size\":%zu}", n);
+ reply_done(id, &b);
+}
+
+/* ---- remote images ---- */
+
+int https_get(const char *url, char **body, size_t *blen, size_t max, char *err, size_t ecap) {
+ char cur[2048];
+ snprintf(cur, sizeof cur, "%s", url);
+ for (int hop = 0; hop < 4; hop++) { /* at most 3 redirects */
+ int tls, port;
+ char host[256], path[1800];
+ if (http_split_url(cur, &tls, host, sizeof host, &port, path, sizeof path)) { snprintf(err, ecap, "url"); return -1; }
+ if (port != 80 && port != 443) { snprintf(err, ecap, "port"); return -1; }
+ char why[32];
+ int fd = net_connect(host, port, why, sizeof why); /* lord-server: granted host, public address only */
+ if (fd < 0) { snprintf(err, ecap, "%s", why); return -1; }
+ Conn *c = conn_new(fd, host, 10000);
+ if (!c) { snprintf(err, ecap, "memory"); return -1; }
+ TlsInfo ti;
+ if (tls && conn_tls(c, NULL, &ti)) { snprintf(err, ecap, "%s", ti.code ? "cert" : "tls"); conn_close(c); return -1; }
+ HttpResp r;
+ int rc = http_request(c, "GET", host, path, "Accept: image/png,image/jpeg,image/gif,image/bmp\r\nConnection: close\r\n", NULL, 0, max, IMG_DEADLINE_MS, &r);
+ conn_close(c);
+ if (rc) { snprintf(err, ecap, rc == -2 ? "too-big" : "http"); return -1; }
+ if (r.status >= 300 && r.status < 400 && r.location[0]) {
+ if (!strncasecmp(r.location, "http://", 7) || !strncasecmp(r.location, "https://", 8)) snprintf(cur, sizeof cur, "%s", r.location);
+ else if (r.location[0] == '/') snprintf(cur, sizeof cur, "%s://%s%s", tls ? "https" : "http", host, r.location);
+ else { http_resp_free(&r); snprintf(err, ecap, "redirect"); return -1; }
+ http_resp_free(&r);
+ continue;
+ }
+ if (r.status != 200) { http_resp_free(&r); snprintf(err, ecap, "status %d", r.status); return -1; }
+ *body = r.body;
+ *blen = r.blen;
+ r.body = NULL;
+ return 0;
+ }
+ snprintf(err, ecap, "redirects");
+ return -1;
+}
+
+void msg_image(uint32_t id, const JVal *args) {
+ const char *src = json_str(args, "src");
+ int maxw = (int)json_num(args, "maxw", 1200);
+ if (maxw < 16 || maxw > 4096) maxw = 1200;
+ if (!src) { reply_err(id, "bad-args", ""); return; }
+ unsigned char *bytes = NULL;
+ size_t n = 0;
+ char url[2048] = "";
+ pthread_mutex_lock(&open_mu);
+ Open *o = open_for(id, args);
+ if (!o) { pthread_mutex_unlock(&open_mu); return; }
+ if (!strncasecmp(src, "cid:", 4)) {
+ for (int i = 0; i < o->mm->nparts; i++) {
+ const MimePart *p = &o->mm->parts[i];
+ if (p->cid[0] && !strcasecmp(p->cid, src + 4)) { bytes = (unsigned char *)mime_decode_body(p, &n); break; }
+ }
+ } else if (!strncmp(src, "d:", 2)) {
+ int k = atoi(src + 2);
+ if (k >= 0 && k < o->ndata && o->data[k].p) { bytes = malloc(o->data[k].n * 3 / 4 + 4); if (bytes) n = b64_decode(o->data[k].p, o->data[k].n, bytes); }
+ } else if (!strncmp(src, "r:", 2)) {
+ int k = atoi(src + 2);
+ if (k >= 0 && k < o->nremote) snprintf(url, sizeof url, "%s", o->remote[k]);
+ }
+ pthread_mutex_unlock(&open_mu);
+ if (url[0]) {
+ /* remote: our cache first, then the network (only after the user chose to load images) */
+ char h[17], rel[64];
+ fs_hash(url, h);
+ snprintf(rel, sizeof rel, "img/%s", h);
+ bytes = (unsigned char *)fs_read(rel, &n, IMG_MAX_BYTES);
+ if (!bytes) {
+ char err[64];
+ char *body;
+ if (https_get(url, &body, &n, IMG_MAX_BYTES, err, sizeof err)) { reply_err(id, "fetch", err); return; }
+ bytes = (unsigned char *)body;
+ fs_mkdirs("img");
+ fs_write(rel, bytes, n);
+ }
+ }
+ if (!bytes || !n) { free(bytes); reply_err(id, "no-image", src); return; }
+ int w, hh;
+ uint32_t *px = img_decode(bytes, n, maxw, 4096, &w, &hh);
+ free(bytes);
+ if (!px) { reply_err(id, "decode", ""); return; }
+ reply_image(id, px, w, hh);
+ free(px);
+}
+
+/* ---- invitations ---- */
+
+static char *invite_text(uint32_t id, const JVal *args, size_t *len) {
+ pthread_mutex_lock(&open_mu);
+ Open *o = open_for(id, args);
+ if (!o) { pthread_mutex_unlock(&open_mu); return NULL; }
+ int hi, pi, ci;
+ find_parts(o->mm, &hi, &pi, &ci);
+ char *t = ci >= 0 ? mime_part_text(&o->mm->parts[ci], len) : NULL;
+ pthread_mutex_unlock(&open_mu);
+ if (!t) reply_err(id, "no-invite", "");
+ return t;
+}
+
+void msg_invite(uint32_t id, const JVal *args) {
+ size_t len;
+ char *t = invite_text(id, args, &len);
+ if (!t) return;
+ IcEvent *ev;
+ char method[24];
+ int n = ical_events(t, len, &ev, method, sizeof method);
+ free(t);
+ if (n <= 0) { reply_err(id, "bad-invite", ""); return; }
+ Account *a = acct_get(json_str(args, "acct"));
+ const char *me = a ? a->email : "";
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"method\":"); jb_str(&b, method);
+ jb_raw(&b, ",\"event\":");
+ ical_event_json(&b, &ev[0], 0);
+ char cal[64] = "", ps[24] = "";
+ pthread_mutex_lock(&G);
+ int have = pim_has_event(ev[0].uid, cal, sizeof cal, ps, sizeof ps, me);
+ pthread_mutex_unlock(&G);
+ jb_printf(&b, ",\"inCalendar\":%s", have ? "true" : "false");
+ jb_raw(&b, ",\"calendar\":"); jb_str(&b, cal);
+ jb_raw(&b, ",\"myStatus\":"); jb_str(&b, ps);
+ /* my partstat in the invitation itself */
+ for (int i = 0; i < ev[0].natt; i++) if (!strcasecmp(ev[0].att[i].email, me)) { jb_raw(&b, ",\"invited\":"); jb_str(&b, ev[0].att[i].partstat); }
+ jb_raw(&b, "}");
+ ical_events_free(ev, n);
+ reply_done(id, &b);
+}
+
+/* Accept / decline / maybe: put it in the calendar with my answer and send the REPLY to the
+ * organizer (iTIP over iMIP, RFC 6047). */
+void msg_invite_respond(uint32_t id, const JVal *args) {
+ const char *ps = json_str(args, "partstat");
+ if (!ps || (strcmp(ps, "ACCEPTED") && strcmp(ps, "DECLINED") && strcmp(ps, "TENTATIVE"))) { reply_err(id, "bad-partstat", ""); return; }
+ Account *a = acct_get(json_str(args, "acct"));
+ if (!a) { reply_err(id, "no-account", ""); return; }
+ size_t len;
+ char *t = invite_text(id, args, &len);
+ if (!t) return;
+ IcEvent *ev;
+ char method[24];
+ int n = ical_events(t, len, &ev, method, sizeof method);
+ if (n <= 0) { free(t); reply_err(id, "bad-invite", ""); return; }
+ char err[200] = "";
+ const char *cal = json_str(args, "calendar");
+ int ok = 0;
+ if (strcmp(ps, "DECLINED") || json_bool(args, "keepDeclined", 0)) {
+ pthread_mutex_lock(&G);
+ ok = pim_add_invite(cal ? cal : "", t, len, ps, a->email, err, sizeof err) == 0;
+ pthread_mutex_unlock(&G);
+ } else ok = 1;
+ free(t);
+ if (!ok) { ical_events_free(ev, n); reply_err(id, "calendar", err); return; }
+ int sent = 0;
+ if (json_bool(args, "reply", 1) && ev[0].organizer[0] && strcasecmp(ev[0].organizer, a->email)) {
+ size_t rl;
+ char *ics = ical_reply(&ev[0], a->email, a->full_name, ps, &rl);
+ if (ics) {
+ /* the reply goes out as a normal message through the sender */
+ JBuf m;
+ jb_init(&m);
+ const char *verb = !strcmp(ps, "ACCEPTED") ? "Accepted" : !strcmp(ps, "DECLINED") ? "Declined" : "Tentative";
+ char subj[700];
+ snprintf(subj, sizeof subj, "%s: %s", verb, ev[0].summary);
+ jb_raw(&m, "{\"op\":\"send\",\"acct\":"); jb_str(&m, a->id);
+ jb_raw(&m, ",\"to\":[{\"name\":"); jb_str(&m, ev[0].organizer_name);
+ jb_raw(&m, ",\"email\":"); jb_str(&m, ev[0].organizer);
+ jb_raw(&m, "}],\"subject\":"); jb_str(&m, subj);
+ jb_raw(&m, ",\"text\":"); jb_str(&m, subj);
+ jb_raw(&m, ",\"calendar\":"); jb_strn(&m, ics, rl);
+ jb_raw(&m, ",\"calendarMethod\":\"REPLY\",\"noSent\":true}");
+ free(ics);
+ Job *j = job_new(J_SEND, 0, 9);
+ if (j && !m.oom) { j->arg = m.p; j->arglen = m.n; snprintf(j->folder, sizeof j->folder, "%s", a->id); sender_queue(j); sent = 1; }
+ else { jb_free(&m); job_free(j); }
+ }
+ }
+ ical_events_free(ev, n);
+ JBuf b;
+ jb_init(&b);
+ jb_printf(&b, "{\"ok\":true,\"replied\":%s}", sent ? "true" : "false");
+ reply_done(id, &b);
+}
diff --git a/server/src/mail/net.c b/server/src/mail/net.c
new file mode 100644
index 0000000..7b321c2
--- /dev/null
+++ b/server/src/mail/net.c
@@ -0,0 +1,253 @@
+/* net.c — see net.h. */
+#include "net.h"
+
+#include <errno.h>
+#include <poll.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+#include <openssl/err.h>
+#include <openssl/ssl.h>
+#include <openssl/x509v3.h>
+
+struct Conn {
+ int fd;
+ SSL *ssl;
+ char host[256];
+ int timeout;
+ char rb[16384];
+ size_t rpos, rlen;
+ char err[160];
+};
+
+static SSL_CTX *ctx;
+
+int net_init(void) {
+ OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
+ ctx = SSL_CTX_new(TLS_client_method());
+ if (!ctx) return -1;
+ SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
+ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
+ /* the whole bundle is read now: inside the sandbox there is no /etc */
+ static const char *const bundles[] = { "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", NULL };
+ int ok = 0;
+ for (int i = 0; bundles[i] && !ok; i++) ok = SSL_CTX_load_verify_locations(ctx, bundles[i], NULL) == 1;
+ if (!ok) { fprintf(stderr, "lord-maild: no CA bundle found; every TLS connection will fail verification\n"); }
+ SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
+ return 0;
+}
+
+Conn *conn_new(int fd, const char *host, int timeout_ms) {
+ Conn *c = calloc(1, sizeof *c);
+ if (!c) return NULL;
+ c->fd = fd;
+ snprintf(c->host, sizeof c->host, "%s", host ? host : "");
+ conn_set_timeout(c, timeout_ms);
+ return c;
+}
+
+void conn_set_timeout(Conn *c, int ms) {
+ c->timeout = ms > 0 ? ms : 60000;
+ struct timeval tv = { c->timeout / 1000, (c->timeout % 1000) * 1000 };
+ setsockopt(c->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ setsockopt(c->fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
+}
+
+void conn_close(Conn *c) {
+ if (!c) return;
+ if (c->ssl) { SSL_shutdown(c->ssl); SSL_free(c->ssl); }
+ if (c->fd >= 0) close(c->fd);
+ free(c);
+}
+
+int conn_fd(const Conn *c) { return c->fd; }
+int conn_is_tls(const Conn *c) { return c->ssl != NULL; }
+const char *conn_error(const Conn *c) { return c->err; }
+
+static void fingerprint(X509 *x, char *out, size_t cap) {
+ unsigned char md[EVP_MAX_MD_SIZE];
+ unsigned int n = 0;
+ out[0] = 0;
+ if (!X509_digest(x, EVP_sha256(), md, &n)) return;
+ size_t o = 0;
+ for (unsigned i = 0; i < n && o + 4 < cap; i++) o += (size_t)snprintf(out + o, cap - o, "%s%02X", i ? ":" : "", md[i]);
+}
+
+static void name_line(X509_NAME *nm, char *out, size_t cap) {
+ out[0] = 0;
+ if (!nm) return;
+ X509_NAME_oneline(nm, out, (int)cap);
+}
+
+int conn_tls(Conn *c, const char *pin, TlsInfo *info) {
+ memset(info, 0, sizeof *info);
+ if (!ctx) { snprintf(c->err, sizeof c->err, "tls-init"); return -1; }
+ c->ssl = SSL_new(ctx);
+ if (!c->ssl) { snprintf(c->err, sizeof c->err, "tls-memory"); return -1; }
+ SSL_set_fd(c->ssl, c->fd);
+ SSL_set_tlsext_host_name(c->ssl, c->host);
+ SSL_set1_host(c->ssl, c->host); /* host name check (SAN / CN) */
+ /* verification errors are collected, not fatal inside OpenSSL: we decide below */
+ SSL_set_verify(c->ssl, SSL_VERIFY_NONE, NULL);
+ int r = SSL_connect(c->ssl);
+ if (r != 1) {
+ unsigned long e = ERR_get_error();
+ snprintf(c->err, sizeof c->err, "tls-handshake: %s", e ? ERR_reason_error_string(e) : "closed");
+ snprintf(info->reason, sizeof info->reason, "%s", c->err);
+ return -1;
+ }
+ snprintf(info->version, sizeof info->version, "%s", SSL_get_version(c->ssl));
+ X509 *peer = SSL_get1_peer_certificate(c->ssl);
+ long vr = SSL_get_verify_result(c->ssl);
+ if (!peer) { info->code = X509_V_ERR_UNSPECIFIED; snprintf(info->reason, sizeof info->reason, "no certificate"); snprintf(c->err, sizeof c->err, "cert"); return -1; }
+ fingerprint(peer, info->sha256, sizeof info->sha256);
+ name_line(X509_get_subject_name(peer), info->subject, sizeof info->subject);
+ name_line(X509_get_issuer_name(peer), info->issuer, sizeof info->issuer);
+ const ASN1_TIME *na = X509_get0_notAfter(peer);
+ if (na) {
+ BIO *b = BIO_new(BIO_s_mem());
+ if (b) { ASN1_TIME_print(b, na); int n = BIO_read(b, info->not_after, (int)sizeof info->not_after - 1); if (n > 0) info->not_after[n] = 0; BIO_free(b); }
+ }
+ X509_free(peer);
+ if (vr != X509_V_OK) {
+ info->code = (int)vr;
+ snprintf(info->reason, sizeof info->reason, "%s", X509_verify_cert_error_string(vr));
+ if (pin && *pin && !strcasecmp(pin, info->sha256)) { info->pinned = 1; return 0; }
+ snprintf(c->err, sizeof c->err, "cert");
+ return -1;
+ }
+ return 0;
+}
+
+static int wait_in(Conn *c, int ms) {
+ if (c->ssl && SSL_pending(c->ssl) > 0) return 1;
+ struct pollfd p = { c->fd, POLLIN, 0 };
+ int r;
+ do r = poll(&p, 1, ms); while (r < 0 && errno == EINTR);
+ return r;
+}
+
+static int fill(Conn *c) {
+ if (c->rpos < c->rlen) return 1;
+ c->rpos = c->rlen = 0;
+ int w = wait_in(c, c->timeout);
+ if (w == 0) { snprintf(c->err, sizeof c->err, "timeout"); return 0; }
+ if (w < 0) { snprintf(c->err, sizeof c->err, "poll"); return 0; }
+ ssize_t n;
+ if (c->ssl) {
+ n = SSL_read(c->ssl, c->rb, (int)sizeof c->rb);
+ if (n <= 0) { snprintf(c->err, sizeof c->err, "closed"); return 0; }
+ } else {
+ do n = read(c->fd, c->rb, sizeof c->rb); while (n < 0 && errno == EINTR);
+ if (n <= 0) { snprintf(c->err, sizeof c->err, n ? "read" : "closed"); return 0; }
+ }
+ c->rlen = (size_t)n;
+ return 1;
+}
+
+char *conn_line(Conn *c, size_t *len, size_t max) {
+ size_t n = 0, cap = 256;
+ char *o = malloc(cap);
+ if (!o) return NULL;
+ for (;;) {
+ if (!fill(c)) { free(o); return NULL; }
+ char *nl = memchr(c->rb + c->rpos, '\n', c->rlen - c->rpos);
+ size_t take = nl ? (size_t)(nl - (c->rb + c->rpos)) + 1 : c->rlen - c->rpos;
+ if (n + take + 1 > cap) {
+ while (n + take + 1 > cap) cap *= 2;
+ if (cap > max + 2) { if (n + take > max) { free(o); snprintf(c->err, sizeof c->err, "line too long"); return NULL; } cap = max + 2; }
+ char *no = realloc(o, cap);
+ if (!no) { free(o); return NULL; }
+ o = no;
+ }
+ memcpy(o + n, c->rb + c->rpos, take);
+ n += take;
+ c->rpos += take;
+ if (nl) break;
+ }
+ o[n] = 0;
+ *len = n;
+ return o;
+}
+
+int conn_read_n(Conn *c, size_t want, char **buf, size_t *len, size_t *cap) {
+ if (*len + want + 1 > *cap) {
+ size_t nc = *cap ? *cap : 1024;
+ while (nc < *len + want + 1) nc *= 2;
+ char *nb = realloc(*buf, nc);
+ if (!nb) return -1;
+ *buf = nb; *cap = nc;
+ }
+ while (want) {
+ if (!fill(c)) return -1;
+ size_t take = c->rlen - c->rpos < want ? c->rlen - c->rpos : want;
+ memcpy(*buf + *len, c->rb + c->rpos, take);
+ *len += take;
+ c->rpos += take;
+ want -= take;
+ }
+ (*buf)[*len] = 0;
+ return 0;
+}
+
+ssize_t conn_read_some(Conn *c, void *out, size_t n) {
+ if (!fill(c)) return -1;
+ size_t take = c->rlen - c->rpos < n ? c->rlen - c->rpos : n;
+ memcpy(out, c->rb + c->rpos, take);
+ c->rpos += take;
+ return (ssize_t)take;
+}
+
+int conn_write(Conn *c, const void *p, size_t n) {
+ const char *s = p;
+ while (n) {
+ ssize_t w;
+ if (c->ssl) {
+ w = SSL_write(c->ssl, s, (int)(n > (1u << 30) ? (1u << 30) : n));
+ if (w <= 0) { snprintf(c->err, sizeof c->err, "write"); return -1; }
+ } else {
+ do w = write(c->fd, s, n); while (w < 0 && errno == EINTR);
+ if (w <= 0) { snprintf(c->err, sizeof c->err, "write"); return -1; }
+ }
+ s += w;
+ n -= (size_t)w;
+ }
+ return 0;
+}
+
+int conn_printf(Conn *c, const char *fmt, ...) {
+ char tmp[4096];
+ va_list ap;
+ va_start(ap, fmt);
+ int k = vsnprintf(tmp, sizeof tmp, fmt, ap);
+ va_end(ap);
+ if (k < 0) return -1;
+ if ((size_t)k < sizeof tmp) return conn_write(c, tmp, (size_t)k);
+ char *big = malloc((size_t)k + 1);
+ if (!big) return -1;
+ va_start(ap, fmt);
+ vsnprintf(big, (size_t)k + 1, fmt, ap);
+ va_end(ap);
+ int r = conn_write(c, big, (size_t)k);
+ free(big);
+ return r;
+}
+
+int conn_pending(const Conn *c) { return (c->rpos < c->rlen) || (c->ssl && SSL_pending(c->ssl) > 0); }
+
+int conn_wait(Conn *c, int wake_fd, int ms) {
+ if (conn_pending(c)) return 1;
+ struct pollfd p[2] = { { c->fd, POLLIN, 0 }, { wake_fd, POLLIN, 0 } };
+ int r;
+ do r = poll(p, wake_fd >= 0 ? 2 : 1, ms); while (r < 0 && errno == EINTR);
+ if (r < 0) return -1;
+ if (r == 0) return 0;
+ if (wake_fd >= 0 && (p[1].revents & POLLIN)) return 2;
+ return 1;
+}
diff --git a/server/src/mail/net.h b/server/src/mail/net.h
new file mode 100644
index 0000000..f102c85
--- /dev/null
+++ b/server/src/mail/net.h
@@ -0,0 +1,57 @@
+/* net.h — buffered connections with TLS for lord-maild (OpenSSL: lord-maild and lord-sessiond are
+ * the only binaries that link it, see docs/ARCHITECTURE.md).
+ *
+ * lord-maild never opens sockets itself (its seccomp profile forbids socket/connect): it asks
+ * lord-server for a connection to host:port, lord-server checks that the endpoint belongs to a
+ * configured account and hands over an already connected TCP socket (SCM_RIGHTS). This file runs
+ * TLS on top of that socket.
+ *
+ * Certificates are always verified against the system CA store (loaded once, before the
+ * sandbox) and the host name. A bad certificate is never accepted silently: the handshake fails
+ * with the certificate's details, and only a fingerprint the user explicitly trusted in Mail
+ * (stored in the account) lets that exact certificate through. */
+#ifndef LORD_MAIL_NET_H
+#define LORD_MAIL_NET_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include <sys/types.h>
+
+typedef struct Conn Conn;
+
+typedef struct {
+ char reason[160]; /* OpenSSL's verify error text ("" if the chain was fine) */
+ int code; /* X509 verify result (0 = ok) */
+ char subject[256], issuer[256];
+ char sha256[96]; /* "AB:CD:…" fingerprint of the leaf certificate */
+ char not_after[40];
+ char version[24]; /* "TLSv1.3" */
+ int pinned; /* accepted only because of a user-trusted fingerprint */
+} TlsInfo;
+
+/* Loads the CA bundle (call before the sandbox). 0 ok. */
+int net_init(void);
+Conn *conn_new(int fd, const char *host, int timeout_ms);
+void conn_close(Conn *c);
+int conn_fd(const Conn *c);
+/* Starts TLS (implicit TLS right away, or after STARTTLS). pin: trusted "AB:CD…" or NULL.
+ * 0 ok; -1 failure with info filled (certificate problems set info->code != 0). */
+int conn_tls(Conn *c, const char *pin, TlsInfo *info);
+int conn_is_tls(const Conn *c);
+/* Reads one line (up to and including LF) into a malloc'd buffer; *len its length.
+ * NULL on EOF/error/timeout (conn_error tells which). Lines are capped at max bytes. */
+char *conn_line(Conn *c, size_t *len, size_t max);
+/* Reads exactly n bytes, appended to *buf (realloc). 0 ok. */
+int conn_read_n(Conn *c, size_t n, char **buf, size_t *len, size_t *cap);
+/* Reads whatever is available (at least 1 byte, waiting up to the timeout). */
+ssize_t conn_read_some(Conn *c, void *out, size_t n);
+int conn_write(Conn *c, const void *p, size_t n);
+int conn_printf(Conn *c, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
+/* Bytes already buffered (ours or OpenSSL's) that can be read without waiting. */
+int conn_pending(const Conn *c);
+/* Waits for input on the connection or on wake_fd (eventfd). 1 data, 2 wake, 0 timeout, -1 error. */
+int conn_wait(Conn *c, int wake_fd, int ms);
+void conn_set_timeout(Conn *c, int ms);
+const char *conn_error(const Conn *c);
+
+#endif
diff --git a/server/src/mail/proto.h b/server/src/mail/proto.h
new file mode 100644
index 0000000..8a87310
--- /dev/null
+++ b/server/src/mail/proto.h
@@ -0,0 +1,33 @@
+/* proto.h — channel between lord-server and lord-maild (see docs/MAIL.md).
+ *
+ * The same framing as lord-doc (doc/wire.h): a SOCK_SEQPACKET socketpair on fd 3, each message a
+ * DocHdr + JSON (+ up to DOC_MAX_FDS-1 descriptors via SCM_RIGHTS; large JSON goes in a sealed
+ * memfd). Requests carry an id; replies use the same id; events use id 0.
+ *
+ * lord-maild has no way to open a socket (seccomp). To reach a server it sends MR_CONNECT
+ * {"host","port"}; lord-server answers MQ_SOCK with a connected TCP socket, but only if that
+ * endpoint is one of the configured accounts (or a remote-image host the user just allowed). */
+#ifndef LORD_MAIL_PROTO_H
+#define LORD_MAIL_PROTO_H
+
+/* lord-server → lord-maild */
+enum {
+ MQ_INIT = 1, /* {"config":{…},"zone":"Europe/Madrid","lang":"es"} + fd of the cache folder */
+ MQ_REQ, /* {"op":…} (+ fds of files to attach / photos) */
+ MQ_SOCK, /* reply to MR_CONNECT: 1 fd, or {"error":"denied"|"dns"|"connect"} */
+ MQ_CONFIG, /* the accounts file changed: {"config":{…}} */
+};
+
+/* lord-maild → lord-server */
+enum {
+ MR_DONE = 1, /* request finished: JSON result */
+ MR_ERR, /* request failed: {"error":"code","detail":"…"} */
+ MR_EVT, /* event (id 0): {"ev":"new"|"sync"|"changed"|"need-auth"|"cert"|"error"|…} */
+ MR_CONNECT, /* {"host","port"}: please connect me (id = connect id) */
+ MR_IMG, /* request finished with an image: {"w","h"} + sealed memfd of w*h ARGB32 */
+};
+
+#define MAIL_MAX_ACCOUNTS 32
+#define MAIL_CONFIG_MAX (512 * 1024)
+
+#endif
diff --git a/server/src/mail/search.c b/server/src/mail/search.c
new file mode 100644
index 0000000..ffc4943
--- /dev/null
+++ b/server/src/mail/search.c
@@ -0,0 +1,175 @@
+/* search.c — the local, offline search index of Mail (see maild.h).
+ *
+ * Every cached message is split into folded words (lower case, without accents): subject,
+ * people, the preview and, once downloaded, the body text. Each word maps to the list of
+ * messages that contain it. A query is a few words; the last one also matches as a prefix
+ * ("presu" finds "presupuesto"). Words are kept sorted (rebuilt lazily after changes) so a
+ * prefix is a binary search, and the whole thing answers in milliseconds for tens of
+ * thousands of messages without touching the network. */
+#include "maild.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct { int acct; Folder *f; uint32_t uid; int alive; } Doc;
+typedef struct { char *w; int *docs; int n, cap; } Word;
+
+static Doc *docs;
+static int ndocs, capdocs;
+static Word *words; /* hash table, open addressing */
+static size_t cap_words, nwords;
+static Word **sorted;
+static size_t nsorted;
+static int sorted_dirty = 1;
+
+static uint64_t hash(const char *s, size_t n) {
+ uint64_t h = 1469598103934665603ull;
+ for (size_t i = 0; i < n; i++) { h ^= (unsigned char)s[i]; h *= 1099511628211ull; }
+ return h;
+}
+
+/* lower case without accents (Latin letters); other bytes are kept */
+void search_fold(const char *in, char *out, size_t cap) {
+ static const struct { const char *from; const char *to; } map[] = {
+ { "á", "a" }, { "à", "a" }, { "â", "a" }, { "ä", "a" }, { "ã", "a" }, { "å", "a" }, { "Á", "a" }, { "À", "a" }, { "Â", "a" }, { "Ä", "a" }, { "Ã", "a" },
+ { "é", "e" }, { "è", "e" }, { "ê", "e" }, { "ë", "e" }, { "É", "e" }, { "È", "e" }, { "Ê", "e" }, { "Ë", "e" },
+ { "í", "i" }, { "ì", "i" }, { "î", "i" }, { "ï", "i" }, { "Í", "i" }, { "Ì", "i" }, { "Î", "i" }, { "Ï", "i" },
+ { "ó", "o" }, { "ò", "o" }, { "ô", "o" }, { "ö", "o" }, { "õ", "o" }, { "Ó", "o" }, { "Ò", "o" }, { "Ô", "o" }, { "Ö", "o" }, { "Õ", "o" },
+ { "ú", "u" }, { "ù", "u" }, { "û", "u" }, { "ü", "u" }, { "Ú", "u" }, { "Ù", "u" }, { "Û", "u" }, { "Ü", "u" },
+ { "ñ", "n" }, { "Ñ", "n" }, { "ç", "c" }, { "Ç", "c" }, { "ß", "ss" }, { "ø", "o" }, { "Ø", "o" }, { "æ", "ae" }, { "œ", "oe" },
+ };
+ size_t o = 0;
+ if (!cap) return;
+ for (const char *s = in ? in : ""; *s && o + 3 < cap;) {
+ unsigned char c = (unsigned char)*s;
+ if (c < 0x80) { out[o++] = (char)((c >= 'A' && c <= 'Z') ? c + 32 : c); s++; continue; }
+ int hit = 0;
+ if (c == 0xc3 || c == 0xc5) {
+ for (size_t k = 0; k < sizeof map / sizeof map[0]; k++) {
+ size_t l = strlen(map[k].from);
+ if (!strncmp(s, map[k].from, l)) { for (const char *t = map[k].to; *t && o + 1 < cap; t++) out[o++] = *t; s += l; hit = 1; break; }
+ }
+ }
+ if (!hit) out[o++] = *s++;
+ }
+ out[o] = 0;
+}
+
+static int wchar(unsigned char c) { return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c >= 0x80 || c == '_'; }
+
+static Word *word_get(const char *w, size_t n, int create) {
+ if (!cap_words) {
+ if (!create) return NULL;
+ cap_words = 1 << 14;
+ words = calloc(cap_words, sizeof *words);
+ if (!words) { cap_words = 0; return NULL; }
+ }
+ if (create && (nwords + 1) * 10 > cap_words * 7) {
+ size_t nc = cap_words * 2;
+ Word *nw = calloc(nc, sizeof *nw);
+ if (!nw) return NULL;
+ for (size_t i = 0; i < cap_words; i++) {
+ if (!words[i].w) continue;
+ size_t h = hash(words[i].w, strlen(words[i].w)) & (nc - 1);
+ while (nw[h].w) h = (h + 1) & (nc - 1);
+ nw[h] = words[i];
+ }
+ free(words);
+ words = nw;
+ cap_words = nc;
+ sorted_dirty = 1;
+ }
+ size_t h = hash(w, n) & (cap_words - 1);
+ while (words[h].w) {
+ if (strlen(words[h].w) == n && !memcmp(words[h].w, w, n)) return &words[h];
+ h = (h + 1) & (cap_words - 1);
+ }
+ if (!create) return NULL;
+ words[h].w = strndup(w, n);
+ if (!words[h].w) return NULL;
+ nwords++;
+ sorted_dirty = 1;
+ return &words[h];
+}
+
+int search_add(const char *text, int acct, Folder *f, uint32_t uid) {
+ if (ndocs == capdocs) {
+ int nc = capdocs ? capdocs * 2 : 4096;
+ Doc *nd = realloc(docs, (size_t)nc * sizeof *nd);
+ if (!nd) return -1;
+ docs = nd;
+ capdocs = nc;
+ }
+ int id = ndocs++;
+ docs[id] = (Doc){ acct, f, uid, 1 };
+ const char *s = text ? text : "";
+ while (*s) {
+ while (*s && !wchar((unsigned char)*s)) s++;
+ const char *a = s;
+ while (*s && wchar((unsigned char)*s)) s++;
+ size_t n = (size_t)(s - a);
+ if (n < 2 || n > 40) continue;
+ Word *w = word_get(a, n, 1);
+ if (!w) continue;
+ if (w->n && w->docs[w->n - 1] == id) continue;
+ if (w->n == w->cap) {
+ int nc = w->cap ? w->cap * 2 : 4;
+ int *nd = realloc(w->docs, (size_t)nc * sizeof *nd);
+ if (!nd) continue;
+ w->docs = nd;
+ w->cap = nc;
+ }
+ w->docs[w->n++] = id;
+ }
+ return id;
+}
+
+void search_remove(int doc) { if (doc >= 0 && doc < ndocs) docs[doc].alive = 0; }
+
+static int cmpw(const void *a, const void *b) { return strcmp((*(Word *const *)a)->w, (*(Word *const *)b)->w); }
+
+static void build_sorted(void) {
+ if (!sorted_dirty) return;
+ free(sorted);
+ sorted = malloc((nwords ? nwords : 1) * sizeof *sorted);
+ nsorted = 0;
+ if (!sorted) return;
+ for (size_t i = 0; i < cap_words; i++) if (words[i].w) sorted[nsorted++] = &words[i];
+ qsort(sorted, nsorted, sizeof *sorted, cmpw);
+ sorted_dirty = 0;
+}
+
+int search_query(const char *q, Hit *out, int max) {
+ char fq[512];
+ search_fold(q, fq, sizeof fq);
+ char *terms[8];
+ int nt = 0;
+ for (char *s = fq; *s && nt < 8;) {
+ while (*s && !wchar((unsigned char)*s)) s++;
+ if (!*s) break;
+ terms[nt++] = s;
+ while (*s && wchar((unsigned char)*s)) s++;
+ if (*s) *s++ = 0;
+ }
+ if (!nt || !ndocs) return 0;
+ build_sorted();
+ if (!sorted) return 0;
+ unsigned char *mark = calloc((size_t)ndocs, 1);
+ if (!mark) return 0;
+ for (int t = 0; t < nt; t++) {
+ size_t tl = strlen(terms[t]);
+ int prefix = 1; /* every word matches by prefix: "factur" → "factura", "facturas" */
+ size_t lo = 0, hi = nsorted;
+ while (lo < hi) { size_t mid = (lo + hi) / 2; if (strcmp(sorted[mid]->w, terms[t]) < 0) lo = mid + 1; else hi = mid; }
+ for (size_t i = lo; i < nsorted; i++) {
+ if (strncmp(sorted[i]->w, terms[t], tl)) break;
+ if (!prefix && strlen(sorted[i]->w) != tl) continue;
+ Word *w = sorted[i];
+ for (int k = 0; k < w->n; k++) if (mark[w->docs[k]] == t) mark[w->docs[k]] = (unsigned char)(t + 1);
+ }
+ }
+ int n = 0;
+ for (int dd = ndocs - 1; dd >= 0 && n < max; dd--) if (mark[dd] == nt && docs[dd].alive) out[n++] = (Hit){ docs[dd].acct, docs[dd].f, docs[dd].uid };
+ free(mark);
+ return n;
+}
diff --git a/server/src/mail/smtp.c b/server/src/mail/smtp.c
new file mode 100644
index 0000000..63af833
--- /dev/null
+++ b/server/src/mail/smtp.c
@@ -0,0 +1,509 @@
+/* smtp.c — composing (MIME) and sending (SMTP submission) for lord-maild (see maild.h).
+ *
+ * Messages are built here, never by JS: headers are encoded (RFC 2047/2231), bodies go out as
+ * quoted-printable, attachments as base64 read from the fds lord-server opened for the files the
+ * user picked. Submission is on 465 (implicit TLS) or 587 (STARTTLS, required), with AUTH PLAIN
+ * or LOGIN. One sender thread serves every account, plus the "send later" outbox. */
+#include "maild.h"
+#include "mime.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/random.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#define ATT_MAX ((size_t)25 << 20)
+#define TOTAL_MAX ((size_t)35 << 20)
+
+static void rand_hex(char *out, size_t bytes) {
+ unsigned char r[32];
+ if (bytes > sizeof r) bytes = sizeof r;
+ if (getrandom(r, bytes, 0) != (ssize_t)bytes) for (size_t i = 0; i < bytes; i++) r[i] = (unsigned char)(rand() ^ (int)time(NULL));
+ for (size_t i = 0; i < bytes; i++) sprintf(out + i * 2, "%02x", r[i]);
+}
+
+static void hdr(JBuf *b, const char *name, const char *value) {
+ if (!value || !*value) return;
+ char *e = mime_encode_header(value);
+ if (!e) return;
+ jb_raw(b, name);
+ jb_raw(b, ": ");
+ jb_raw(b, e);
+ jb_raw(b, "\r\n");
+ free(e);
+}
+
+static int valid_email(const char *e) {
+ if (!e || !*e || strlen(e) > 254 || !strchr(e, '@')) return 0;
+ for (const char *c = e; *c; c++) if ((unsigned char)*c <= 0x20 || *c == '<' || *c == '>' || *c == ',' || *c == ';' || *c == '"' || *c == '\\' || *c == 0x7f) return 0;
+ return 1;
+}
+
+static void addr_hdr(JBuf *b, const char *name, const JVal *list) {
+ if (!list || list->type != J_ARR || !list->kid) return;
+ jb_raw(b, name);
+ jb_raw(b, ": ");
+ int first = 1;
+ for (const JVal *x = list->kid; x; x = x->next) {
+ const char *e = json_str(x, "email");
+ if (!valid_email(e)) continue;
+ char *f = mime_format_addr(json_str(x, "name"), e);
+ if (!f) continue;
+ if (!first) jb_raw(b, ",\r\n ");
+ jb_raw(b, f);
+ free(f);
+ first = 0;
+ }
+ jb_raw(b, "\r\n");
+}
+
+static void text_part(JBuf *b, const char *type, const char *text, const char *extra_params) {
+ jb_printf(b, "Content-Type: %s; charset=utf-8%s\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n", type, extra_params ? extra_params : "");
+ size_t ql;
+ char *q = qp_encode(text ? text : "", text ? strlen(text) : 0, &ql);
+ if (q) { jb_raw(b, q); free(q); }
+ jb_raw(b, "\r\n");
+}
+
+static char *read_fd(int fd, size_t *n, size_t max) {
+ struct stat st;
+ *n = 0;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || (size_t)st.st_size > max) return NULL;
+ char *buf = malloc((size_t)st.st_size + 1);
+ if (!buf) return NULL;
+ size_t got = 0;
+ while (got < (size_t)st.st_size) {
+ ssize_t r = pread(fd, buf + got, (size_t)st.st_size - got, (off_t)got);
+ if (r <= 0) { if (r < 0 && errno == EINTR) continue; break; }
+ got += (size_t)r;
+ }
+ *n = got;
+ return buf;
+}
+
+static void pct(JBuf *b, const char *s) {
+ for (; *s; s++) {
+ unsigned char c = (unsigned char)*s;
+ if (isalnum(c) || strchr("!#$&+-.^_`|~", c)) { char t[2] = { (char)c, 0 }; jb_raw(b, t); }
+ else jb_printf(b, "%%%02X", c);
+ }
+}
+
+char *compose_message(Account *a, const JVal *m, int *fds, int nfds, size_t *olen, char *msgid, size_t mcap, char *err, size_t ecap) {
+ JBuf b;
+ jb_init(&b);
+ char date[64];
+ mime_format_date(time(NULL), date, sizeof date);
+ jb_printf(&b, "Date: %s\r\n", date);
+ char *from = mime_format_addr(a->full_name, a->email);
+ if (!from || !valid_email(a->email)) { free(from); jb_free(&b); snprintf(err, ecap, "bad sender address"); return NULL; }
+ jb_printf(&b, "From: %s\r\n", from);
+ free(from);
+ addr_hdr(&b, "To", json_get(m, "to"));
+ addr_hdr(&b, "Cc", json_get(m, "cc"));
+ hdr(&b, "Subject", json_str(m, "subject"));
+ const char *dom = strchr(a->email, '@') + 1;
+ char rnd[40];
+ rand_hex(rnd, 16);
+ snprintf(msgid, mcap, "<%s@%s>", rnd, dom);
+ jb_printf(&b, "Message-ID: %s\r\n", msgid);
+ const char *irt = json_str(m, "inReplyTo"), *refs = json_str(m, "references");
+ /* threading headers: ids only (no line breaks smuggled in) */
+ if (irt && *irt && !strpbrk(irt, "\r\n")) jb_printf(&b, "In-Reply-To: %.*s\r\n", 998, irt);
+ if (refs && *refs && !strpbrk(refs, "\r\n")) jb_printf(&b, "References: %.*s\r\n", 3000, refs);
+ jb_raw(&b, "MIME-Version: 1.0\r\nX-Mailer: LordOS Mail\r\n");
+ const char *text = json_str(m, "text"), *html = json_str(m, "html");
+ const char *ics = json_str(m, "calendar"), *icsm = json_str(m, "calendarMethod");
+ const JVal *atts = json_get(m, "attachments");
+ int natt = nfds;
+ char bm[48], ba[48];
+ rand_hex(rnd, 12);
+ snprintf(bm, sizeof bm, "=_lordos_m_%s", rnd);
+ rand_hex(rnd, 12);
+ snprintf(ba, sizeof ba, "=_lordos_a_%s", rnd);
+ int mixed = natt > 0;
+ int alt = (html && *html) || (ics && *ics);
+ if (mixed) jb_printf(&b, "Content-Type: multipart/mixed; boundary=\"%s\"\r\n\r\nThis is a multi-part message in MIME format.\r\n--%s\r\n", bm, bm);
+ if (alt) {
+ jb_printf(&b, "Content-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", ba);
+ jb_printf(&b, "--%s\r\n", ba);
+ text_part(&b, "text/plain", text, NULL);
+ if (html && *html) { jb_printf(&b, "--%s\r\n", ba); text_part(&b, "text/html", html, NULL); }
+ if (ics && *ics) {
+ char mp[48];
+ snprintf(mp, sizeof mp, "; method=%s", icsm && !strcmp(icsm, "REPLY") ? "REPLY" : icsm && !strcmp(icsm, "CANCEL") ? "CANCEL" : "REQUEST");
+ jb_printf(&b, "--%s\r\n", ba);
+ text_part(&b, "text/calendar", ics, mp);
+ }
+ jb_printf(&b, "--%s--\r\n", ba);
+ } else text_part(&b, "text/plain", text, NULL);
+ size_t total = b.n;
+ int i = 0;
+ for (const JVal *x = atts && atts->type == J_ARR ? atts->kid : NULL; i < natt; i++, x = x ? x->next : NULL) {
+ size_t n;
+ char *data = read_fd(fds[i], &n, ATT_MAX);
+ if (!data) { jb_free(&b); snprintf(err, ecap, "attachment %d is too big or unreadable", i + 1); return NULL; }
+ total += n * 4 / 3;
+ if (total > TOTAL_MAX) { free(data); jb_free(&b); snprintf(err, ecap, "the message is too big"); return NULL; }
+ char name[256];
+ fs_safe_name(x && json_str(x, "name") ? json_str(x, "name") : "attachment", name, sizeof name);
+ const char *type = x && json_str(x, "type") ? json_str(x, "type") : "application/octet-stream";
+ int type_ok = strlen(type) < 100 && strchr(type, '/') && !strpbrk(type, "\r\n;\"");
+ jb_printf(&b, "--%s\r\nContent-Type: %s; name=\"", bm, type_ok ? type : "application/octet-stream");
+ char *en = mime_encode_header(name);
+ if (en) { jb_raw(&b, en); free(en); }
+ jb_raw(&b, "\"\r\nContent-Disposition: attachment; filename*=UTF-8''");
+ pct(&b, name);
+ jb_raw(&b, "\r\nContent-Transfer-Encoding: base64\r\n\r\n");
+ size_t el;
+ char *e64 = b64_encode((const unsigned char *)data, n, 1, &el);
+ free(data);
+ if (!e64) { jb_free(&b); snprintf(err, ecap, "memory"); return NULL; }
+ jb_raw(&b, e64);
+ free(e64);
+ }
+ if (mixed) jb_printf(&b, "--%s--\r\n", bm);
+ if (b.oom) { jb_free(&b); snprintf(err, ecap, "memory"); return NULL; }
+ *olen = b.n;
+ return b.p;
+}
+
+/* ---- SMTP ---- */
+
+static int smtp_reply(Conn *c, char *text, size_t tcap, char *caps, size_t ccap) {
+ int code = -1;
+ if (caps && ccap) caps[0] = 0;
+ for (int n = 0; n < 100; n++) {
+ size_t l;
+ char *line = conn_line(c, &l, 4096);
+ if (!line) return -1;
+ if (l < 4) { free(line); return -1; }
+ code = atoi(line);
+ if (caps && ccap && strlen(caps) + l + 1 < ccap) strcat(caps, line + 4);
+ int more = line[3] == '-';
+ if (!more && text) { snprintf(text, tcap, "%s", line + 4); for (char *p = text; *p; p++) if (*p == '\r' || *p == '\n') *p = 0; }
+ free(line);
+ if (!more) break;
+ }
+ return code;
+}
+
+static int smtp_cmd(Conn *c, char *text, size_t tcap, const char *fmt, const char *arg) {
+ if (conn_printf(c, fmt, arg ? arg : "") || conn_write(c, "\r\n", 2)) return -1;
+ return smtp_reply(c, text, tcap, NULL, 0);
+}
+
+int smtp_send(Account *a, const char *from, const char **rcpt, int nrcpt, const char *msg, size_t len, char *err, size_t ecap) {
+ pthread_mutex_lock(&G);
+ char *pw = a->password ? strdup(a->password) : NULL;
+ Server s = a->smtp;
+ char pin[96];
+ snprintf(pin, sizeof pin, "%s", a->pin_smtp);
+ pthread_mutex_unlock(&G);
+ if (!pw) { snprintf(err, ecap, "no-password"); return -2; }
+ if (s.sec == SEC_NONE || !s.host[0]) { free(pw); snprintf(err, ecap, s.host[0] ? "insecure" : "no SMTP server"); return -1; }
+ TlsInfo ti;
+ char why[64], text[512], caps[4096];
+ Conn *c = open_conn(a->id, s.host, s.port, s.sec == SEC_SSL, pin, &ti, why, sizeof why);
+ if (!c) { free(pw); snprintf(err, ecap, "%s", why); return -1; }
+ int r = -1;
+ if (smtp_reply(c, text, sizeof text, NULL, 0) != 220) { snprintf(err, ecap, "greeting: %s", text); goto out; }
+ if (smtp_cmd(c, text, sizeof text, "EHLO %s", "lordos") != 250) { snprintf(err, ecap, "EHLO: %s", text); goto out; }
+ /* EHLO again to read the capabilities (the first reply already went by) */
+ conn_printf(c, "EHLO lordos\r\n");
+ if (smtp_reply(c, text, sizeof text, caps, sizeof caps) != 250) { snprintf(err, ecap, "EHLO: %s", text); goto out; }
+ if (s.sec == SEC_STARTTLS) {
+ if (!strcasestr(caps, "STARTTLS")) { snprintf(err, ecap, "no-starttls"); goto out; }
+ if (smtp_cmd(c, text, sizeof text, "STARTTLS%s", "") != 220) { snprintf(err, ecap, "STARTTLS: %s", text); goto out; }
+ if (conn_tls(c, pin, &ti)) {
+ snprintf(err, ecap, "%s", ti.code ? "cert" : "tls");
+ if (ti.code) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"cert\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"host\":"); jb_str(&b, s.host);
+ jb_printf(&b, ",\"port\":%d,\"smtp\":true,\"reason\":", s.port); jb_str(&b, ti.reason);
+ jb_raw(&b, ",\"subject\":"); jb_str(&b, ti.subject);
+ jb_raw(&b, ",\"issuer\":"); jb_str(&b, ti.issuer);
+ jb_raw(&b, ",\"sha256\":"); jb_str(&b, ti.sha256);
+ jb_raw(&b, "}");
+ send_event(&b);
+ }
+ goto out;
+ }
+ conn_printf(c, "EHLO lordos\r\n");
+ if (smtp_reply(c, text, sizeof text, caps, sizeof caps) != 250) { snprintf(err, ecap, "EHLO: %s", text); goto out; }
+ }
+ /* AUTH PLAIN (or LOGIN) */
+ {
+ size_t ul = strlen(a->user), pl = strlen(pw);
+ int code;
+ if (strcasestr(caps, "PLAIN") || !strcasestr(caps, "LOGIN")) {
+ unsigned char *raw = malloc(ul + pl + 3);
+ if (!raw) goto out;
+ raw[0] = 0; memcpy(raw + 1, a->user, ul); raw[1 + ul] = 0; memcpy(raw + 2 + ul, pw, pl);
+ size_t el;
+ char *e = b64_encode(raw, ul + pl + 2, 0, &el);
+ explicit_bzero(raw, ul + pl + 2);
+ free(raw);
+ if (!e) goto out;
+ code = smtp_cmd(c, text, sizeof text, "AUTH PLAIN %s", e);
+ explicit_bzero(e, el);
+ free(e);
+ } else {
+ size_t el;
+ code = smtp_cmd(c, text, sizeof text, "AUTH LOGIN%s", "");
+ if (code == 334) { char *e = b64_encode((const unsigned char *)a->user, ul, 0, &el); code = e ? smtp_cmd(c, text, sizeof text, "%s", e) : -1; free(e); }
+ if (code == 334) { char *e = b64_encode((const unsigned char *)pw, pl, 0, &el); code = e ? smtp_cmd(c, text, sizeof text, "%s", e) : -1; if (e) { explicit_bzero(e, el); free(e); } }
+ }
+ if (code != 235) { snprintf(err, ecap, "auth: %s", text); r = -2; goto out; }
+ }
+ if (!msg) { r = 0; goto out; } /* a login test */
+ {
+ char line[600];
+ snprintf(line, sizeof line, "MAIL FROM:<%s>%s", from, strcasestr(caps, "SIZE") ? "" : "");
+ if (smtp_cmd(c, text, sizeof text, "%s", line) != 250) { snprintf(err, ecap, "MAIL FROM: %s", text); goto out; }
+ int okr = 0;
+ for (int i = 0; i < nrcpt; i++) {
+ snprintf(line, sizeof line, "RCPT TO:<%s>", rcpt[i]);
+ int code = smtp_cmd(c, text, sizeof text, "%s", line);
+ if (code == 250 || code == 251) okr++;
+ else { snprintf(err, ecap, "%s: %s", rcpt[i], text); goto out; }
+ }
+ if (!okr) { snprintf(err, ecap, "no recipients"); goto out; }
+ if (smtp_cmd(c, text, sizeof text, "DATA%s", "") != 354) { snprintf(err, ecap, "DATA: %s", text); goto out; }
+ /* dot-stuffing, CRLF line ends */
+ JBuf d;
+ jb_init(&d);
+ int bol = 1;
+ for (size_t i = 0; i < len; i++) {
+ char ch = msg[i];
+ if (bol && ch == '.') jb_raw(&d, ".");
+ if (ch == '\n' && (i == 0 || msg[i - 1] != '\r')) jb_raw(&d, "\r");
+ char t[2] = { ch, 0 };
+ if (ch) jb_raw(&d, t);
+ bol = ch == '\n';
+ }
+ if (!bol) jb_raw(&d, "\r\n");
+ jb_raw(&d, ".\r\n");
+ int w = d.oom ? -1 : conn_write(c, d.p, d.n);
+ jb_free(&d);
+ if (w || smtp_reply(c, text, sizeof text, NULL, 0) != 250) { snprintf(err, ecap, "send: %s", text); goto out; }
+ r = 0;
+ }
+out:
+ if (pw) { explicit_bzero(pw, strlen(pw)); free(pw); }
+ conn_printf(c, "QUIT\r\n");
+ conn_close(c);
+ return r;
+}
+
+/* ---- the sender ---- */
+
+static pthread_mutex_t smu = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t scv = PTHREAD_COND_INITIALIZER;
+static Job *squeue;
+
+void sender_queue(Job *j) {
+ pthread_mutex_lock(&smu);
+ Job **p = &squeue;
+ while (*p) p = &(*p)->next;
+ j->next = NULL;
+ *p = j;
+ pthread_cond_signal(&scv);
+ pthread_mutex_unlock(&smu);
+}
+
+static void sent_event(const char *acct, const char *msgid, const char *subject, int later) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"sent\",\"acct\":"); jb_str(&b, acct);
+ jb_raw(&b, ",\"msgid\":"); jb_str(&b, msgid);
+ jb_raw(&b, ",\"subject\":"); jb_str(&b, subject ? subject : "");
+ jb_printf(&b, ",\"later\":%s}", later ? "true" : "false");
+ send_event(&b);
+}
+
+/* Envelope + raw message → SMTP, then the copy in Sent and the \Answered flag. */
+static int deliver(Account *a, const JVal *m, const char *raw, size_t rl, char *err, size_t ecap) {
+ const char *rcpt[300];
+ int nr = 0;
+ const char *lists[] = { "to", "cc", "bcc" };
+ for (int l = 0; l < 3; l++) {
+ const JVal *arr = json_get(m, lists[l]);
+ for (const JVal *x = arr && arr->type == J_ARR ? arr->kid : NULL; x && nr < 300; x = x->next) {
+ const char *e = json_str(x, "email");
+ if (valid_email(e)) rcpt[nr++] = e;
+ }
+ }
+ if (!nr) { snprintf(err, ecap, "no recipients"); return -1; }
+ int r = smtp_send(a, a->email, rcpt, nr, raw, rl, err, ecap);
+ if (r) return r;
+ if (!a->sent_saved && !json_bool(m, "noSent", 0)) imap_append_sent(a, raw, rl);
+ /* the message we answered or forwarded */
+ const JVal *orig = json_get(m, "original");
+ if (orig && json_str(orig, "folder") && json_num(orig, "uid", 0) >= 1) {
+ JBuf fj;
+ jb_init(&fj);
+ jb_printf(&fj, "{\"add\":[\"%s\"]}", json_bool(orig, "forward", 0) ? "forwarded" : "answered");
+ Job *j = job_new(J_FLAGS, 0, 6);
+ if (j && !fj.oom) {
+ snprintf(j->folder, sizeof j->folder, "%s", json_str(orig, "folder"));
+ j->uids = malloc(sizeof *j->uids);
+ if (j->uids) { j->uids[0] = (uint32_t)json_num(orig, "uid", 0); j->nuids = 1; }
+ j->arg = fj.p; j->arglen = fj.n;
+ Account *oa = acct_get(json_str(orig, "acct"));
+ job_push(oa ? oa : a, j);
+ } else { jb_free(&fj); job_free(j); }
+ }
+ /* the draft it came from */
+ double du = json_num(m, "draftUid", 0);
+ if (du >= 1 && json_str(m, "draftFolder")) {
+ Job *j = job_new(J_DELETE, 0, 6);
+ if (j) {
+ snprintf(j->folder, sizeof j->folder, "%s", json_str(m, "draftFolder"));
+ j->uids = malloc(sizeof *j->uids);
+ if (j->uids) { j->uids[0] = (uint32_t)du; j->nuids = 1; }
+ j->arg = strdup("{\"permanent\":true}");
+ j->arglen = j->arg ? strlen(j->arg) : 0;
+ job_push(a, j);
+ }
+ }
+ return 0;
+}
+
+static void run_outbox(void) {
+ int dfd = openat(cache_fd, "outbox", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ if (dfd < 0) return;
+ close(dfd);
+ /* outbox/<n>.json holds {"acct","sendAt","env":{…},"raw":"…"} */
+ for (int k = 0; k < 1000; k++) {
+ char rel[64];
+ snprintf(rel, sizeof rel, "outbox/%d.json", k);
+ size_t n;
+ char *t = fs_read(rel, &n, 64 << 20);
+ if (!t) continue;
+ JDoc d;
+ if (json_parse(t, n, &d, NULL, 0)) { free(t); fs_unlink(rel); continue; }
+ double at = json_num(d.root, "sendAt", 0) / 1000;
+ if (at > (double)time(NULL)) { json_free(&d); free(t); continue; }
+ Account *a = acct_get(json_str(d.root, "acct"));
+ const char *raw = json_str(d.root, "raw");
+ const JVal *env = json_get(d.root, "env");
+ char err[300] = "";
+ if (a && raw && env) {
+ int r = deliver(a, env, raw, strlen(raw), err, sizeof err);
+ if (!r) { fs_unlink(rel); sent_event(a->id, json_str(d.root, "msgid"), json_str(env, "subject"), 1); }
+ else if (r == -2) { /* no password yet: keep it */ }
+ else {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"ev\":\"send-failed\",\"acct\":"); jb_str(&b, a->id);
+ jb_raw(&b, ",\"subject\":"); jb_str(&b, json_str(env, "subject"));
+ jb_raw(&b, ",\"error\":"); jb_str(&b, err);
+ jb_raw(&b, "}");
+ send_event(&b);
+ fs_unlink(rel);
+ }
+ } else fs_unlink(rel);
+ json_free(&d);
+ free(t);
+ }
+}
+
+static int outbox_store(Account *a, const JVal *m, const char *raw, size_t rl, const char *msgid, double at) {
+ fs_mkdirs("outbox");
+ for (int k = 0; k < 1000; k++) {
+ char rel[64];
+ snprintf(rel, sizeof rel, "outbox/%d.json", k);
+ if (fs_exists(rel)) continue;
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "{\"acct\":"); jb_str(&b, a->id);
+ jb_printf(&b, ",\"sendAt\":%.0f,\"msgid\":", at);
+ jb_str(&b, msgid);
+ jb_raw(&b, ",\"env\":{\"subject\":"); jb_str(&b, json_str(m, "subject"));
+ const char *lists[] = { "to", "cc", "bcc" };
+ for (int l = 0; l < 3; l++) {
+ jb_printf(&b, ",\"%s\":[", lists[l]);
+ const JVal *arr = json_get(m, lists[l]);
+ int f = 1;
+ for (const JVal *x = arr && arr->type == J_ARR ? arr->kid : NULL; x; x = x->next) {
+ const char *e = json_str(x, "email");
+ if (!valid_email(e)) continue;
+ if (!f) jb_raw(&b, ",");
+ jb_raw(&b, "{\"email\":"); jb_str(&b, e); jb_raw(&b, "}");
+ f = 0;
+ }
+ jb_raw(&b, "]");
+ }
+ jb_raw(&b, "},\"raw\":");
+ jb_strn(&b, raw, rl);
+ jb_raw(&b, "}");
+ int ok = !b.oom && fs_write(rel, b.p, b.n) == 0;
+ jb_free(&b);
+ return ok ? 0 : -1;
+ }
+ return -1;
+}
+
+static void *sender(void *arg) {
+ (void)arg;
+ for (;;) {
+ pthread_mutex_lock(&smu);
+ while (!squeue) {
+ struct timespec dl;
+ clock_gettime(CLOCK_REALTIME, &dl);
+ dl.tv_sec += 30;
+ if (pthread_cond_timedwait(&scv, &smu, &dl) == ETIMEDOUT) break;
+ }
+ Job *j = squeue;
+ if (j) squeue = j->next;
+ pthread_mutex_unlock(&smu);
+ if (!j) { run_outbox(); continue; }
+ JDoc d;
+ Account *a = acct_get(j->folder);
+ if (!a || !j->arg || json_parse(j->arg, j->arglen, &d, NULL, 0)) { if (j->req) reply_err(j->req, "bad-args", ""); job_free(j); continue; }
+ const JVal *m = d.root;
+ char err[300] = "", msgid[300] = "";
+ if (json_bool(m, "test", 0)) {
+ int r = smtp_send(a, NULL, NULL, 0, NULL, 0, err, sizeof err);
+ if (r) reply_err(j->req, r == -2 ? "auth" : "smtp", err);
+ else { JBuf b; jb_init(&b); jb_raw(&b, "{\"ok\":true}"); reply_done(j->req, &b); }
+ json_free(&d);
+ job_free(j);
+ continue;
+ }
+ size_t rl;
+ char *raw = compose_message(a, m, j->fds, j->nfds, &rl, msgid, sizeof msgid, err, sizeof err);
+ if (!raw) { if (j->req) reply_err(j->req, "compose", err); json_free(&d); job_free(j); continue; }
+ double at = json_num(m, "sendAt", 0);
+ if (at / 1000 > (double)time(NULL) + 20) {
+ int r = outbox_store(a, m, raw, rl, msgid, at);
+ if (j->req) { if (r) reply_err(j->req, "outbox", ""); else { JBuf b; jb_init(&b); jb_raw(&b, "{\"ok\":true,\"scheduled\":true,\"msgid\":"); jb_str(&b, msgid); jb_raw(&b, "}"); reply_done(j->req, &b); } }
+ } else {
+ int r = deliver(a, m, raw, rl, err, sizeof err);
+ if (j->req) {
+ if (r) reply_err(j->req, r == -2 ? "auth" : "smtp", err);
+ else { JBuf b; jb_init(&b); jb_raw(&b, "{\"ok\":true,\"msgid\":"); jb_str(&b, msgid); jb_raw(&b, "}"); reply_done(j->req, &b); }
+ }
+ if (!r) sent_event(a->id, msgid, json_str(m, "subject"), 0);
+ }
+ free(raw);
+ json_free(&d);
+ job_free(j);
+ }
+ return NULL;
+}
+
+void sender_start(void) {
+ pthread_t t;
+ if (!pthread_create(&t, NULL, sender, NULL)) pthread_detach(t);
+}
diff --git a/server/src/mail/store.c b/server/src/mail/store.c
new file mode 100644
index 0000000..a368a8c
--- /dev/null
+++ b/server/src/mail/store.c
@@ -0,0 +1,732 @@
+/* store.c — the local mail cache: folders, message index, conversations and the lists the UI
+ * shows (see maild.h). Everything is in memory and mirrored to small text files, so a folder
+ * with 10,000 messages opens instantly and offline. Callers hold G. */
+#include "maild.h"
+#include "mime.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <time.h>
+
+typedef struct { char id[40]; FolderList fl; int idx; } Store;
+static Store stores[MAIL_MAX_ACCOUNTS * 2];
+static int nstores;
+
+static int acct_index(const Account *a) { for (int i = 0; i < naccounts; i++) if (accounts[i] == a) return i; return -1; }
+
+static Store *store_of(const Account *a, int create) {
+ for (int i = 0; i < nstores; i++) if (!strcmp(stores[i].id, a->id)) { stores[i].idx = acct_index(a); return &stores[i]; }
+ if (!create || nstores >= (int)(sizeof stores / sizeof stores[0])) return NULL;
+ Store *s = &stores[nstores++];
+ memset(s, 0, sizeof *s);
+ snprintf(s->id, sizeof s->id, "%s", a->id);
+ s->idx = acct_index(a);
+ return s;
+}
+
+FolderList *store_folders(Account *a) { Store *s = store_of(a, 1); return s ? &s->fl : NULL; }
+
+/* ---- special folders ---- */
+
+const char *special_of(const char *name, const char *flags) {
+ static const struct { const char *flag, *sp; } fl[] = {
+ { "\\Sent", "sent" }, { "\\Drafts", "drafts" }, { "\\Trash", "trash" }, { "\\Junk", "junk" }, { "\\Archive", "archive" },
+ { "\\All", "all" }, { "\\Flagged", "flagged" },
+ };
+ for (size_t i = 0; flags && i < sizeof fl / sizeof fl[0]; i++) if (strcasestr(flags, fl[i].flag)) return fl[i].sp;
+ if (!strcasecmp(name, "INBOX")) return "inbox";
+ const char *base = strrchr(name, '/');
+ base = base ? base + 1 : name;
+ const char *dot = strrchr(base, '.');
+ if (dot && !strncasecmp(name, "INBOX.", 6)) base = dot + 1;
+ static const struct { const char *n, *sp; } names[] = {
+ { "Sent", "sent" }, { "Sent Items", "sent" }, { "Sent Messages", "sent" }, { "Sent Mail", "sent" }, { "Enviados", "sent" }, { "Elementos enviados", "sent" },
+ { "Drafts", "drafts" }, { "Borradores", "drafts" }, { "Rascunhos", "drafts" },
+ { "Trash", "trash" }, { "Deleted Items", "trash" }, { "Deleted Messages", "trash" }, { "Papelera", "trash" }, { "Lixeira", "trash" }, { "Bin", "trash" },
+ { "Junk", "junk" }, { "Spam", "junk" }, { "Junk E-mail", "junk" }, { "Correo no deseado", "junk" },
+ { "Archive", "archive" }, { "Archivo", "archive" }, { "Arquivo", "archive" }, { "All Mail", "all" },
+ };
+ for (size_t i = 0; i < sizeof names / sizeof names[0]; i++) if (!strcasecmp(base, names[i].n)) return names[i].sp;
+ return "";
+}
+
+/* ---- escaping for the index files ---- */
+
+static void put_field(JBuf *b, const char *s) {
+ for (; s && *s; s++) {
+ if (*s == '\t') jb_raw(b, "\\t");
+ else if (*s == '\n') jb_raw(b, "\\n");
+ else if (*s == '\r') continue;
+ else if (*s == '\\') jb_raw(b, "\\\\");
+ else { char c[2] = { *s, 0 }; jb_raw(b, c); }
+ }
+}
+
+static char *get_field(char **p) {
+ char *s = *p, *o = s, *r = s;
+ while (*s && *s != '\t' && *s != '\n') {
+ if (*s == '\\' && s[1]) { s++; *o++ = *s == 't' ? '\t' : *s == 'n' ? '\n' : *s; s++; continue; }
+ *o++ = *s++;
+ }
+ char end = *s;
+ *o = 0;
+ *p = end ? s + 1 : s;
+ if (end == '\n') *p = s; /* leave the newline for the caller */
+ return r;
+}
+
+static char *sdup(const char *s) { return strdup(s ? s : ""); }
+
+static void msg_free(Msg *m) {
+ free(m->from_name); free(m->from_email); free(m->to); free(m->cc); free(m->subject);
+ free(m->msgid); free(m->inreplyto); free(m->refs); free(m->preview); free(m->text);
+}
+
+/* ---- folders ---- */
+
+static void folder_path(Account *a, Folder *f, const char *file, char *out, size_t cap) { snprintf(out, cap, "%s/f/%s/%s", a->id, f->dir, file); }
+
+Folder *store_folder(Account *a, const char *name, int create) {
+ FolderList *fl = store_folders(a);
+ if (!fl || !name) return NULL;
+ for (int i = 0; i < fl->n; i++) if (!strcmp(fl->f[i]->name, name)) return fl->f[i];
+ if (!create) return NULL;
+ Folder **nf = realloc(fl->f, (size_t)(fl->n + 1) * sizeof *nf);
+ if (!nf) return NULL;
+ fl->f = nf;
+ Folder *f = calloc(1, sizeof *f);
+ if (!f) return NULL;
+ snprintf(f->name, sizeof f->name, "%s", name);
+ snprintf(f->display, sizeof f->display, "%s", name);
+ fs_hash(name, f->dir);
+ fl->f[fl->n++] = f;
+ return f;
+}
+
+Msg *store_msg(Folder *f, uint32_t uid) {
+ /* messages are kept sorted by uid */
+ int lo = 0, hi = f->n;
+ while (lo < hi) { int mid = (lo + hi) / 2; if (f->msgs[mid].uid < uid) lo = mid + 1; else hi = mid; }
+ return lo < f->n && f->msgs[lo].uid == uid ? &f->msgs[lo] : NULL;
+}
+
+void store_msg_text(Msg *m, const char *body) {
+ size_t n = strlen(m->subject ? m->subject : "") + strlen(m->from_name ? m->from_name : "") + strlen(m->from_email ? m->from_email : "") +
+ strlen(m->to ? m->to : "") + strlen(m->cc ? m->cc : "") + strlen(m->preview ? m->preview : "") + (body ? strlen(body) : 0) + 16;
+ if (n > 24000) n = 24000;
+ char *raw = malloc(n);
+ if (!raw) return;
+ snprintf(raw, n, "%s %s %s %s %s %s %s", m->subject ? m->subject : "", m->from_name ? m->from_name : "", m->from_email ? m->from_email : "",
+ m->to ? m->to : "", m->cc ? m->cc : "", m->preview ? m->preview : "", body ? body : "");
+ char *fold = malloc(n + 8);
+ if (fold) search_fold(raw, fold, n + 8);
+ free(raw);
+ free(m->text);
+ m->text = fold;
+}
+
+static void index_msg(Account *a, Folder *f, Msg *m) {
+ if (m->doc > 0) search_remove(m->doc - 1);
+ int d = search_add(m->text ? m->text : "", acct_index(a), f, m->uid);
+ m->doc = d + 1;
+}
+
+void store_reindex(Account *a, Folder *f, Msg *m) { index_msg(a, f, m); }
+
+Msg *store_add(Account *a, Folder *f, const Msg *src) {
+ Msg *ex = store_msg(f, src->uid);
+ if (ex) {
+ uint32_t old = ex->flags;
+ ex->flags = src->flags;
+ if ((old ^ ex->flags) & F_SEEN) f->unread += (ex->flags & F_SEEN) ? -1 : 1;
+ f->dirty = 1; f->version++;
+ return ex;
+ }
+ if (f->n == f->cap) {
+ int nc = f->cap ? f->cap * 2 : 64;
+ Msg *nm = realloc(f->msgs, (size_t)nc * sizeof *nm);
+ if (!nm) return NULL;
+ f->msgs = nm;
+ f->cap = nc;
+ }
+ int pos = f->n;
+ while (pos > 0 && f->msgs[pos - 1].uid > src->uid) pos--;
+ memmove(&f->msgs[pos + 1], &f->msgs[pos], (size_t)(f->n - pos) * sizeof *f->msgs);
+ Msg *m = &f->msgs[pos];
+ *m = *src;
+ m->from_name = sdup(src->from_name); m->from_email = sdup(src->from_email); m->to = sdup(src->to); m->cc = sdup(src->cc);
+ m->subject = sdup(src->subject); m->msgid = sdup(src->msgid); m->inreplyto = sdup(src->inreplyto); m->refs = sdup(src->refs);
+ m->preview = sdup(src->preview);
+ m->text = NULL;
+ m->doc = 0;
+ f->n++;
+ if (!(m->flags & F_SEEN)) f->unread++;
+ store_msg_text(m, NULL);
+ /* search docs point at (folder, uid): re-adding is enough */
+ index_msg(a, f, m);
+ f->dirty = 1;
+ f->version++;
+ return m;
+}
+
+void store_remove(Account *a, Folder *f, uint32_t uid) {
+ Msg *m = store_msg(f, uid);
+ if (!m) return;
+ if (!(m->flags & F_SEEN)) f->unread--;
+ if (m->doc > 0) search_remove(m->doc - 1);
+ char rel[700];
+ char name[32];
+ snprintf(name, sizeof name, "m/%u", uid);
+ folder_path(a, f, name, rel, sizeof rel);
+ fs_unlink(rel);
+ msg_free(m);
+ int pos = (int)(m - f->msgs);
+ memmove(&f->msgs[pos], &f->msgs[pos + 1], (size_t)(f->n - pos - 1) * sizeof *f->msgs);
+ f->n--;
+ f->dirty = 1;
+ f->version++;
+}
+
+void store_clear(Account *a, Folder *f) {
+ for (int i = 0; i < f->n; i++) { if (f->msgs[i].doc > 0) search_remove(f->msgs[i].doc - 1); msg_free(&f->msgs[i]); }
+ f->n = 0;
+ f->unread = 0;
+ char rel[700];
+ folder_path(a, f, "m", rel, sizeof rel);
+ fs_rmtree(rel);
+ f->uidnext = 0;
+ f->modseq = 0;
+ f->dirty = 1;
+ f->version++;
+}
+
+char *store_body_path(Account *a, Folder *f, uint32_t uid, char *out, size_t cap) {
+ char name[32];
+ snprintf(name, sizeof name, "m/%u", uid);
+ folder_path(a, f, name, out, cap);
+ return out;
+}
+
+void store_save(Account *a, Folder *f) {
+ if (!f->dirty) return;
+ JBuf b;
+ jb_init(&b);
+ for (int i = 0; i < f->n; i++) {
+ Msg *m = &f->msgs[i];
+ jb_printf(&b, "%u\t%u\t%lld\t%u\t%u\t%u\t", m->uid, m->flags, (long long)m->date, m->size, m->att, m->body);
+ put_field(&b, m->from_name); jb_raw(&b, "\t");
+ put_field(&b, m->from_email); jb_raw(&b, "\t");
+ put_field(&b, m->to); jb_raw(&b, "\t");
+ put_field(&b, m->cc); jb_raw(&b, "\t");
+ put_field(&b, m->subject); jb_raw(&b, "\t");
+ put_field(&b, m->msgid); jb_raw(&b, "\t");
+ put_field(&b, m->inreplyto); jb_raw(&b, "\t");
+ put_field(&b, m->refs); jb_raw(&b, "\t");
+ put_field(&b, m->preview); jb_raw(&b, "\n");
+ }
+ char rel[700];
+ folder_path(a, f, "index", rel, sizeof rel);
+ if (!b.oom) fs_write(rel, b.p ? b.p : "", b.n);
+ jb_free(&b);
+ char st[96];
+ snprintf(st, sizeof st, "%u %u %llu\n", f->uidvalidity, f->uidnext, (unsigned long long)f->modseq);
+ folder_path(a, f, "state", rel, sizeof rel);
+ fs_write(rel, st, strlen(st));
+ f->dirty = 0;
+}
+
+void store_save_folders(Account *a) {
+ FolderList *fl = store_folders(a);
+ if (!fl) return;
+ JBuf b;
+ jb_init(&b);
+ for (int i = 0; i < fl->n; i++) {
+ Folder *f = fl->f[i];
+ put_field(&b, f->name); jb_raw(&b, "\t");
+ put_field(&b, f->display); jb_raw(&b, "\t");
+ put_field(&b, f->special);
+ jb_printf(&b, "\t%d\t%d\n", (int)(unsigned char)f->delim, f->noselect);
+ }
+ char rel[100];
+ snprintf(rel, sizeof rel, "%s/folders", a->id);
+ if (!b.oom) fs_write(rel, b.p ? b.p : "", b.n);
+ jb_free(&b);
+}
+
+static void load_folder(Account *a, Folder *f) {
+ char rel[700];
+ size_t n;
+ folder_path(a, f, "state", rel, sizeof rel);
+ char *st = fs_read(rel, &n, 256);
+ if (st) {
+ unsigned v = 0, nx = 0;
+ unsigned long long ms = 0;
+ if (sscanf(st, "%u %u %llu", &v, &nx, &ms) >= 2) { f->uidvalidity = v; f->uidnext = nx; f->modseq = ms; }
+ free(st);
+ }
+ folder_path(a, f, "index", rel, sizeof rel);
+ char *ix = fs_read(rel, &n, (size_t)512 << 20);
+ if (!ix) return;
+ char *p = ix;
+ while (*p) {
+ Msg m;
+ memset(&m, 0, sizeof m);
+ char *line_end = strchr(p, '\n');
+ if (!line_end) break;
+ unsigned long long date;
+ unsigned uid, flags, size, att, body;
+ if (sscanf(p, "%u\t%u\t%llu\t%u\t%u\t%u\t", &uid, &flags, &date, &size, &att, &body) != 6) { p = line_end + 1; continue; }
+ for (int k = 0; k < 6; k++) { char *t = strchr(p, '\t'); if (!t || t > line_end) { p = line_end; break; } p = t + 1; }
+ if (p >= line_end) { p = line_end + 1; continue; }
+ m.uid = uid; m.flags = flags; m.date = (int64_t)date; m.size = size; m.att = (uint16_t)att; m.body = (uint16_t)body;
+ m.from_name = get_field(&p); m.from_email = get_field(&p); m.to = get_field(&p); m.cc = get_field(&p);
+ m.subject = get_field(&p); m.msgid = get_field(&p); m.inreplyto = get_field(&p); m.refs = get_field(&p); m.preview = get_field(&p);
+ p = strchr(p, '\n') ? strchr(p, '\n') + 1 : p + strlen(p);
+ if (uid) store_add(a, f, &m);
+ }
+ free(ix);
+ /* the body text of downloaded messages goes into the search index too */
+ for (int i = 0; i < f->n; i++) {
+ Msg *m = &f->msgs[i];
+ if (!m->body) continue;
+ char tr[700], name[32];
+ snprintf(name, sizeof name, "t/%u", m->uid);
+ folder_path(a, f, name, tr, sizeof tr);
+ size_t tl;
+ char *t = fs_read(tr, &tl, 64 * 1024);
+ if (t) { store_msg_text(m, t); index_msg(a, f, m); free(t); }
+ }
+ f->dirty = 0;
+}
+
+void store_load(Account *a) {
+ char rel[100];
+ snprintf(rel, sizeof rel, "%s/folders", a->id);
+ size_t n;
+ char *list = fs_read(rel, &n, 4 << 20);
+ if (!list) return;
+ char *p = list;
+ while (*p) {
+ char *name = get_field(&p), *disp = get_field(&p), *sp = get_field(&p);
+ int delim = 0, nosel = 0;
+ sscanf(p, "%d\t%d", &delim, &nosel);
+ char *nl = strchr(p, '\n');
+ p = nl ? nl + 1 : p + strlen(p);
+ if (!*name) continue;
+ Folder *f = store_folder(a, name, 1);
+ if (!f) continue;
+ snprintf(f->display, sizeof f->display, "%s", disp);
+ snprintf(f->special, sizeof f->special, "%s", sp);
+ f->delim = (char)delim;
+ f->noselect = nosel;
+ load_folder(a, f);
+ }
+ free(list);
+}
+
+void store_drop_account(const char *id) {
+ for (int i = 0; i < nstores; i++) {
+ if (strcmp(stores[i].id, id)) continue;
+ FolderList *fl = &stores[i].fl;
+ for (int k = 0; k < fl->n; k++) {
+ Folder *f = fl->f[k];
+ for (int m = 0; m < f->n; m++) { if (f->msgs[m].doc > 0) search_remove(f->msgs[m].doc - 1); msg_free(&f->msgs[m]); }
+ free(f->msgs);
+ free(f);
+ }
+ free(fl->f);
+ char rel[64];
+ snprintf(rel, sizeof rel, "%s", id);
+ fs_rmtree(rel);
+ stores[i] = stores[--nstores];
+ return;
+ }
+}
+
+/* ---- JSON ---- */
+
+static int special_rank(const char *sp) {
+ static const char *order[] = { "inbox", "drafts", "sent", "archive", "junk", "trash", "all", "flagged" };
+ for (int i = 0; i < 8; i++) if (!strcmp(sp, order[i])) return i;
+ return 20;
+}
+
+static int cmp_folder(const void *x, const void *y) {
+ const Folder *a = *(Folder *const *)x, *b = *(Folder *const *)y;
+ int ra = special_rank(a->special), rb = special_rank(b->special);
+ if (ra != rb) return ra - rb;
+ return strcasecmp(a->display, b->display);
+}
+
+void store_folders_json(JBuf *b) {
+ jb_raw(b, "{\"accounts\":[");
+ int first = 1;
+ for (int i = 0; i < naccounts; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop || strcmp(a->kind, "mail")) continue;
+ FolderList *fl = store_folders(a);
+ if (!first) jb_raw(b, ",");
+ first = 0;
+ jb_raw(b, "{\"id\":"); jb_str(b, a->id);
+ jb_raw(b, ",\"name\":"); jb_str(b, a->name[0] ? a->name : a->email);
+ jb_raw(b, ",\"email\":"); jb_str(b, a->email);
+ jb_raw(b, ",\"status\":"); jb_str(b, a->status);
+ jb_raw(b, ",\"folders\":[");
+ Folder **sorted = fl && fl->n ? malloc((size_t)fl->n * sizeof *sorted) : NULL;
+ int n = 0;
+ if (sorted) { memcpy(sorted, fl->f, (size_t)fl->n * sizeof *sorted); n = fl->n; qsort(sorted, (size_t)n, sizeof *sorted, cmp_folder); }
+ for (int k = 0; k < n; k++) {
+ Folder *f = sorted[k];
+ if (k) jb_raw(b, ",");
+ jb_raw(b, "{\"name\":"); jb_str(b, f->name);
+ jb_raw(b, ",\"display\":"); jb_str(b, f->display);
+ jb_raw(b, ",\"special\":"); jb_str(b, f->special);
+ char d[2] = { f->delim ? f->delim : '/', 0 };
+ jb_raw(b, ",\"delim\":"); jb_str(b, d);
+ jb_printf(b, ",\"total\":%d,\"unread\":%d,\"noselect\":%s}", f->n, f->unread < 0 ? 0 : f->unread, f->noselect ? "true" : "false");
+ }
+ free(sorted);
+ jb_raw(b, "]}");
+ }
+ jb_raw(b, "]}");
+}
+
+void store_counts_json(JBuf *b) {
+ int total = 0;
+ jb_raw(b, "{\"inbox\":[");
+ int first = 1;
+ for (int i = 0; i < naccounts; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop || strcmp(a->kind, "mail")) continue;
+ Folder *f = store_folder(a, "INBOX", 0);
+ int u = f && f->unread > 0 ? f->unread : 0;
+ total += u;
+ if (!first) jb_raw(b, ",");
+ first = 0;
+ jb_raw(b, "{\"acct\":"); jb_str(b, a->id);
+ jb_printf(b, ",\"unread\":%d}", u);
+ }
+ jb_printf(b, "],\"unread\":%d}", total);
+}
+
+/* ---- lists and conversations ---- */
+
+typedef struct { int acct; Folder *f; Msg *m; uint64_t key; } Ent;
+typedef struct { int first; int n, unread, flagged, att; uint64_t key; } Grp;
+
+static uint64_t h64(const char *s, size_t n) {
+ uint64_t h = 1469598103934665603ull;
+ for (size_t i = 0; i < n; i++) { h ^= (unsigned char)s[i]; h *= 1099511628211ull; }
+ return h ? h : 1;
+}
+
+/* conversation key: the first Message-ID of References (the root), else In-Reply-To, else
+ * the message's own id; replies without headers fall back to the subject without "Re:" */
+static uint64_t thread_key(const Msg *m) {
+ const char *r = m->refs && *m->refs ? m->refs : m->inreplyto && *m->inreplyto ? m->inreplyto : NULL;
+ if (r) {
+ const char *a = strchr(r, '<');
+ const char *e = a ? strchr(a, '>') : NULL;
+ if (a && e) return h64(a + 1, (size_t)(e - a - 1));
+ }
+ char base[512];
+ mime_base_subject(m->subject, base, sizeof base);
+ if (m->subject && strcmp(base, m->subject) && base[0]) {
+ char low[512];
+ search_fold(base, low, sizeof low);
+ uint64_t k = h64(low, strlen(low));
+ return k ^ 0x5bd1e995ull;
+ }
+ if (m->msgid && *m->msgid) {
+ const char *a = strchr(m->msgid, '<');
+ const char *e = a ? strchr(a, '>') : NULL;
+ if (a && e) return h64(a + 1, (size_t)(e - a - 1));
+ return h64(m->msgid, strlen(m->msgid));
+ }
+ return h64((const char *)&m, sizeof m); /* unique: alone */
+}
+
+/* the subject-only key of an original message, so "Re: X" without headers joins "X" */
+static uint64_t subject_key(const Msg *m) {
+ char base[512], low[512];
+ mime_base_subject(m->subject, base, sizeof base);
+ search_fold(base, low, sizeof low);
+ return h64(low, strlen(low)) ^ 0x5bd1e995ull;
+}
+
+static int cmp_ent(const void *x, const void *y) {
+ const Ent *a = x, *b = y;
+ if (a->m->date != b->m->date) return a->m->date > b->m->date ? -1 : 1;
+ return a->m->uid > b->m->uid ? -1 : a->m->uid < b->m->uid ? 1 : 0;
+}
+
+static void flags_json(JBuf *b, uint32_t f) {
+ jb_printf(b, ",\"seen\":%s,\"flagged\":%s,\"answered\":%s,\"forwarded\":%s,\"draft\":%s", f & F_SEEN ? "true" : "false",
+ f & F_FLAGGED ? "true" : "false", f & F_ANSWERED ? "true" : "false", f & F_FORWARDED ? "true" : "false", f & F_DRAFT ? "true" : "false");
+ jb_raw(b, ",\"labels\":[");
+ int first = 1;
+ for (int i = 0; i < 6; i++) if (f & (F_LABEL1 << i)) { jb_printf(b, "%s%d", first ? "" : ",", i + 1); first = 0; }
+ jb_raw(b, "]");
+}
+
+static void item_json(JBuf *b, const Ent *e, const Grp *g, const Ent *all) {
+ const Msg *m = e->m;
+ const Account *a = accounts[e->acct];
+ jb_raw(b, "{\"acct\":"); jb_str(b, a->id);
+ jb_raw(b, ",\"folder\":"); jb_str(b, e->f->name);
+ jb_printf(b, ",\"uid\":%u,\"date\":%lld", m->uid, (long long)m->date * 1000);
+ jb_raw(b, ",\"from\":"); jb_str(b, m->from_name && *m->from_name ? m->from_name : m->from_email);
+ jb_raw(b, ",\"email\":"); jb_str(b, m->from_email);
+ jb_raw(b, ",\"to\":"); jb_str(b, m->to);
+ jb_raw(b, ",\"subject\":"); jb_str(b, m->subject);
+ jb_raw(b, ",\"preview\":"); jb_str(b, m->preview);
+ flags_json(b, m->flags);
+ jb_printf(b, ",\"att\":%s", m->att ? "true" : "false");
+ if (g) {
+ jb_printf(b, ",\"n\":%d,\"unreadN\":%d,\"anyFlag\":%s,\"tk\":\"%016llx\"", g->n, g->unread, g->flagged ? "true" : "false", (unsigned long long)g->key);
+ if (g->n > 1) {
+ /* the conversation's messages in this list, newest first (for actions and expanding) */
+ jb_raw(b, ",\"thread\":[");
+ int k = 0;
+ for (int i = g->first; all && k < g->n && k < 200; i++) {
+ if (all[i].key != g->key) continue;
+ if (k) jb_raw(b, ",");
+ jb_raw(b, "{\"acct\":"); jb_str(b, accounts[all[i].acct]->id);
+ jb_raw(b, ",\"folder\":"); jb_str(b, all[i].f->name);
+ jb_printf(b, ",\"uid\":%u,\"seen\":%s}", all[i].m->uid, all[i].m->flags & F_SEEN ? "true" : "false");
+ k++;
+ }
+ jb_raw(b, "]");
+ }
+ }
+ jb_raw(b, "}");
+}
+
+static int filter_ok(const Msg *m, const char *filter, int label) {
+ if (m->flags & F_DELETED) return 0;
+ if (label && !(m->flags & (F_LABEL1 << (label - 1)))) return 0;
+ if (!filter || !*filter || !strcmp(filter, "all")) return 1;
+ if (!strcmp(filter, "unread")) return !(m->flags & F_SEEN);
+ if (!strcmp(filter, "flagged")) return (m->flags & F_FLAGGED) != 0;
+ if (!strcmp(filter, "att")) return m->att != 0;
+ return 1;
+}
+
+/* cache of the last built list (sorting 10,000 rows on every scroll would be wasteful) */
+static struct { char key[700]; uint64_t ver; Ent *e; int n; Grp *g; int ng; } view;
+
+static uint64_t versions(const char *acct, const char *folder, int unified) {
+ uint64_t v = 0;
+ for (int i = 0; i < naccounts; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop || strcmp(a->kind, "mail")) continue;
+ if (!unified && strcmp(a->id, acct)) continue;
+ FolderList *fl = store_folders(a);
+ for (int k = 0; fl && k < fl->n; k++) {
+ Folder *f = fl->f[k];
+ if (unified ? !strcmp(f->special, "inbox") : !strcmp(f->name, folder)) v = v * 31 + f->version + (uint64_t)(uintptr_t)f;
+ }
+ }
+ return v;
+}
+
+static int build_view(const char *acct, const char *folder, int unified, int threaded, const char *filter, int label) {
+ char key[700];
+ snprintf(key, sizeof key, "%s|%s|%d|%d|%s|%d", acct ? acct : "", folder ? folder : "", unified, threaded, filter ? filter : "", label);
+ uint64_t ver = versions(acct ? acct : "", folder ? folder : "", unified);
+ if (!strcmp(view.key, key) && view.ver == ver && view.e) return 0;
+ free(view.e); free(view.g);
+ memset(&view, 0, sizeof view);
+ int cap = 0;
+ for (int i = 0; i < naccounts; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop || strcmp(a->kind, "mail") || (!unified && strcmp(a->id, acct))) continue;
+ FolderList *fl = store_folders(a);
+ for (int k = 0; fl && k < fl->n; k++) {
+ Folder *f = fl->f[k];
+ if (unified ? strcmp(f->special, "inbox") : strcmp(f->name, folder)) continue;
+ cap += f->n;
+ }
+ }
+ view.e = malloc((size_t)(cap ? cap : 1) * sizeof *view.e);
+ if (!view.e) return -1;
+ for (int i = 0; i < naccounts; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop || strcmp(a->kind, "mail") || (!unified && strcmp(a->id, acct))) continue;
+ FolderList *fl = store_folders(a);
+ for (int k = 0; fl && k < fl->n; k++) {
+ Folder *f = fl->f[k];
+ if (unified ? strcmp(f->special, "inbox") : strcmp(f->name, folder)) continue;
+ for (int m = 0; m < f->n; m++) if (filter_ok(&f->msgs[m], filter, label)) view.e[view.n++] = (Ent){ i, f, &f->msgs[m], 0 };
+ }
+ }
+ qsort(view.e, (size_t)view.n, sizeof *view.e, cmp_ent);
+ view.g = malloc((size_t)(view.n ? view.n : 1) * sizeof *view.g);
+ if (!view.g) return -1;
+ if (threaded) {
+ /* hash table key → group */
+ size_t hc = 16;
+ while (hc < (size_t)view.n * 2) hc *= 2;
+ int *tab = malloc(hc * sizeof *tab);
+ if (!tab) return -1;
+ for (size_t i = 0; i < hc; i++) tab[i] = -1;
+ /* subject keys of originals, so header-less replies can join them */
+ for (int i = 0; i < view.n; i++) {
+ Ent *e = &view.e[i];
+ uint64_t k = thread_key(e->m) ^ ((uint64_t)e->acct << 56);
+ e->key = k;
+ }
+ for (int i = 0; i < view.n; i++) {
+ Ent *e = &view.e[i];
+ size_t h = (size_t)e->key & (hc - 1);
+ while (tab[h] >= 0 && view.g[tab[h]].key != e->key) h = (h + 1) & (hc - 1);
+ if (tab[h] < 0) {
+ tab[h] = view.ng;
+ view.g[view.ng++] = (Grp){ i, 0, 0, 0, 0, e->key };
+ }
+ Grp *g = &view.g[tab[h]];
+ g->n++;
+ if (!(e->m->flags & F_SEEN)) g->unread++;
+ if (e->m->flags & F_FLAGGED) g->flagged = 1;
+ if (e->m->att) g->att = 1;
+ }
+ free(tab);
+ (void)subject_key;
+ } else {
+ for (int i = 0; i < view.n; i++) view.g[view.ng++] = (Grp){ i, 1, !(view.e[i].m->flags & F_SEEN), (view.e[i].m->flags & F_FLAGGED) != 0, view.e[i].m->att, 0 };
+ }
+ snprintf(view.key, sizeof view.key, "%s", key);
+ view.ver = ver;
+ return 0;
+}
+
+void store_list_json(JBuf *b, const JVal *args) {
+ const char *acct = json_str(args, "acct"), *folder = json_str(args, "folder");
+ int unified = json_bool(args, "unified", 0) || (folder && !strcmp(folder, "*inbox"));
+ int threaded = json_bool(args, "threaded", 1);
+ const char *filter = json_str(args, "filter");
+ int label = (int)json_num(args, "label", 0);
+ if (label < 0 || label > 6) label = 0;
+ int off = (int)json_num(args, "offset", 0), cnt = (int)json_num(args, "count", 60);
+ if (off < 0) off = 0;
+ if (cnt < 1) cnt = 1;
+ if (cnt > 500) cnt = 500;
+ if (!unified && (!acct || !folder)) { jb_raw(b, "{\"total\":0,\"items\":[]}"); return; }
+ if (build_view(acct, folder, unified, threaded, filter, label)) { jb_raw(b, "{\"total\":0,\"items\":[],\"error\":\"memory\"}"); return; }
+ jb_printf(b, "{\"total\":%d,\"messages\":%d,\"version\":%llu,\"items\":[", view.ng, view.n, (unsigned long long)view.ver);
+ for (int i = off; i < view.ng && i < off + cnt; i++) {
+ if (i > off) jb_raw(b, ",");
+ item_json(b, &view.e[view.g[i].first], threaded ? &view.g[i] : NULL, view.e);
+ }
+ jb_raw(b, "]}");
+}
+
+void store_search_json(JBuf *b, const JVal *args) {
+ const char *q = json_str(args, "q");
+ const char *acct = json_str(args, "acct");
+ Hit *hits = malloc(sizeof *hits * 2000);
+ int n = hits && q ? search_query(q, hits, 2000) : 0;
+ Ent *ents = malloc(sizeof *ents * (size_t)(n ? n : 1));
+ int ne = 0;
+ for (int i = 0; ents && i < n; i++) {
+ if (hits[i].acct < 0 || hits[i].acct >= naccounts || !accounts[hits[i].acct] || accounts[hits[i].acct]->stop) continue;
+ if (acct && *acct && strcmp(accounts[hits[i].acct]->id, acct)) continue;
+ Msg *m = store_msg(hits[i].f, hits[i].uid);
+ if (!m || (m->flags & F_DELETED)) continue;
+ ents[ne++] = (Ent){ hits[i].acct, hits[i].f, m, 0 };
+ }
+ if (ents) qsort(ents, (size_t)ne, sizeof *ents, cmp_ent);
+ int max = (int)json_num(args, "count", 300);
+ if (max < 1 || max > 2000) max = 300;
+ jb_printf(b, "{\"total\":%d,\"items\":[", ne);
+ for (int i = 0; i < ne && i < max; i++) {
+ if (i) jb_raw(b, ",");
+ item_json(b, &ents[i], NULL, NULL);
+ }
+ jb_raw(b, "]}");
+ free(ents);
+ free(hits);
+}
+
+void store_autocomplete(const char *q, JBuf *b, int *count, int max) {
+ char fq[256];
+ search_fold(q, fq, sizeof fq);
+ if (strlen(fq) < 1) return;
+ /* senders and recipients we have seen, newest first, without repeats */
+ typedef struct { const char *name, *email; int64_t date; } Seen;
+ int cap = 64, n = 0;
+ Seen *s = malloc((size_t)cap * sizeof *s);
+ if (!s) return;
+ for (int i = 0; i < naccounts && n < 4000; i++) {
+ Account *a = accounts[i];
+ if (!a || a->stop || strcmp(a->kind, "mail")) continue;
+ FolderList *fl = store_folders(a);
+ for (int k = 0; fl && k < fl->n; k++) {
+ Folder *f = fl->f[k];
+ if (!strcmp(f->special, "junk") || !strcmp(f->special, "trash")) continue;
+ for (int m = 0; m < f->n && n < 4000; m++) {
+ Msg *x = &f->msgs[m];
+ if (!x->from_email || !*x->from_email) continue;
+ char fe[300], fnm[300];
+ search_fold(x->from_email, fe, sizeof fe);
+ search_fold(x->from_name, fnm, sizeof fnm);
+ if (strncmp(fe, fq, strlen(fq)) && !strstr(fnm, fq)) continue;
+ int dup = 0;
+ for (int d = 0; d < n; d++) if (!strcasecmp(s[d].email, x->from_email)) { dup = 1; if (x->date > s[d].date) s[d].date = x->date; break; }
+ if (dup) continue;
+ if (n == cap) { cap *= 2; Seen *ns = realloc(s, (size_t)cap * sizeof *ns); if (!ns) break; s = ns; }
+ s[n++] = (Seen){ x->from_name, x->from_email, x->date };
+ }
+ }
+ }
+ /* newest first */
+ for (int i = 1; i < n; i++) for (int j = i; j > 0 && s[j].date > s[j - 1].date; j--) { Seen t = s[j]; s[j] = s[j - 1]; s[j - 1] = t; }
+ for (int i = 0; i < n && *count < max; i++) {
+ if (*count) jb_raw(b, ",");
+ jb_raw(b, "{\"name\":"); jb_str(b, s[i].name);
+ jb_raw(b, ",\"email\":"); jb_str(b, s[i].email);
+ jb_raw(b, ",\"src\":\"mail\"}");
+ (*count)++;
+ }
+ free(s);
+}
+
+/* Every message of one conversation in the account, oldest first, from any folder except the
+ * trash and junk (so the reading pane shows the replies we sent too). */
+void store_thread_json(JBuf *b, const JVal *args) {
+ Account *a = acct_get(json_str(args, "acct"));
+ const char *tk = json_str(args, "tk");
+ jb_raw(b, "{\"items\":[");
+ if (!a || !tk) { jb_raw(b, "]}"); return; }
+ unsigned long long want = strtoull(tk, NULL, 16);
+ int ai = acct_index(a);
+ FolderList *fl = store_folders(a);
+ Ent *e = NULL;
+ int n = 0, cap = 0;
+ for (int k = 0; fl && k < fl->n; k++) {
+ Folder *f = fl->f[k];
+ if (!strcmp(f->special, "trash") || !strcmp(f->special, "junk") || !strcmp(f->special, "all")) continue;
+ for (int m = 0; m < f->n; m++) {
+ if (f->msgs[m].flags & F_DELETED) continue;
+ uint64_t key = thread_key(&f->msgs[m]) ^ ((uint64_t)ai << 56);
+ if (key != want) continue;
+ if (n == cap) { cap = cap ? cap * 2 : 16; Ent *ne = realloc(e, (size_t)cap * sizeof *ne); if (!ne) break; e = ne; }
+ e[n++] = (Ent){ ai, f, &f->msgs[m], key };
+ }
+ }
+ if (e) qsort(e, (size_t)n, sizeof *e, cmp_ent);
+ /* duplicates (the same Message-ID in two folders, e.g. Gmail labels): keep one */
+ int out = 0;
+ for (int i = n - 1; i >= 0 && out < 200; i--) {
+ int dup = 0;
+ for (int j = n - 1; j > i; j--) if (e[j].m->msgid && *e[j].m->msgid && e[i].m->msgid && !strcmp(e[j].m->msgid, e[i].m->msgid)) dup = 1;
+ if (dup) continue;
+ if (out) jb_raw(b, ",");
+ item_json(b, &e[i], NULL, NULL);
+ out++;
+ }
+ jb_raw(b, "]}");
+ free(e);
+}
diff --git a/server/src/mail/vcard.c b/server/src/mail/vcard.c
new file mode 100644
index 0000000..5d97584
--- /dev/null
+++ b/server/src/mail/vcard.c
@@ -0,0 +1,381 @@
+/* vcard.c — see vcard.h. */
+#include "vcard.h"
+#include "ical.h"
+#include "mime.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <time.h>
+
+/* Splits a structured value on unescaped ';' into up to max unescaped fields. */
+static int split_fields(const char *v, char fields[][256], int max) {
+ int n = 0;
+ size_t o = 0;
+ for (int i = 0; i < max; i++) fields[i][0] = 0;
+ for (; v && *v && n < max; v++) {
+ if (*v == '\\' && v[1]) {
+ v++;
+ char c = (*v == 'n' || *v == 'N') ? '\n' : *v;
+ if (o + 1 < 256) fields[n][o++] = c;
+ continue;
+ }
+ if (*v == ';') { fields[n][o] = 0; n++; o = 0; continue; }
+ if (o + 1 < 256) fields[n][o++] = *v;
+ }
+ if (n < max) { fields[n][o] = 0; n++; }
+ return n;
+}
+
+/* vCard 2.1 values may be quoted-printable and in another charset */
+static char *prop_text(const IcProp *p) {
+ char enc[32] = "", cs[40] = "";
+ ic_param(p, "ENCODING", enc, sizeof enc);
+ ic_param(p, "CHARSET", cs, sizeof cs);
+ if (!strcasecmp(enc, "QUOTED-PRINTABLE")) {
+ size_t n = strlen(p->value);
+ char *raw = malloc(n + 1);
+ if (!raw) return NULL;
+ size_t rl = qp_decode(p->value, n, raw, 0);
+ size_t ul;
+ char *u = charset_to_utf8(cs[0] ? cs : "utf-8", raw, rl, &ul);
+ free(raw);
+ return u;
+ }
+ size_t ul;
+ return cs[0] ? charset_to_utf8(cs, p->value, strlen(p->value), &ul) : utf8_clean(p->value, strlen(p->value), &ul);
+}
+
+static void type_of(const IcProp *p, char *out, size_t cap) {
+ char t[128] = "";
+ ic_param(p, "TYPE", t, sizeof t);
+ out[0] = 0;
+ /* first meaningful type: home, work, cell/mobile, fax, iphone, main, other */
+ char *save = NULL;
+ for (char *tok = strtok_r(t, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
+ while (*tok == ' ') tok++;
+ for (char *c = tok; *c; c++) *c = (char)tolower((unsigned char)*c);
+ if (!strcmp(tok, "pref") || !strcmp(tok, "internet") || !strcmp(tok, "voice") || !strcmp(tok, "x400")) continue;
+ if (!strcmp(tok, "mobile")) tok = "cell";
+ snprintf(out, cap, "%s", tok);
+ return;
+ }
+ /* Apple: item1.X-ABLabel:_$!<Other>!$_ is a separate property; ignore */
+}
+
+static void list_item(JBuf *b, int *first, const char *type, const char *value) {
+ if (!value || !*value) return;
+ jb_raw(b, *first ? "{\"type\":" : ",{\"type\":");
+ jb_str(b, type);
+ jb_raw(b, ",\"value\":");
+ jb_str(b, value);
+ jb_raw(b, "}");
+ *first = 0;
+}
+
+static void one_card(const IcComp *c, JBuf *b) {
+ char fields[7][256];
+ IcProp *p;
+ jb_raw(b, "{\"uid\":");
+ p = ic_prop(c, "UID");
+ char uid[256] = "";
+ if (p) ic_unescape(p->value, uid, sizeof uid);
+ if (!strncasecmp(uid, "urn:uuid:", 9)) memmove(uid, uid + 9, strlen(uid + 9) + 1);
+ jb_str(b, uid);
+ char *fn = NULL;
+ if ((p = ic_prop(c, "FN"))) { char *t = prop_text(p); if (t) { fn = ic_unescape_dup(t); free(t); } }
+ jb_raw(b, ",\"fn\":");
+ jb_str(b, fn ? fn : "");
+ free(fn);
+ jb_raw(b, ",\"n\":{");
+ if ((p = ic_prop(c, "N"))) {
+ char *t = prop_text(p);
+ split_fields(t ? t : "", fields, 5);
+ free(t);
+ static const char *k[] = { "family", "given", "middle", "prefix", "suffix" };
+ for (int i = 0; i < 5; i++) { jb_printf(b, "%s\"%s\":", i ? "," : "", k[i]); jb_str(b, fields[i]); }
+ }
+ jb_raw(b, "}");
+ if ((p = ic_prop(c, "NICKNAME"))) { char t[256]; ic_unescape(p->value, t, sizeof t); jb_raw(b, ",\"nick\":"); jb_str(b, t); }
+ if ((p = ic_prop(c, "ORG"))) {
+ char *t = prop_text(p);
+ split_fields(t ? t : "", fields, 2);
+ free(t);
+ jb_raw(b, ",\"org\":"); jb_str(b, fields[0]);
+ if (fields[1][0]) { jb_raw(b, ",\"dept\":"); jb_str(b, fields[1]); }
+ }
+ if ((p = ic_prop(c, "TITLE"))) { char t[256]; ic_unescape(p->value, t, sizeof t); jb_raw(b, ",\"title\":"); jb_str(b, t); }
+ static const struct { const char *prop, *key; } lists[] = { { "EMAIL", "emails" }, { "TEL", "phones" }, { "URL", "urls" }, { "IMPP", "im" } };
+ for (size_t l = 0; l < sizeof lists / sizeof lists[0]; l++) {
+ jb_printf(b, ",\"%s\":[", lists[l].key);
+ int first = 1;
+ for (p = ic_prop(c, lists[l].prop); p; p = ic_prop_next(c, p, lists[l].prop)) {
+ char ty[32], v[512];
+ type_of(p, ty, sizeof ty);
+ char *t = prop_text(p);
+ ic_unescape(t ? t : "", v, sizeof v);
+ free(t);
+ if (!strcmp(lists[l].prop, "TEL") && !strncasecmp(v, "tel:", 4)) memmove(v, v + 4, strlen(v + 4) + 1);
+ list_item(b, &first, ty, v);
+ }
+ jb_raw(b, "]");
+ }
+ jb_raw(b, ",\"addrs\":[");
+ int first = 1;
+ for (p = ic_prop(c, "ADR"); p; p = ic_prop_next(c, p, "ADR")) {
+ char ty[32];
+ type_of(p, ty, sizeof ty);
+ char *t = prop_text(p);
+ split_fields(t ? t : "", fields, 7);
+ free(t);
+ jb_raw(b, first ? "{\"type\":" : ",{\"type\":");
+ first = 0;
+ jb_str(b, ty);
+ /* street = extended + street */
+ char street[520];
+ snprintf(street, sizeof street, "%s%s%s", fields[1], fields[1][0] && fields[2][0] ? "\n" : "", fields[2]);
+ jb_raw(b, ",\"street\":"); jb_str(b, street);
+ jb_raw(b, ",\"city\":"); jb_str(b, fields[3]);
+ jb_raw(b, ",\"region\":"); jb_str(b, fields[4]);
+ jb_raw(b, ",\"code\":"); jb_str(b, fields[5]);
+ jb_raw(b, ",\"country\":"); jb_str(b, fields[6]);
+ jb_raw(b, "}");
+ }
+ jb_raw(b, "]");
+ if ((p = ic_prop(c, "BDAY"))) {
+ int64_t t; int ad, y, m, d;
+ char tz[8];
+ const char *v = p->value;
+ if (!strncmp(v, "--", 2)) { /* vCard 4: --0517 (no year) */
+ if (strlen(v) >= 6) { char out[16]; snprintf(out, sizeof out, "--%.2s-%.2s", v + 2, v + 4); jb_raw(b, ",\"bday\":"); jb_str(b, out); }
+ } else if (ic_time(p, &t, &ad, tz, sizeof tz)) {
+ int64_t w = t + ic_zone_offset(NULL, t);
+ ic_civil_from_days(w >= 0 ? w / 86400 : (w - 86399) / 86400, &y, &m, &d);
+ char out[16];
+ snprintf(out, sizeof out, "%04d-%02d-%02d", y, m, d);
+ jb_raw(b, ",\"bday\":"); jb_str(b, out);
+ }
+ }
+ if ((p = ic_prop(c, "NOTE"))) { char *t = prop_text(p); char *u = ic_unescape_dup(t ? t : ""); free(t); jb_raw(b, ",\"notes\":"); jb_str(b, u ? u : ""); free(u); }
+ if ((p = ic_prop(c, "CATEGORIES"))) {
+ jb_raw(b, ",\"cats\":[");
+ char t[512];
+ snprintf(t, sizeof t, "%s", p->value);
+ int f = 1;
+ char *save = NULL;
+ for (char *tok = strtok_r(t, ",", &save); tok; tok = strtok_r(NULL, ",", &save)) {
+ char u[256];
+ ic_unescape(tok, u, sizeof u);
+ if (!u[0]) continue;
+ if (!f) jb_raw(b, ",");
+ jb_str(b, u);
+ f = 0;
+ }
+ jb_raw(b, "]");
+ }
+ jb_printf(b, ",\"photo\":%s", ic_prop(c, "PHOTO") ? "true" : "false");
+ IcProp *kind = ic_prop(c, "KIND");
+ if (!kind) kind = ic_prop(c, "X-ADDRESSBOOKSERVER-KIND");
+ int group = kind && !strncasecmp(kind->value, "group", 5);
+ jb_printf(b, ",\"kind\":\"%s\"", group ? "group" : "individual");
+ if (group) {
+ jb_raw(b, ",\"members\":[");
+ int f = 1;
+ for (int pass = 0; pass < 2; pass++) {
+ const char *pn = pass ? "X-ADDRESSBOOKSERVER-MEMBER" : "MEMBER";
+ for (p = ic_prop(c, pn); p; p = ic_prop_next(c, p, pn)) {
+ char u[256];
+ ic_unescape(p->value, u, sizeof u);
+ const char *x = !strncasecmp(u, "urn:uuid:", 9) ? u + 9 : u;
+ if (!*x) continue;
+ if (!f) jb_raw(b, ",");
+ jb_str(b, x);
+ f = 0;
+ }
+ }
+ jb_raw(b, "]");
+ }
+ if ((p = ic_prop(c, "REV"))) { jb_raw(b, ",\"rev\":"); jb_str(b, p->value); }
+ jb_raw(b, "}");
+}
+
+int vcard_json(const char *text, size_t len, JBuf *b) {
+ const char *err;
+ IcComp *root = ic_parse(text, len, &err);
+ if (!root) return -1;
+ int n = 0;
+ for (IcComp *c = root->kid; c; c = c->next) {
+ if (strcmp(c->name, "VCARD")) continue;
+ if (n) jb_raw(b, ",");
+ one_card(c, b);
+ n++;
+ if (n >= 50000) break;
+ }
+ ic_free(root);
+ return n ? n : -1;
+}
+
+unsigned char *vcard_photo(const char *text, size_t len, size_t *olen) {
+ *olen = 0;
+ const char *err;
+ IcComp *root = ic_parse(text, len, &err);
+ if (!root) return NULL;
+ unsigned char *out = NULL;
+ for (IcComp *c = root->kid; c && !out; c = c->next) {
+ if (strcmp(c->name, "VCARD")) continue;
+ IcProp *p = ic_prop(c, "PHOTO");
+ if (!p) break;
+ const char *v = p->value;
+ char enc[16] = "";
+ ic_param(p, "ENCODING", enc, sizeof enc);
+ if (!strncasecmp(v, "data:", 5)) {
+ const char *comma = strchr(v, ',');
+ if (!comma || !strstr(v, ";base64")) break;
+ v = comma + 1;
+ } else if (strcasecmp(enc, "b") && strcasecmp(enc, "base64")) break; /* a URI: not fetched */
+ size_t n = strlen(v);
+ if (n > VCARD_MAX_PHOTO * 4 / 3 + 16) break;
+ out = malloc(n * 3 / 4 + 4);
+ if (out) *olen = b64_decode(v, n, out);
+ break;
+ }
+ ic_free(root);
+ return out;
+}
+
+void vcard_uid(const char *text, size_t len, char *out, size_t cap) {
+ if (cap) out[0] = 0;
+ const char *err;
+ IcComp *root = ic_parse(text, len, &err);
+ if (!root) return;
+ for (IcComp *c = root->kid; c; c = c->next) {
+ if (strcmp(c->name, "VCARD")) continue;
+ IcProp *p = ic_prop(c, "UID");
+ if (p) { ic_unescape(p->value, out, cap); size_t l = strlen(out); if (l >= 9 && !strncasecmp(out, "urn:uuid:", 9)) memmove(out, out + 9, l - 8); }
+ break;
+ }
+ ic_free(root);
+}
+
+void vcard_emails(const char *text, size_t len, void (*fn)(void *u, const char *name, const char *email), void *u) {
+ const char *err;
+ IcComp *root = ic_parse(text, len, &err);
+ if (!root) return;
+ for (IcComp *c = root->kid; c; c = c->next) {
+ if (strcmp(c->name, "VCARD")) continue;
+ char name[256] = "";
+ IcProp *p = ic_prop(c, "FN");
+ if (p) { char *t = prop_text(p); ic_unescape(t ? t : "", name, sizeof name); free(t); }
+ for (p = ic_prop(c, "EMAIL"); p; p = ic_prop_next(c, p, "EMAIL")) {
+ char e[256];
+ ic_unescape(p->value, e, sizeof e);
+ if (e[0]) fn(u, name, e);
+ }
+ }
+ ic_free(root);
+}
+
+/* ---- writing ---- */
+
+static void field(JBuf *b, const char *s) {
+ char *e = ic_escape(s ? s : "");
+ if (e) { jb_raw(b, e); free(e); }
+}
+
+static const char *js(const JVal *o, const char *k) { const char *s = json_str(o, k); return s ? s : ""; }
+
+static void typed_line(JBuf *b, const char *prop, const JVal *item, const char *extra_type) {
+ const char *type = js(item, "type"), *value = js(item, "value");
+ if (!*value) return;
+ JBuf l;
+ jb_init(&l);
+ jb_raw(&l, prop);
+ char t[40];
+ size_t o = 0;
+ for (const char *c = type; *c && o + 1 < sizeof t; c++) if (isalnum((unsigned char)*c) || *c == '-') t[o++] = (char)toupper((unsigned char)*c);
+ t[o] = 0;
+ if (t[0] || extra_type) {
+ jb_raw(&l, ";TYPE=");
+ if (extra_type) { jb_raw(&l, extra_type); if (t[0]) jb_raw(&l, ","); }
+ jb_raw(&l, t);
+ }
+ jb_raw(&l, ":");
+ field(&l, value);
+ if (!l.oom) ic_line(b, l.p);
+ jb_free(&l);
+}
+
+char *vcard_build(const JVal *c, const unsigned char *photo, size_t plen, const char *ptype, size_t *olen) {
+ JBuf b, l;
+ jb_init(&b);
+ jb_raw(&b, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//LordOS//Contacts 1.0//EN\r\n");
+#define LINE(...) do { jb_init(&l); __VA_ARGS__; if (!l.oom) ic_line(&b, l.p); jb_free(&l); } while (0)
+ LINE(jb_raw(&l, "UID:"); field(&l, js(c, "uid")));
+ const JVal *n = json_get(c, "n");
+ const char *fn = js(c, "fn");
+ char fnbuf[600];
+ if (!*fn) {
+ snprintf(fnbuf, sizeof fnbuf, "%s%s%s", js(n, "given"), *js(n, "given") && *js(n, "family") ? " " : "", js(n, "family"));
+ if (!fnbuf[0]) snprintf(fnbuf, sizeof fnbuf, "%s", js(c, "org"));
+ fn = fnbuf;
+ }
+ LINE(jb_raw(&l, "FN:"); field(&l, fn));
+ LINE(jb_raw(&l, "N:"); field(&l, js(n, "family")); jb_raw(&l, ";"); field(&l, js(n, "given")); jb_raw(&l, ";"); field(&l, js(n, "middle"));
+ jb_raw(&l, ";"); field(&l, js(n, "prefix")); jb_raw(&l, ";"); field(&l, js(n, "suffix")));
+ if (*js(c, "nick")) LINE(jb_raw(&l, "NICKNAME:"); field(&l, js(c, "nick")));
+ if (*js(c, "org") || *js(c, "dept")) LINE(jb_raw(&l, "ORG:"); field(&l, js(c, "org")); if (*js(c, "dept")) { jb_raw(&l, ";"); field(&l, js(c, "dept")); });
+ if (*js(c, "title")) LINE(jb_raw(&l, "TITLE:"); field(&l, js(c, "title")));
+ const JVal *arr;
+ if ((arr = json_get(c, "emails")) && arr->type == J_ARR) for (const JVal *it = arr->kid; it; it = it->next) typed_line(&b, "EMAIL", it, "INTERNET");
+ if ((arr = json_get(c, "phones")) && arr->type == J_ARR) for (const JVal *it = arr->kid; it; it = it->next) typed_line(&b, "TEL", it, NULL);
+ if ((arr = json_get(c, "urls")) && arr->type == J_ARR) for (const JVal *it = arr->kid; it; it = it->next) typed_line(&b, "URL", it, NULL);
+ if ((arr = json_get(c, "im")) && arr->type == J_ARR) for (const JVal *it = arr->kid; it; it = it->next) typed_line(&b, "IMPP", it, NULL);
+ if ((arr = json_get(c, "addrs")) && arr->type == J_ARR) {
+ for (const JVal *it = arr->kid; it; it = it->next) {
+ char t[40];
+ size_t o = 0;
+ for (const char *x = js(it, "type"); *x && o + 1 < sizeof t; x++) if (isalnum((unsigned char)*x)) t[o++] = (char)toupper((unsigned char)*x);
+ t[o] = 0;
+ LINE(jb_raw(&l, "ADR"); if (t[0]) { jb_raw(&l, ";TYPE="); jb_raw(&l, t); } jb_raw(&l, ":;;"); field(&l, js(it, "street")); jb_raw(&l, ";");
+ field(&l, js(it, "city")); jb_raw(&l, ";"); field(&l, js(it, "region")); jb_raw(&l, ";"); field(&l, js(it, "code")); jb_raw(&l, ";");
+ field(&l, js(it, "country")));
+ }
+ }
+ const char *bd = js(c, "bday");
+ if (strlen(bd) == 10 && bd[4] == '-' && bd[7] == '-' && isdigit((unsigned char)bd[0])) jb_printf(&b, "BDAY;VALUE=date:%.10s\r\n", bd);
+ if (*js(c, "notes")) LINE(jb_raw(&l, "NOTE:"); field(&l, js(c, "notes")));
+ if ((arr = json_get(c, "cats")) && arr->type == J_ARR && arr->kid) {
+ LINE(jb_raw(&l, "CATEGORIES:"); int f = 1; for (const JVal *it = arr->kid; it; it = it->next) if (it->type == J_STR) { if (!f) jb_raw(&l, ","); field(&l, it->str); f = 0; });
+ }
+ if (!strcmp(js(c, "kind"), "group")) {
+ jb_raw(&b, "X-ADDRESSBOOKSERVER-KIND:group\r\n");
+ if ((arr = json_get(c, "members")) && arr->type == J_ARR)
+ for (const JVal *it = arr->kid; it; it = it->next) if (it->type == J_STR) LINE(jb_raw(&l, "X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:"); field(&l, it->str));
+ }
+ if (photo && plen && plen <= VCARD_MAX_PHOTO) {
+ size_t el;
+ char *e = b64_encode(photo, plen, 0, &el);
+ if (e) {
+ char t[16] = "JPEG";
+ if (ptype && !strcasecmp(ptype, "png")) snprintf(t, sizeof t, "PNG");
+ JBuf pl;
+ jb_init(&pl);
+ jb_printf(&pl, "PHOTO;ENCODING=b;TYPE=%s:", t);
+ jb_raw(&pl, e);
+ if (!pl.oom) ic_line(&b, pl.p);
+ jb_free(&pl);
+ free(e);
+ }
+ }
+ time_t now = time(NULL);
+ struct tm tm;
+ gmtime_r(&now, &tm);
+ jb_printf(&b, "REV:%04d%02d%02dT%02d%02d%02dZ\r\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
+ jb_raw(&b, "END:VCARD\r\n");
+#undef LINE
+ if (b.oom) { jb_free(&b); return NULL; }
+ if (olen) *olen = b.n;
+ return b.p;
+}
diff --git a/server/src/mail/vcard.h b/server/src/mail/vcard.h
new file mode 100644
index 0000000..2b646c2
--- /dev/null
+++ b/server/src/mail/vcard.h
@@ -0,0 +1,30 @@
+/* vcard.h — vCard 2.1, 3.0 and 4.0 (RFC 6350) for Contacts in lord-maild.
+ *
+ * Reading goes through the shared content-line parser (ical.h). The JSON a contact becomes:
+ * {"uid","fn","n":{"family","given","middle","prefix","suffix"},"nick","org","dept","title",
+ * "emails":[{"type","value"}],"phones":[…],"addrs":[{"type","street","city","region","code","country"}],
+ * "urls":[…],"im":[…],"bday":"YYYY-MM-DD","notes","cats":[…],"photo":true,"kind":"individual"|"group",
+ * "members":["uid"…],"rev"}
+ * Writing produces vCard 3.0 (what iCloud, Nextcloud and Radicale all accept). */
+#ifndef LORD_MAIL_VCARD_H
+#define LORD_MAIL_VCARD_H
+
+#include <stddef.h>
+#include "../doc/wire.h"
+#include "../sec/json.h"
+
+#define VCARD_MAX_PHOTO (4u << 20)
+
+/* Appends one JSON object per VCARD found in text to b (comma separated, no brackets).
+ * Returns the count, or -1 if the text is not a vCard. */
+int vcard_json(const char *text, size_t len, JBuf *b);
+/* Decoded PHOTO of the first VCARD (base64 or data: URI). malloc; NULL if none. */
+unsigned char *vcard_photo(const char *text, size_t len, size_t *olen);
+/* UID of the first VCARD into out ("" if none). */
+void vcard_uid(const char *text, size_t len, char *out, size_t cap);
+/* vCard 3.0 from a contact JSON object (see above). photo may be NULL. malloc. */
+char *vcard_build(const JVal *c, const unsigned char *photo, size_t photo_len, const char *photo_type, size_t *olen);
+/* Name and e-mail pairs of every VCARD, for Mail's autocomplete: calls fn(name, email). */
+void vcard_emails(const char *text, size_t len, void (*fn)(void *u, const char *name, const char *email), void *u);
+
+#endif
diff --git a/server/src/mail/xml.c b/server/src/mail/xml.c
index 3cb2700..18f7caa 100644
--- a/server/src/mail/xml.c
+++ b/server/src/mail/xml.c
@@ -1,4 +1,4 @@
-/* xml.c — ver xml.h. Un solo recorrido sobre la entrada, sin recursión. */
+/* xml.c — see xml.h. A single pass over the input, without recursion. */
#include "xml.h"
#include <stdint.h>
@@ -7,7 +7,7 @@
typedef struct {
MxNode node;
- char *qname; /* nombre con prefijo, para comparar con la etiqueta de cierre */
+ char *qname; /* prefixed name, to compare against the closing tag */
} Elem;
typedef struct { char *prefix, *uri; int depth; } Bind;
@@ -30,7 +30,7 @@ static int starts(const P *p, const char *lit) {
return p->len - p->i >= n && !memcmp(p->s + p->i, lit, n);
}
-/* busca lit desde i; devuelve la posición o (size_t)-1 */
+/* finds lit starting at i; returns the position or (size_t)-1 */
static size_t find(const P *p, size_t from, const char *lit) {
size_t n = strlen(lit);
if (from > p->len || p->len - from < n) return (size_t)-1;
@@ -46,8 +46,8 @@ static int put_utf8(char *o, uint32_t cp) {
return 4;
}
-/* Copia s[a..b) a out decodificando entidades. out tiene que tener b-a bytes como mínimo (una
- * entidad nunca ocupa más decodificada que escrita). Devuelve el largo o -1 si hay una mala. */
+/* Copies s[a..b) to out, decoding entities. out must hold at least b-a bytes (an entity
+ * never takes more space decoded than encoded). Returns the length or -1 on a bad one. */
static long decode(const char *s, size_t a, size_t b, char *out) {
size_t o = 0;
for (size_t k = a; k < b;) {
@@ -78,7 +78,7 @@ static long decode(const char *s, size_t a, size_t b, char *out) {
if (cp > 0x10ffff) return -1;
}
if (!cp || (cp >= 0xd800 && cp <= 0xdfff)) return -1;
- /* "&#N;" mide ≥ 4 bytes y el UTF-8 de N ocupa ≤ 4: siempre entra */
+ /* "&#N;" is ≥ 4 bytes and the UTF-8 of N takes ≤ 4: it always fits */
o += (size_t)put_utf8(out + o, cp);
} else return -1;
k = e + 1;
@@ -136,129 +136,129 @@ MxNode *mx_parse(const char *s, size_t len, const char **err) {
int depth = 0;
char *tmp = NULL;
#define FAIL(m) do { p.err = (m); goto fail; } while (0)
- if (!s || len > MX_MAX_INPUT) FAIL("entrada");
+ if (!s || len > MX_MAX_INPUT) FAIL("input");
if (len >= 3 && (unsigned char)s[0] == 0xef && (unsigned char)s[1] == 0xbb && (unsigned char)s[2] == 0xbf) p.i = 3;
while (p.i < len) {
if (s[p.i] != '<') {
size_t a = p.i;
while (p.i < len && s[p.i] != '<') p.i++;
if (!cur) {
- for (size_t k = a; k < p.i; k++) if (!is_ws(s[k])) FAIL("texto fuera del elemento");
+ for (size_t k = a; k < p.i; k++) if (!is_ws(s[k])) FAIL("text outside element");
continue;
}
tmp = malloc(p.i - a + 1);
- if (!tmp) FAIL("memoria");
+ if (!tmp) FAIL("memory");
long n = decode(s, a, p.i, tmp);
- if (n < 0) FAIL("entidad");
+ if (n < 0) FAIL("entity");
append_text(cur, tmp, (size_t)n);
free(tmp); tmp = NULL;
continue;
}
if (starts(&p, "<?")) {
size_t e = find(&p, p.i + 2, "?>");
- if (e == (size_t)-1) FAIL("instrucción sin cerrar");
+ if (e == (size_t)-1) FAIL("unclosed instruction");
p.i = e + 2;
continue;
}
if (starts(&p, "<!--")) {
size_t e = find(&p, p.i + 4, "-->");
- if (e == (size_t)-1) FAIL("comentario sin cerrar");
+ if (e == (size_t)-1) FAIL("unclosed comment");
p.i = e + 3;
continue;
}
if (starts(&p, "<![CDATA[")) {
- if (!cur) FAIL("CDATA fuera del elemento");
+ if (!cur) FAIL("CDATA outside element");
size_t e = find(&p, p.i + 9, "]]>");
- if (e == (size_t)-1) FAIL("CDATA sin cerrar");
+ if (e == (size_t)-1) FAIL("unclosed CDATA");
append_text(cur, s + p.i + 9, e - (p.i + 9));
p.i = e + 3;
continue;
}
- if (starts(&p, "<!")) FAIL("DOCTYPE no permitido");
+ if (starts(&p, "<!")) FAIL("DOCTYPE not allowed");
if (starts(&p, "</")) {
p.i += 2;
size_t a = p.i;
while (p.i < len && is_name((unsigned char)s[p.i])) p.i++;
size_t nl = p.i - a;
while (p.i < len && is_ws(s[p.i])) p.i++;
- if (p.i >= len || s[p.i] != '>') FAIL("cierre mal formado");
+ if (p.i >= len || s[p.i] != '>') FAIL("malformed closing tag");
p.i++;
- if (!cur) FAIL("cierre sin apertura");
+ if (!cur) FAIL("closing tag without opening");
const char *q = ((Elem *)cur)->qname;
- if (strlen(q) != nl || memcmp(q, s + a, nl)) FAIL("cierre distinto");
+ if (strlen(q) != nl || memcmp(q, s + a, nl)) FAIL("mismatched closing tag");
pop_binds(&p, depth);
depth--;
cur = cur->parent;
continue;
}
- /* etiqueta de apertura */
+ /* opening tag */
p.i++;
size_t a = p.i;
while (p.i < len && is_name((unsigned char)s[p.i])) p.i++;
size_t ql = p.i - a;
- if (!ql) FAIL("nombre vacío");
- if (cur == NULL && root) FAIL("dos raíces");
- if (depth >= MX_MAX_DEPTH) FAIL("demasiado profundo");
- if (++p.nodes > MX_MAX_NODES) FAIL("demasiados elementos");
+ if (!ql) FAIL("empty name");
+ if (cur == NULL && root) FAIL("two roots");
+ if (depth >= MX_MAX_DEPTH) FAIL("too deep");
+ if (++p.nodes > MX_MAX_NODES) FAIL("too many elements");
size_t qa = a;
int selfclose = 0;
for (;;) {
while (p.i < len && is_ws(s[p.i])) p.i++;
- if (p.i >= len) FAIL("etiqueta sin cerrar");
+ if (p.i >= len) FAIL("unclosed tag");
if (s[p.i] == '>') { p.i++; break; }
if (s[p.i] == '/') {
- if (p.i + 1 >= len || s[p.i + 1] != '>') FAIL("/ suelto");
+ if (p.i + 1 >= len || s[p.i + 1] != '>') FAIL("stray /");
p.i += 2; selfclose = 1; break;
}
size_t an = p.i;
while (p.i < len && is_name((unsigned char)s[p.i])) p.i++;
size_t anl = p.i - an;
- if (!anl) FAIL("atributo");
+ if (!anl) FAIL("attribute");
while (p.i < len && is_ws(s[p.i])) p.i++;
- if (p.i >= len || s[p.i] != '=') FAIL("atributo sin =");
+ if (p.i >= len || s[p.i] != '=') FAIL("attribute without =");
p.i++;
while (p.i < len && is_ws(s[p.i])) p.i++;
- if (p.i >= len || (s[p.i] != '"' && s[p.i] != '\'')) FAIL("valor sin comillas");
+ if (p.i >= len || (s[p.i] != '"' && s[p.i] != '\'')) FAIL("unquoted value");
char qc = s[p.i++];
size_t va = p.i;
- while (p.i < len && s[p.i] != qc) { if (s[p.i] == '<') FAIL("< en un atributo"); p.i++; }
- if (p.i >= len) FAIL("valor sin cerrar");
+ while (p.i < len && s[p.i] != qc) { if (s[p.i] == '<') FAIL("< in an attribute"); p.i++; }
+ if (p.i >= len) FAIL("unclosed value");
size_t vb = p.i++;
int is_def = anl == 5 && !memcmp(s + an, "xmlns", 5);
int is_pre = anl > 6 && !memcmp(s + an, "xmlns:", 6);
if (is_def || is_pre) {
- if (p.nbinds >= MAX_BINDS) FAIL("demasiados espacios de nombres");
+ if (p.nbinds >= MAX_BINDS) FAIL("too many namespaces");
char *uri = malloc(vb - va + 1);
- if (!uri) FAIL("memoria");
+ if (!uri) FAIL("memory");
long ul = decode(s, va, vb, uri);
- if (ul < 0) { free(uri); FAIL("entidad"); }
+ if (ul < 0) { free(uri); FAIL("entity"); }
uri[ul] = 0;
size_t pl = is_def ? 0 : anl - 6;
char *pf = malloc(pl + 1);
- if (!pf) { free(uri); FAIL("memoria"); }
+ if (!pf) { free(uri); FAIL("memory"); }
memcpy(pf, s + an + (is_def ? 0 : 6), pl);
pf[pl] = 0;
p.binds[p.nbinds++] = (Bind){ pf, uri, depth + 1 };
} else {
- /* los demás atributos se validan (entidades) y se descartan: DAV no los usa */
+ /* other attributes are validated (entities) and discarded: DAV does not use them */
tmp = malloc(vb - va + 1);
- if (!tmp) FAIL("memoria");
- if (decode(s, va, vb, tmp) < 0) FAIL("entidad");
+ if (!tmp) FAIL("memory");
+ if (decode(s, va, vb, tmp) < 0) FAIL("entity");
free(tmp); tmp = NULL;
}
}
- /* nombre resuelto */
+ /* resolved name */
const char *colon = memchr(s + qa, ':', ql);
size_t plen = colon ? (size_t)(colon - (s + qa)) : 0;
const char *local = colon ? colon + 1 : s + qa;
size_t ll = ql - (size_t)(local - (s + qa));
- if (!ll) FAIL("nombre local vacío");
+ if (!ll) FAIL("empty local name");
const char *ns = resolve(&p, s + qa, plen, 0);
size_t nsl = strlen(ns);
Elem *e = calloc(1, sizeof *e + nsl + 1 + ll + 1);
- if (!e) FAIL("memoria");
+ if (!e) FAIL("memory");
e->qname = malloc(ql + 1);
- if (!e->qname) { free(e); FAIL("memoria"); }
+ if (!e->qname) { free(e); FAIL("memory"); }
memcpy(e->qname, s + qa, ql);
e->qname[ql] = 0;
char *store = (char *)(e + 1);
@@ -274,7 +274,7 @@ MxNode *mx_parse(const char *s, size_t len, const char **err) {
if (selfclose) pop_binds(&p, depth + 1);
else { cur = n; depth++; }
}
- if (cur || !root) FAIL("documento incompleto");
+ if (cur || !root) FAIL("incomplete document");
pop_binds(&p, 0);
if (err) *err = NULL;
return root;
diff --git a/server/src/mail/xml.h b/server/src/mail/xml.h
index d46407b..2a83611 100644
--- a/server/src/mail/xml.h
+++ b/server/src/mail/xml.h
@@ -1,12 +1,12 @@
-/* xml.h — lector de XML propio para WebDAV (CalDAV y CardDAV) en lord-maild (ver docs/MAIL.md).
+/* xml.h — in-house XML reader for WebDAV (CalDAV and CardDAV) in lord-maild (see docs/MAIL.md).
*
- * Entiende espacios de nombres (xmlns y xmlns:p), así se buscan los elementos por (espacio, nombre)
- * sin importar el prefijo que eligió el servidor ("d:", "D:", ninguno). Es estricto y acotado:
- * - nunca expande entidades declaradas: un <!DOCTYPE es un error (sin «billion laughs» ni
- * entidades externas); solo las cinco predefinidas y las numéricas válidas;
- * - profundidad máxima MX_MAX_DEPTH, MX_MAX_NODES elementos, entrada de hasta MX_MAX_INPUT;
- * - todo índice se verifica contra el largo: nunca lee fuera de la entrada.
- * La prueba (tests/mail_test.c) lo recorre con entradas mutadas al azar. */
+ * Understands namespaces (xmlns and xmlns:p), so elements are looked up by (namespace, name)
+ * regardless of the prefix the server chose ("d:", "D:", none). It is strict and bounded:
+ * - never expands declared entities: a <!DOCTYPE is an error (no "billion laughs" and no
+ * external entities); only the five predefined ones and valid numeric ones;
+ * - maximum depth MX_MAX_DEPTH, MX_MAX_NODES elements, input of up to MX_MAX_INPUT;
+ * - every index is checked against the length: it never reads outside the input.
+ * The test (tests/mail_test.c) exercises it with randomly mutated inputs. */
#ifndef LORD_MAIL_XML_H
#define LORD_MAIL_XML_H
@@ -24,26 +24,26 @@
typedef struct MxNode MxNode;
struct MxNode {
- const char *ns; /* espacio de nombres resuelto ("" si ninguno) */
- const char *name; /* nombre local, sin prefijo */
- char *text; /* texto directo (sin el de los hijos), ya sin entidades */
+ const char *ns; /* resolved namespace ("" if none) */
+ const char *name; /* local name, without prefix */
+ char *text; /* direct text (excluding children's), entities already decoded */
size_t tlen;
MxNode *kid, *last, *next, *parent;
};
-/* Árbol del documento (el elemento raíz) o NULL. err (opcional) recibe un texto corto. */
+/* Document tree (the root element) or NULL. err (optional) receives a short message. */
MxNode *mx_parse(const char *s, size_t len, const char **err);
void mx_free(MxNode *root);
-/* primer hijo directo con ese espacio y nombre (ns NULL = cualquiera) */
+/* first direct child with that namespace and name (ns NULL = any) */
MxNode *mx_child(const MxNode *n, const char *ns, const char *name);
-/* siguiente hermano con ese espacio y nombre */
+/* next sibling with that namespace and name */
MxNode *mx_next(const MxNode *n, const char *ns, const char *name);
-/* primer descendiente (en profundidad, sin recursión) */
+/* first descendant (depth-first, without recursion) */
MxNode *mx_find(const MxNode *n, const char *ns, const char *name);
-const char *mx_text(const MxNode *n); /* "" si no hay */
-/* texto de un hijo (ns, name), sin espacios a los costados, en out; "" si no está */
+const char *mx_text(const MxNode *n); /* "" if none */
+/* text of a child (ns, name), trimmed, into out; "" if absent */
void mx_child_text(const MxNode *n, const char *ns, const char *name, char *out, size_t cap);
-/* Escapa texto para meterlo en XML (&, <, >, "). Devuelve bytes escritos (sin el 0). */
+/* Escapes text for embedding in XML (&, <, >, "). Returns bytes written (excluding the NUL). */
size_t mx_escape(char *out, size_t cap, const char *s);
#endif
diff --git a/server/src/main.c b/server/src/main.c
index b1cf218..a40776d 100644
--- a/server/src/main.c
+++ b/server/src/main.c
@@ -43,6 +43,7 @@
#include "ui/js_wm.h"
#include "ui/portal.h"
#include "ui/js_logs.h"
+#include "hw/hw.h"
#include <errno.h>
#include <fcntl.h>
@@ -258,6 +259,7 @@ static void dispatch_pointer(Server *s) {
static Server *remote_server;
static void remote_settle(Server *s) {
+ display_activity(now_ms()); /* idle timers (Settings → Battery) */
if (s->cx < 0) s->cx = 0;
if (s->cy < 0) s->cy = 0;
if (s->cx >= s->W) s->cx = s->W - 1;
@@ -365,12 +367,16 @@ static void display_attach(const int *fds, int n) {
}
if (input_open_fds(&s->input, fds + 1, n - 1)) fprintf(stderr, "monitor: sin teclado ni mouse\n");
wl_input_devices_changed(); /* ¿hay pantalla táctil? (wl_seat touch) */
- set_size(s, (int)s->kms.width & ~1, (int)s->kms.height & ~1);
+ {
+ int lw, lh; /* rotated by Settings → Displays: the logical size */
+ display_logical_size((int)s->kms.width, (int)s->kms.height, &lw, &lh);
+ set_size(s, lw & ~1, lh & ~1);
+ }
s->headless = 0;
s->gpu_paused = 0;
struct stat st;
if (fstat(s->kms.fd, &st) == 0) wl_set_drm_device(st.st_rdev);
- if (mirror_clients() || media_needs_cpu() || gpu_start(s)) s->gpu_paused = mirror_clients() > 0 || media_needs_cpu();
+ if (display_rotation() || mirror_clients() || media_needs_cpu() || gpu_start(s)) s->gpu_paused = mirror_clients() > 0 || media_needs_cpu();
/* el puntero donde está (una tablet absoluta no avisa si no se mueve) o en el medio */
s->cx = s->W / 2;
s->cy = s->H / 2;
@@ -388,6 +394,7 @@ static void display_attach(const int *fds, int n) {
damage_add((Box){ 0, 0, (float)s->W, (float)s->H });
ui.dirty = 1;
fprintf(stderr, "monitor: la sesión se muestra (%dx%d, %s)\n", s->W, s->H, gpu_active() ? "GPU" : "CPU");
+ display_attached(); /* Night Shift, idle timers, the list in Settings */
}
static void display_detach(void) {
@@ -403,6 +410,7 @@ static void display_detach(void) {
s->hw_cursor = 0;
s->gpu_paused = 0;
s->headless = 1;
+ display_detached();
if (!s->frame) s->frame = calloc((size_t)s->W * s->H, 4);
damage_add((Box){ 0, 0, (float)s->W, (float)s->H });
ui.dirty = 1;
@@ -411,6 +419,7 @@ static void display_detach(void) {
static void on_input(void *ud, const InputDevice *d, const struct input_event *ev) {
Server *s = ud;
+ if (ev->type == EV_KEY || ev->type == EV_REL || ev->type == EV_ABS) display_activity(now_ms());
if (s->debug && ev->type != EV_SYN)
fprintf(stderr, "ev %s type=%u code=%u value=%d\n", d->name, ev->type, ev->code, ev->value);
if (d->tp) { /* touchpad o pantalla táctil: driver propio (tp/tp.c) */
@@ -432,6 +441,18 @@ static void on_input(void *ud, const InputDevice *d, const struct input_event *e
const struct input_absinfo *a = ev->code == ABS_X ? &d->ax : ev->code == ABS_Y ? &d->ay : NULL;
int range = a ? a->maximum - a->minimum : 0;
if (range <= 0) break;
+ if (display_rotation()) {
+ /* rotated screen: the tablet reports physical positions; both axes can change */
+ static double nx, ny;
+ if (ev->code == ABS_X) nx = (double)(ev->value - a->minimum) / range; else ny = (double)(ev->value - a->minimum) / range;
+ double lx, ly;
+ display_unrotate_point(nx, ny, &lx, &ly);
+ int x = (int)(lx * (s->W - 1)), y = (int)(ly * (s->H - 1));
+ s->rdx += x - s->lx; s->rdy += y - s->ly;
+ s->cx = x; s->cy = y;
+ s->moved = 1;
+ break;
+ }
int v = (int)((long)(ev->value - a->minimum) * (ev->code == ABS_X ? s->W - 1 : s->H - 1) / range);
if (ev->code == ABS_X) { s->rdx += v - s->lx; s->cx = v; } else { s->rdy += v - s->ly; s->cy = v; }
s->moved = 1;
@@ -687,15 +708,21 @@ static void render_frame(Server *s) {
}
} else {
KmsBuffer *b = kms_back(&s->kms);
- Canvas out;
- canvas_init(&out, b->map, s->W, s->H, (int)(b->pitch / 4));
+ Canvas out, phys;
+ /* rotated (Settings → Displays): the frame is composed upright in s->frame and copied
+ * rotated into the card's buffer; otherwise straight into the buffer */
+ int rot = display_rotation();
+ canvas_init(&phys, b->map, rot ? (int)s->kms.width : s->W, rot ? (int)s->kms.height : s->H, (int)(b->pitch / 4));
+ if (rot) canvas_init(&out, s->frame, s->W, s->H, s->W);
+ else out = phys;
int bi = s->kms.front ^ 1, fs = wl_fullscreen_active();
if (fs != s->was_fs) { s->was_fs = fs; s->full_copy = 2; }
+ Rect need = { 0, 0, s->W, s->H }; /* what this buffer gets now (also tinted) */
if (s->full_copy > 0 || fs) {
canvas_copy(&out, &s->scene);
if (s->full_copy > 0) s->full_copy--;
} else {
- Rect need = rect_join(rect_join(s->stale[bi], r), s->curs[bi]);
+ need = rect_join(rect_join(s->stale[bi], r), s->curs[bi]);
if (need.x0 < 0) need.x0 = 0;
if (need.y0 < 0) need.y0 = 0;
if (need.x1 > s->W) need.x1 = s->W;
@@ -718,9 +745,35 @@ static void render_frame(Server *s) {
mirror_frame(seen->px, seen->stride, s->W, s->H);
mirror_cursor(s->cx, s->cy, mode, px, w, h, hx, hy, gen);
cursor_local(s, &k); /* la flecha también es una imagen (cursor.c) */
- if (k.mode == 1) {
- canvas_blit(&out, k.px, k.w, k.h, s->cx - k.hx, s->cy - k.hy, 0, 1, 0);
- s->curs[bi] = (Rect){ s->cx - k.hx, s->cy - k.hy, s->cx - k.hx + k.w, s->cy - k.hy + k.h };
+ Rect cr = { s->cx - k.hx, s->cy - k.hy, s->cx - k.hx + k.w, s->cy - k.hy + k.h };
+ if (!rot) {
+ display_tint(&out, need); /* Night Shift without a gamma LUT (software) */
+ if (k.mode == 1) {
+ canvas_blit(&out, k.px, k.w, k.h, s->cx - k.hx, s->cy - k.hy, 0, 1, 0);
+ s->curs[bi] = cr;
+ }
+ } else {
+ if (need.x1 > need.x0 && need.y1 > need.y0) {
+ display_rotate_copy(&out, need, &phys, rot);
+ display_tint(&phys, display_rotate_rect(need, s->W, s->H, rot));
+ }
+ /* the cursor is composited apart (s->frame stays clean) and copied rotated */
+ static uint32_t tmp[128 * 128];
+ Rect cc = cr;
+ if (cc.x0 < 0) cc.x0 = 0;
+ if (cc.y0 < 0) cc.y0 = 0;
+ if (cc.x1 > s->W) cc.x1 = s->W;
+ if (cc.y1 > s->H) cc.y1 = s->H;
+ int cw = cc.x1 - cc.x0, ch = cc.y1 - cc.y0;
+ if (k.mode == 1 && cw > 0 && ch > 0 && cw <= 128 && ch <= 128) {
+ for (int y = 0; y < ch; y++) memcpy(tmp + (size_t)y * cw, out.px + (size_t)(cc.y0 + y) * out.stride + cc.x0, (size_t)cw * 4);
+ Canvas t;
+ canvas_init(&t, tmp, cw, ch, cw);
+ canvas_blit(&t, k.px, k.w, k.h, cr.x0 - cc.x0, cr.y0 - cc.y0, 0, 1, 0);
+ display_rotate_copy_at(tmp, cw, cc.x0, cc.y0, cc, s->W, s->H, &phys, rot);
+ display_tint(&phys, display_rotate_rect(cc, s->W, s->H, rot));
+ s->curs[bi] = cc;
+ }
}
kms_flip(&s->kms);
}
@@ -747,6 +800,39 @@ static void switch_theme(const char *current) {
}
}
+/* ---- Settings → Displays and the other hardware pages (src/hw, docs/SETTINGS.md) ---- */
+
+static Server *hw_server;
+static Kms *hw_kms(void) { Server *s = hw_server; return s && !s->headless && s->kms.fd >= 0 ? &s->kms : NULL; }
+static void hw_redraw(void) {
+ Server *s = hw_server;
+ if (!s) return;
+ s->full_copy = 2;
+ damage_add((Box){ 0, 0, (float)s->W, (float)s->H });
+ ui.dirty = 1;
+}
+static const DisplayHost hw_host = { hw_kms, hw_redraw, js_hw_event };
+
+/* A modeset queued by Settings, run between frames: the GPU path stops (its surfaces have the old
+ * size), kms.c changes the mode, the session takes the new (logical) size and the GPU comes back.
+ * A rotated screen stays on the CPU path (the rotation is done while copying the frame). */
+static int gpu_was_on = 1; /* try the GPU again after a modeset (fails quietly without one) */
+static void run_modeset(Server *s, uint32_t conn, const struct drm_mode_modeinfo *m) {
+ if (gpu_active()) { gpu_was_on = 1; gpu_tex_free(s->cursor_tex); s->cursor_tex = NULL; gpu_shutdown(); }
+ kms_cursor_show(&s->kms, 0);
+ s->hw_cursor = 0;
+ int ok = kms_modeset(&s->kms, conn, m) == 0;
+ int lw, lh;
+ display_logical_size((int)s->kms.width, (int)s->kms.height, &lw, &lh);
+ set_size(s, lw & ~1, lh & ~1);
+ memset(s->stale, 0, sizeof s->stale);
+ memset(s->curs, 0, sizeof s->curs);
+ s->full_copy = 2;
+ if (gpu_was_on && !display_rotation() && !mirror_clients() && !media_needs_cpu() && gpu_start(s) == 0) gpu_was_on = 0;
+ display_modeset_done(ok);
+ hw_redraw();
+}
+
static void usage(const char *argv0) {
fprintf(stderr, "uso: %s [--theme bundle.js] [--fonts dir] [--shell dir] [--user nombre] [--card /dev/dri/cardN]\n"
" [--headless ANCHOxALTO [--greeter]] [--timeout s] [--debug] [--profile]\n", argv0);
@@ -808,6 +894,7 @@ int main(int argc, char **argv) {
else {
char picked[64];
if (!card) { drm_pick_card(picked, sizeof picked); card = picked; }
+ kms_set_picker(display_pick); /* the display saved in Settings (displays.json) */
if (kms_open(&s.kms, card)) return 1;
s.W = (int)s.kms.width;
s.H = (int)s.kms.height;
@@ -830,9 +917,9 @@ int main(int argc, char **argv) {
* pantalla de ingreso no tiene: lo que necesita root lo hace lord-sessiond. */
const char *session_user = s.greeter ? NULL : user ? user : getenv("SUDO_USER");
if (session_user && admin_start(session_user)) fprintf(stderr, "lord-server: sin ayudante de administración\n");
- /* red de LordOS: con lord-sessiond la red es del sistema (lord-netd la levanta al arrancar el
- * equipo) y net-restore solo confirma; sin él (lord-server suelto) la levanta el ayudante de
- * esta sesión (ver net_act_restore y docs/RED.md) */
+ /* LordOS networking: with lord-sessiond the network belongs to the system (lord-netd brings it
+ * up at boot) and net-restore only confirms; without it (a standalone lord-server) this
+ * session's helper brings it up (see net_act_restore and docs/RED.md) */
else if (session_user) admin_send("net-restore", "", 0);
int ok = drop_privileges(user) == 0;
if (ok && s.headless && getenv("HOME")) {
@@ -847,14 +934,18 @@ int main(int argc, char **argv) {
setvbuf(stderr, NULL, _IOLBF, 0);
}
/* GPU (Mesa) después de soltar root: si no hay una usable, sigue el camino por CPU */
- if (ok && !s.headless) gpu_start(&s);
+ /* Settings' hardware pages: displays, uevents, Bluetooth, power profiles (src/hw) */
+ kms_set_picker(display_pick);
+ hw_server = &s;
+ if (ok && !s.greeter) hw_start(&hw_host, 1);
+ if (ok && !s.headless && !display_rotation()) gpu_start(&s);
{
struct stat st;
if (s.kms.fd >= 0 && fstat(s.kms.fd, &st) == 0) wl_set_drm_device(st.st_rdev);
}
if (ok && wl_start()) fprintf(stderr, "lord-server: sin Wayland (las apps Linux no van a poder abrirse)\n");
if (ok && net_open()) fprintf(stderr, "lord-server: sin avisos de red (rtnetlink)\n");
- /* Copias de seguridad: un hilo como el usuario, nice 19 y E/S idle (backup/backup.c) */
+ /* Backups: a thread running as the user, nice 19 and idle I/O (backup/backup.c) */
if (ok && !s.greeter && getenv("HOME") && session_user) backup_start(getenv("HOME"), session_user);
if (ok && snd_start()) fprintf(stderr, "lord-server: sin PipeWire por ahora (sonido); se reintenta solo\n");
if (ok && !s.greeter) portal_start(); /* modo oscuro, acento y botones para GTK/GNOME/Qt (ui/portal.c) */
@@ -914,10 +1005,19 @@ int main(int argc, char **argv) {
double td = term_timeout(now);
if (td >= 0 && (delay < 0 || td < delay)) delay = td;
tp_tick(now); /* touchpad: tocar, arrastrar, inercia (tp/tp.c) */
+ display_tick(now_ms()); /* screen off, lock and sleep after N minutes (src/hw) */
+ double hwd = display_timeout(now_ms());
+ if (hwd >= 0 && (delay < 0 || hwd < delay)) delay = hwd;
+ if (!s.kms.flip_pending) { /* a resolution/output chosen in Settings → Displays */
+ uint32_t mconn;
+ struct drm_mode_modeinfo mmode;
+ if (display_take_modeset(&mconn, &mmode)) run_modeset(&s, mconn, &mmode);
+ }
double tpd = tp_timeout(now_ms());
if (tpd >= 0 && (delay < 0 || tpd < delay)) delay = tpd;
/* sin monitor y sin nadie mirando no se dibuja (al conectarse alguien llega un cuadro entero) */
int unseen = s.headless && !mirror_clients() && !media_needs_cpu(); /* grabando la pantalla, sí */
+ if (!s.headless && display_is_off()) unseen = 1; /* screen off after idle (DPMS): nothing to draw */
int wants = !unseen && (ui.dirty || s.cursor_dirty || js_wants_frame() || wl_wants_frame() || media_wants_frame());
/* sin monitor no hay vblank: a lo sumo 60 cuadros por segundo */
double pace = s.headless ? s.last_render + 16.6 - now_ms() : 0;
@@ -948,7 +1048,7 @@ int main(int argc, char **argv) {
if (wbase >= 0) pfd[n++] = (struct pollfd){ wl_fd(), POLLIN, 0 };
int nbase = net_fd() >= 0 ? n : -1;
if (nbase >= 0) pfd[n++] = (struct pollfd){ net_fd(), POLLIN, 0 };
- int dkbase = disk_watch_fd() >= 0 ? n : -1; /* app Discos abierta: montajes y udev */
+ int dkbase = disk_watch_fd() >= 0 ? n : -1; /* Disks app open: mounts and udev */
if (dkbase >= 0) pfd[n++] = (struct pollfd){ disk_watch_fd(), POLLIN, 0 };
int bkbase = backup_fd() >= 0 ? n : -1;
if (bkbase >= 0) pfd[n++] = (struct pollfd){ backup_fd(), POLLIN, 0 };
@@ -966,6 +1066,8 @@ int main(int argc, char **argv) {
n += nabr;
int medbase = n, nmed = media_pollfds(pfd + n, 40); /* ayudantes lord-media y sus streams de PipeWire */
n += nmed;
+ int hwbase = n, nhw = hw_pollfds(pfd + n, 4); /* uevents and the system bus (src/hw) */
+ n += nhw;
if (poll(pfd, n, wait) < 0 && errno != EINTR) { perror("poll"); break; }
if (pfd[0].revents & POLLIN) {
int was = s.kms.flip_pending;
@@ -984,7 +1086,7 @@ int main(int argc, char **argv) {
for (int k = nlost - 1; k >= 0; k--) input_remove(&s.input, lost[k]);
if (nlost) wl_input_devices_changed();
/* la GPU vuelve cuando ya nadie mira desde la red */
- if (s.gpu_paused && !s.headless && !mirror_clients() && !media_needs_cpu() && !s.kms.flip_pending) {
+ if (s.gpu_paused && !s.headless && !mirror_clients() && !media_needs_cpu() && !s.kms.flip_pending && !display_rotation()) {
s.gpu_paused = 0;
gpu_start(&s);
}
@@ -1002,6 +1104,8 @@ int main(int argc, char **argv) {
if (nbrk) brokersrv_dispatch(pfd + brkbase, nbrk);
if (nabr) brokersrv_audio_dispatch(pfd + abr, nabr);
if (nmed) media_dispatch(pfd + medbase, nmed);
+ if (nhw) hw_dispatch(pfd + hwbase, nhw);
+ hw_events();
media_events(js_media_event);
brokersrv_events(js_broker_event); /* avisos de permiso e indicadores → tema */
brokersrv_tick(); /* teclado y reintentos hacia las apps aisladas */
diff --git a/server/src/media/media.c b/server/src/media/media.c
index 8077714..7224f42 100644
--- a/server/src/media/media.c
+++ b/server/src/media/media.c
@@ -380,6 +380,7 @@ static uint8_t *map_sealed(int fd, size_t need) {
static void on_src_msg(MediaSrc *s, const MediaMsg *m, int *fds) {
char esc[MP_PAYLOAD_MAX * 2 + 16];
+ if (s->bk_msg && s->bk_msg(s, m, payload, fds)) return; /* camera of an isolated app (brokercam.c) */
switch (m->type) {
case MM_INFO:
if (m->len && payload[0] == '{') media_event(s->id, "info", "%s", payload);
diff --git a/server/src/media/media_int.h b/server/src/media/media_int.h
index 6f4a857..6d8b0f5 100644
--- a/server/src/media/media_int.h
+++ b/server/src/media/media_int.h
@@ -68,6 +68,10 @@ typedef struct {
int job; /* imagen: trabajo que la decodifica */
MAudio *audio; /* reproductor: el stream de PipeWire (de lord-server) */
MAudio *mic; /* grabaciones: el micrófono (de lord-server, con permiso) */
+ /* camera of an isolated app (sec/brokercam.c): its helper's messages go to the app over the
+ * broker instead of the session; bk_msg returns 1 when it consumed the message */
+ void *bk;
+ int (*bk_msg)(void *src, const MediaMsg *m, const char *payload, int *fds);
} MediaSrc;
/* media.c */
diff --git a/server/src/net/actions.c b/server/src/net/actions.c
index 799b04b..6aac1d7 100644
--- a/server/src/net/actions.c
+++ b/server/src/net/actions.c
@@ -2,8 +2,8 @@
* argumento acá; ninguna pasa texto del usuario a un shell ni como argumentos libres.
*
* net-restore al arrancar: aplica las configs de /etc/lordos/net/if y levanta DHCP
- * (y Wi-Fi) en las interfaces libres. Con lord-netd lo corre él solo,
- * al arrancar el equipo ("system"); ver admin.c
+ * (y Wi-Fi) en las interfaces libres. With lord-netd it runs it itself
+ * at boot ("system"); see admin.c
* net-up / net-down <if>
* net-config <if>\n<líneas> method=dhcp|static|off, address=ip/prefijo (varias),
* gateway=ip, dns=ip (varias)
@@ -147,10 +147,10 @@ static char *load_if_conf(const char *ifname) {
void net_act_restore(const AdminReq *r, const char *arg, size_t len) {
(void)r;
mkdir(NET_RUN_DIR, 0755);
- /* Normalmente la red es del sistema: la levanta lord-netd al arrancar el equipo (arg "system",
- * ver admin.c) y el net-restore de las sesiones ni llega acá. Sin lord-netd (lord-server suelto,
- * en desarrollo) la levanta el ayudante de la sesión; si hubiera varias, solo la primera (su pid
- * en net-owner, mientras viva), así dos no arrancan dos DHCP en la misma placa. */
+ /* Normally the network belongs to the system: lord-netd brings it up at boot (arg "system", see
+ * admin.c) and the sessions' net-restore never gets here. Without lord-netd (a standalone
+ * lord-server, in development) the session's helper brings it up; with several, only the first
+ * (its pid in net-owner, while alive), so two don't start two DHCP clients on the same NIC. */
if (!(len == 6 && !strcmp(arg, "system"))) {
char *o = read_file(NET_RUN_DIR "/net-owner", 32, NULL);
if (o) {
diff --git a/server/src/net/dhcp.c b/server/src/net/dhcp.c
index aaf283a..5c3f1be 100644
--- a/server/src/net/dhcp.c
+++ b/server/src/net/dhcp.c
@@ -3,10 +3,10 @@
* con netlink, renueva en T1 (unicast al servidor) y re-pide en T2 (broadcast); si vence la
* concesión o llega un NAK, vuelve a empezar. Sigue el enlace: sin portadora espera, y al
* volver confirma la misma dirección (INIT-REBOOT). En Wi-Fi además traduce los avisos de
- * wpa_supplicant (conectado/desconectado) a EVENTs. SIGTERM: DHCPRELEASE y limpia. Si muere el
- * proceso que lo lanzó (lord-netd, que lord-sessiond vuelve a lanzar enseguida) recibe SIGUSR1:
- * deja la dirección puesta y la concesión en /run/lordos/dhcp/<if>.lease, y el cliente nuevo la
- * confirma (INIT-REBOOT) sin cortar las conexiones.
+ * wpa_supplicant (conectado/desconectado) a EVENTs. SIGTERM: DHCPRELEASE y limpia. If the process that
+ * started it dies (lord-netd, which lord-sessiond restarts right away) it gets SIGUSR1: it keeps
+ * the address and leaves the lease in /run/lordos/dhcp/<if>.lease, and the new client confirms it
+ * (INIT-REBOOT) without dropping connections.
*
* Envía y recibe por un socket AF_PACKET (no hace falta tener IP todavía); un socket UDP en
* el puerto 68 atado a la interfaz evita que el kernel conteste "puerto inalcanzable" y sirve
@@ -286,7 +286,7 @@ static void enter(Dhcp *d, int st) {
if (st == S_REBOOTING) d->deadline = now_s() + 10;
}
-/* ---- la concesión guardada (para que un lord-netd nuevo la retome) ---- */
+/* ---- the saved lease (so a new lord-netd can resume it) ---- */
#define LEASE_DIR NET_RUN_DIR "/dhcp"
#define LEASE_MAGIC 0x4c444c31u /* "LDL1" */
@@ -309,7 +309,7 @@ static void lease_save(const Dhcp *d) {
static void lease_forget(const Dhcp *d) { char p[96]; lease_path(d, p, sizeof p); unlink(p); }
-/* La de un cliente anterior en esta misma interfaz, si todavía vale. */
+/* The lease of an earlier client on this same interface, if still valid. */
static void lease_load(Dhcp *d) {
char p[96];
lease_path(d, p, sizeof p);
@@ -394,7 +394,7 @@ void dhcp_run(const char *ifname, int wifi) {
sigaction(SIGINT, &sa, NULL);
struct sigaction sk = { .sa_handler = on_parent_gone };
sigaction(SIGUSR1, &sk, NULL);
- prctl(PR_SET_PDEATHSIG, SIGUSR1); /* muere lord-netd: se va sin soltar la dirección */
+ prctl(PR_SET_PDEATHSIG, SIGUSR1); /* lord-netd dies: exit without releasing the address */
d.ifindex = rt_ifindex(ifname);
gethostname(d.host, sizeof d.host - 1);
for (char *p = d.host; *p; p++) if (*p == '.') { *p = 0; break; }
@@ -474,7 +474,7 @@ void dhcp_run(const char *ifname, int wifi) {
}
}
}
- if (keep_flag) { /* lo retoma el próximo lord-netd */
+ if (keep_flag) { /* the next lord-netd resumes it */
if (d.lease.addr && d.state == S_BOUND) lease_save(&d);
_exit(0);
}
diff --git a/server/src/net/netd.c b/server/src/net/netd.c
index b740e78..01e1acb 100644
--- a/server/src/net/netd.c
+++ b/server/src/net/netd.c
@@ -1,14 +1,14 @@
-/* netd.c — lord-netd: la red de LordOS es del sistema, no de una sesión (docs/RED.md, «La red es
- * del sistema»).
+/* netd.c — lord-netd: LordOS networking belongs to the system, not to a session (docs/RED.md,
+ * "The network belongs to the system").
*
- * Lo lanza lord-sessiond al arrancar (ruta fija, al lado de su binario, de root y no escribible
- * por otros), sin argumentos, y lo vuelve a lanzar si termina. Levanta la red antes de que alguien
- * entre (DHCP, Wi-Fi guardadas, configs de /etc/lordos/net/if, DNS), así la pantalla de ingreso
- * muestra la IP y el escritorio remoto se alcanza; y la mantiene aunque las sesiones entren y
- * salgan. Es el mismo admin.c compilado con LORD_NETD: su tabla tiene solo las acciones net-*
- * (las mismas validaciones), y las atiende por /run/lordos/netd.sock, un socket 0600 al que solo
- * se conectan los ayudantes root de las sesiones. No ejecuta nada fuera de lo que ya ejecutan
- * esas acciones (wpa_supplicant, openvpn, charon, pppd, resolvectl, networkctl… con ruta fija). */
+ * lord-sessiond starts it at boot (fixed path next to its own binary, root-owned and not writable
+ * by others), with no arguments, and restarts it if it exits. It brings the network up before
+ * anyone logs in (DHCP, saved Wi-Fi, /etc/lordos/net/if configs, DNS), so the greeter shows the IP
+ * and the remote desktop is reachable, and keeps it up while sessions come and go. It is admin.c
+ * built with LORD_NETD: its table has only the net-* actions (same validation), served on
+ * /run/lordos/netd.sock, a 0600 socket that only the sessions' root helpers connect to. It runs
+ * nothing beyond what those actions already run (wpa_supplicant, openvpn, charon, pppd, resolvectl,
+ * networkctl… at fixed paths). */
#include "../admin.h"
#include <stdio.h>
@@ -17,8 +17,8 @@
int main(int argc, char **argv) {
(void)argv;
- if (argc != 1) { fprintf(stderr, "uso: lord-netd (sin argumentos; lo lanza lord-sessiond)\n"); return 2; }
- if (geteuid() != 0) { fprintf(stderr, "lord-netd: tiene que correr como root\n"); return 1; }
+ if (argc != 1) { fprintf(stderr, "usage: lord-netd (no arguments; started by lord-sessiond)\n"); return 2; }
+ if (geteuid() != 0) { fprintf(stderr, "lord-netd: must run as root\n"); return 1; }
setvbuf(stderr, NULL, _IOLBF, 0);
return admin_netd_serve();
}
diff --git a/server/src/remote/cgsup.c b/server/src/remote/cgsup.c
new file mode 100644
index 0000000..688b5ab
--- /dev/null
+++ b/server/src/remote/cgsup.c
@@ -0,0 +1,74 @@
+/* cgsup.c — lord-sessiond's cgroup placement service (see sec/cgroup.h, docs/PRIVACIDAD.md).
+ *
+ * A small root child of lord-sessiond listens on /run/lordos/cgroup.sock. lord-server (and the
+ * children it forks right before exec: Linux apps, .lpk apps, lord-media, lord-doc…) ask it to be
+ * placed into their app scope. The scopes and their cgroup.procs are root-owned, so a process of
+ * the user can never move itself out of its scope. The child runs serially with short timeouts
+ * and dies with its parent (PR_SET_PDEATHSIG): a lord-sessiond restart starts a fresh one. */
+#include "sessiond.h"
+#include "../sec/cgroup.h"
+
+#include <errno.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+static pid_t cg_pid = -1;
+static double cg_restart_at;
+
+static void serve(void) {
+ syscall(SYS_close_range, 3, ~0u, 0); /* no monitor fds, no worker sockets */
+ prctl(PR_SET_PDEATHSIG, SIGTERM);
+ signal(SIGTERM, SIG_DFL);
+ signal(SIGHUP, SIG_DFL);
+ if (getppid() == 1) _exit(0);
+ char bindir[512];
+ snprintf(bindir, sizeof bindir, "%s", rd_conf.server);
+ char *slash = strrchr(bindir, '/');
+ if (!slash) _exit(1);
+ *slash = 0;
+ char real[PATH_MAX];
+ if (realpath(bindir, real) && strlen(real) < sizeof bindir) memcpy(bindir, real, strlen(real) + 1);
+ int lfd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
+ struct sockaddr_un a = { .sun_family = AF_UNIX };
+ snprintf(a.sun_path, sizeof a.sun_path, "%s", CGROUP_SOCK);
+ unlink(CGROUP_SOCK);
+ mode_t old = umask(0);
+ int ok = lfd >= 0 && !bind(lfd, (struct sockaddr *)&a, sizeof a) && !listen(lfd, 32);
+ umask(old);
+ if (!ok) { sd_log("cgroup: no se pudo escuchar en %s: %s", CGROUP_SOCK, strerror(errno)); _exit(1); }
+ chmod(CGROUP_SOCK, 0666); /* anyone may ask; SO_PEERCRED decides */
+ sd_log("cgroup: scopes de root (servicio en %s, binarios de %s)", CGROUP_SOCK, bindir);
+ for (;;) {
+ int c = accept4(lfd, NULL, NULL, SOCK_CLOEXEC);
+ if (c < 0) { if (errno == EINTR) continue; _exit(1); }
+ cgroup_place_serve(c, bindir, rd_conf.insecure_dev);
+ close(c);
+ }
+}
+
+void sd_cgroup_start(void) {
+ pid_t p = fork();
+ if (p == 0) { serve(); _exit(0); }
+ cg_pid = p;
+}
+
+int sd_cgroup_reaped(pid_t pid, int status) {
+ (void)status;
+ if (pid != cg_pid) return 0;
+ cg_pid = -1;
+ cg_restart_at = rd_now() + 1;
+ return 1;
+}
+
+void sd_cgroup_tick(void) {
+ if (cg_pid < 0 && cg_restart_at > 0 && rd_now() >= cg_restart_at) { cg_restart_at = 0; sd_cgroup_start(); }
+}
diff --git a/server/src/remote/netsup.c b/server/src/remote/netsup.c
index 794f5db..879aa78 100644
--- a/server/src/remote/netsup.c
+++ b/server/src/remote/netsup.c
@@ -1,15 +1,15 @@
-/* netsup.c — lord-sessiond vigila a lord-netd, la red del sistema (docs/RED.md, «La red es del
- * sistema»; el proceso en sí está en admin.c con LORD_NETD y net/netd.c).
+/* netsup.c — lord-sessiond supervises lord-netd, the system network (docs/RED.md, "The network
+ * belongs to the system"; the process itself is admin.c built with LORD_NETD plus net/netd.c).
*
- * - Lo lanza al arrancar, antes que la pantalla de ingreso: así hay red (y la IP) antes de que
- * alguien entre, y el escritorio remoto se alcanza.
- * - Ruta fija: <carpeta de lord-sessiond>/lord-netd, de root y no escribible por otros (salvo
- * insecure_dev, como lord-server). Sin argumentos y con un entorno mínimo.
- * - Si termina, lo vuelve a lanzar con una espera creciente (1, 2, 4… hasta 30 s).
- * - Un reinicio de lord-sessiond (KillMode=process) no corta la red: lord-netd sigue vivo y el
- * lord-sessiond nuevo lo adopta (pidfd sobre el pid de /run/lordos/netd.pid), sin sondear.
- * - Deja /run/lordos/netd.enabled: con esa marca, los ayudantes de las sesiones nunca levantan
- * la red por su cuenta (si lord-netd se está reiniciando, la acción responde un error). */
+ * - Started at boot, before the greeter, so there is a network (and an IP) before anyone logs
+ * in, and the remote desktop is reachable.
+ * - Fixed path: <lord-sessiond's directory>/lord-netd, root-owned and not writable by others
+ * (unless insecure_dev, as for lord-server). No arguments and a minimal environment.
+ * - If it exits, it is started again with a growing delay (1, 2, 4… up to 30 s).
+ * - Restarting lord-sessiond (KillMode=process) doesn't cut the network: lord-netd keeps running
+ * and the new lord-sessiond adopts it (a pidfd on the pid in /run/lordos/netd.pid), no polling.
+ * - Leaves /run/lordos/netd.enabled: with that mark, the sessions' helpers never bring the
+ * network up themselves (while lord-netd restarts, the action answers with an error). */
#include "sessiond.h"
#include <errno.h>
@@ -27,11 +27,11 @@
#define NETD_PIDFILE SD_RUN_DIR "/netd.pid"
#define NETD_MARK SD_RUN_DIR "/netd.enabled"
-static pid_t child = -1; /* lord-netd hijo nuestro */
-static int pidfd = -1; /* uno adoptado (de un lord-sessiond anterior) */
-static double next_try; /* cuándo volver a lanzarlo */
+static pid_t child = -1; /* lord-netd as our child */
+static int pidfd = -1; /* an adopted one (from an earlier lord-sessiond) */
+static double next_try; /* when to start it again */
static int fails;
-static double started; /* cuándo se lanzó o adoptó (si duró, la espera vuelve a 1 s) */
+static double started; /* when it was started or adopted (if it lasted, the delay goes back to 1 s) */
static char path[PATH_MAX];
static void netd_path(void) {
@@ -41,14 +41,14 @@ static void netd_path(void) {
if (slash) snprintf(slash + 1, sizeof path - (size_t)(slash + 1 - path), "lord-netd");
}
-/* ¿Sigue vivo un lord-netd de antes (de un lord-sessiond anterior)? */
+/* Is a lord-netd from an earlier lord-sessiond still alive? */
static int adopt(void) {
FILE *f = fopen(NETD_PIDFILE, "r");
int p = 0;
if (f) { if (fscanf(f, "%d", &p) != 1) p = 0; fclose(f); }
if (p <= 1) return -1;
- /* el pidfile es de root; el proceso tiene que ser de root y llamarse lord-netd (prctl). No se
- * compara /proc/<pid>/exe: si el binario se actualizó mientras corría, apunta a otro nombre */
+ /* the pidfile is root's; the process must be root's and named lord-netd (prctl). /proc/<pid>/exe
+ * is not compared: if the binary was updated while running, it points to another name */
char proc[64], comm[32] = "";
struct stat st;
snprintf(proc, sizeof proc, "/proc/%d", p);
@@ -65,7 +65,7 @@ static int adopt(void) {
fcntl(fd, F_SETFD, FD_CLOEXEC);
pidfd = fd;
started = rd_now();
- sd_log("lord-netd sigue corriendo (pid %d): la red no se cortó", p);
+ sd_log("lord-netd still running (pid %d): the network was not interrupted", p);
return 0;
}
@@ -73,9 +73,9 @@ void sd_netd_start(void) {
netd_path();
if (child > 0 || pidfd >= 0) return;
struct stat st;
- if (stat(path, &st)) { if (!fails++) sd_log("sin %s: la red la levanta cada sesión, como antes", path); next_try = rd_now() + 3600; return; }
+ if (stat(path, &st)) { if (!fails++) sd_log("no %s: each session brings the network up, as before", path); next_try = rd_now() + 3600; return; }
if (!rd_conf.insecure_dev && (st.st_uid != 0 || (st.st_mode & 022))) {
- sd_log("%s no es de root o lo pueden escribir otros: no se lanza", path);
+ sd_log("%s is not root-owned or is writable by others: not started", path);
next_try = rd_now() + 3600;
return;
}
@@ -85,7 +85,7 @@ void sd_netd_start(void) {
if (!adopt()) return;
pid_t p = fork();
if (p == 0) {
- syscall(SYS_close_range, 3, ~0u, 0); /* nada del monitor ni de las conexiones */
+ syscall(SYS_close_range, 3, ~0u, 0); /* nothing from the monitor or the connections */
int null = open("/dev/null", O_RDWR);
if (null >= 0) dup2(null, 0);
sigset_t none;
@@ -94,7 +94,7 @@ void sd_netd_start(void) {
signal(SIGPIPE, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGHUP, SIG_DFL);
- setsid(); /* no muere con lord-sessiond (KillMode=process) */
+ setsid(); /* does not die with lord-sessiond (KillMode=process) */
char *const argv[] = { path, NULL };
char *const env[] = { "PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C.UTF-8", NULL };
execve(path, argv, env);
@@ -103,7 +103,7 @@ void sd_netd_start(void) {
if (p < 0) { next_try = rd_now() + 5; return; }
child = p;
started = rd_now();
- sd_log("lord-netd lanzado (pid %d)", (int)p);
+ sd_log("lord-netd started (pid %d)", (int)p);
}
int sd_netd_fd(void) { return pidfd; }
@@ -113,22 +113,22 @@ static void schedule(const char *why) {
double wait = fails < 5 ? (double)(1 << fails) : 30;
fails++;
next_try = rd_now() + wait;
- sd_log("lord-netd %s: se vuelve a lanzar en %.0f s", why, wait);
+ sd_log("lord-netd %s: restarting in %.0f s", why, wait);
}
-void sd_netd_event(void) { /* el pidfd del adoptado avisó que terminó */
+void sd_netd_event(void) { /* the adopted one's pidfd says it exited */
close(pidfd);
pidfd = -1;
- schedule("(adoptado) terminó");
+ schedule("(adopted) exited");
}
int sd_netd_reaped(pid_t pid, int status) {
if (pid != child) return 0;
child = -1;
- if (WIFEXITED(status) && WEXITSTATUS(status) == 3) { next_try = rd_now() + 1; adopt(); return 1; } /* ya corría otro */
+ if (WIFEXITED(status) && WEXITSTATUS(status) == 3) { next_try = rd_now() + 1; adopt(); return 1; } /* another one was already running */
char why[48];
- if (WIFEXITED(status)) snprintf(why, sizeof why, "terminó con código %d", WEXITSTATUS(status));
- else snprintf(why, sizeof why, "terminó por la señal %d", WIFSIGNALED(status) ? WTERMSIG(status) : 0);
+ if (WIFEXITED(status)) snprintf(why, sizeof why, "exited with code %d", WEXITSTATUS(status));
+ else snprintf(why, sizeof why, "killed by signal %d", WIFSIGNALED(status) ? WTERMSIG(status) : 0);
schedule(why);
return 1;
}
diff --git a/server/src/remote/sessiond.c b/server/src/remote/sessiond.c
index efb473b..682d935 100644
--- a/server/src/remote/sessiond.c
+++ b/server/src/remote/sessiond.c
@@ -662,7 +662,10 @@ int main(int argc, char **argv) {
mkdir("/run/lordos", 0755);
/* cgroup delegado (Delegate=yes): sessiond pasa a la hoja «supervisor» y cada sesión recibe
* su subárbol (cgroup_delegate_session en sess.c). Sin delegación sigue igual que antes. */
- if (!cgroup_service_init()) sd_log("cgroup: servicio delegado; cada sesión tendrá su subárbol");
+ if (!cgroup_service_init()) {
+ sd_log("cgroup: servicio delegado; cada sesión tendrá su subárbol");
+ sd_cgroup_start(); /* app scopes are root's: placed on request (cgsup.c) */
+ }
rd_shared = mmap(NULL, sizeof *rd_shared, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (rd_shared == MAP_FAILED) return 1;
@@ -704,7 +707,7 @@ int main(int argc, char **argv) {
sd_log("sesiones con %s%s%s", rd_conf.server, sd_gpu_env[0] ? ", " : "", sd_gpu_env);
int wk[2];
if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, wk) == 0) { wk_r = wk[0]; wk_w = wk[1]; }
- /* la red es del sistema: lord-netd la levanta antes que la pantalla de ingreso (netsup.c) */
+ /* the network belongs to the system: lord-netd brings it up before the greeter (netsup.c) */
sd_netd_start();
has_monitor = !no_monitor && sd_mon_open() == 0;
if (has_monitor) boot_monitor();
@@ -729,6 +732,7 @@ int main(int argc, char **argv) {
int st;
while ((pid = waitpid(-1, &st, WNOHANG)) > 0) {
if (sd_netd_reaped(pid, st)) continue; /* lord-netd (netsup.c) */
+ if (sd_cgroup_reaped(pid, st)) continue; /* cgroup placement service (cgsup.c) */
if (pid == worker_pid) {
worker_pid = -1;
WorkKind k = pending;
@@ -745,6 +749,7 @@ int main(int argc, char **argv) {
}
if (r > 0 && p[4].fd >= 0 && p[4].revents) sd_netd_event();
sd_netd_tick();
+ sd_cgroup_tick();
if (r > 0 && (p[0].revents & POLLIN)) from_worker();
if (r > 0 && lfd >= 0 && (p[1].revents & POLLIN)) accept_remote();
if (r > 0 && p[2].fd >= 0 && p[2].fd == sd_mon_fd() && p[2].revents) monitor_event();
diff --git a/server/src/remote/sessiond.h b/server/src/remote/sessiond.h
index 74ebb9f..7c7aad5 100644
--- a/server/src/remote/sessiond.h
+++ b/server/src/remote/sessiond.h
@@ -76,12 +76,17 @@ int sd_session_running(uid_t uid); /* ¿hay un lord-server vivo
/* Usuario de sistema sin login para la pantalla de ingreso o el monitor; lo crea si falta. */
struct passwd *sd_system_user(const char *name, const char *home);
-/* ---- netsup.c: lord-netd, la red del sistema (docs/RED.md) ---- */
-void sd_netd_start(void); /* al arrancar; después, sd_netd_tick */
-int sd_netd_fd(void); /* pidfd de un lord-netd adoptado, o -1 */
-void sd_netd_event(void); /* ese pidfd avisó que terminó */
-int sd_netd_reaped(pid_t pid, int status); /* 1 si el hijo era lord-netd */
-void sd_netd_tick(void); /* lo vuelve a lanzar cuando toca */
+/* ---- netsup.c: lord-netd, the system network (docs/RED.md) ---- */
+void sd_netd_start(void); /* at startup; afterwards, sd_netd_tick */
+int sd_netd_fd(void); /* pidfd of an adopted lord-netd, or -1 */
+void sd_netd_event(void); /* that pidfd says it exited */
+int sd_netd_reaped(pid_t pid, int status); /* 1 if the child was lord-netd */
+void sd_netd_tick(void); /* restarts it when due */
+
+/* ---- cgsup.c: root-owned app scopes (/run/lordos/cgroup.sock, docs/PRIVACIDAD.md) ---- */
+void sd_cgroup_start(void); /* after cgroup_service_init */
+int sd_cgroup_reaped(pid_t pid, int status); /* 1 if the child was the cgroup service */
+void sd_cgroup_tick(void); /* restarts it if it died */
/* "LORD_GPU=0" con lordos.gpu=0 en la línea del kernel (o el LORD_GPU del servicio), o vacío */
extern char sd_gpu_env[24];
diff --git a/server/src/sec/broker.h b/server/src/sec/broker.h
index 8703031..1c0a55f 100644
--- a/server/src/sec/broker.h
+++ b/server/src/sec/broker.h
@@ -32,6 +32,9 @@ enum BrokerOp {
BOP_STATE, /* → JSON { theme, locale, keyboard }: el estado actual, al arrancar */
BOP_MENU, /* payload: JSON de los menús de la app (para la barra de menú del sistema) */
BOP_MIC, /* payload "1"/"0": pedir/soltar el micrófono. Con permiso, → fd de solo lectura del anillo */
+ BOP_CAMERA, /* payload "list" | "open dev w h" | "ring sid" (→ read-only ring fd) | "ack sid id" |
+ * "size sid w h" | "photo sid mirror name" | "record sid mirror mic name" |
+ * "recstop sid" | "close sid". See brokercam.c */
BOP_EVENT = 100, /* servidor → app, sin pedido (reqid 0): payload "tipo\0json" */
};
@@ -60,6 +63,8 @@ void brokersrv_events(BrokerEventFn fn);
/* Respuesta del usuario a un aviso (desde JS: lord.broker.resolve). */
void brokersrv_resolve(uint32_t reqid, int allow);
int brokersrv_count(void);
+/* The app <id> is running: ask it for a new window. 0 if sent, -1 if it is not running. */
+int brokersrv_new_window(const char *id);
/* El tema publica su estado (tipo "theme" o "locale", JSON) y se reenvía en vivo a todas las
* apps aisladas; también se guarda para las que arranquen después (BOP_STATE). */
int brokersrv_publish(const char *kind, const char *json, size_t len);
diff --git a/server/src/sec/broker_int.h b/server/src/sec/broker_int.h
new file mode 100644
index 0000000..50ab4ab
--- /dev/null
+++ b/server/src/sec/broker_int.h
@@ -0,0 +1,26 @@
+/* broker_int.h — internals shared by the broker's server-side files (brokersrv.c and
+ * brokercam.c). Not for the rest of lord-server: use broker.h. */
+#ifndef LORD_SEC_BROKER_INT_H
+#define LORD_SEC_BROKER_INT_H
+
+#include "broker.h"
+
+/* App id of broker connection `conn` (index), or NULL if it is not in use. */
+const char *brokersrv_conn_app(int conn);
+/* Event to that app (never blocks). 0 if sent, -1 if the socket is full or gone. */
+int brokersrv_conn_event(int conn, const char *kind, const char *data, size_t len);
+/* Reply to request reqid on fd, optionally passing passfd (SCM_RIGHTS). */
+int brokersrv_reply(int fd, uint32_t reqid, int status, const void *data, uint32_t len, int passfd);
+/* Camera/microphone indicator for the menu bar (only the session's JS draws it). */
+void brokersrv_device(const char *app, const char *kind, int on);
+/* System save dialog (powerbox) for `app`; the answer comes back as brokersrv_pick_result(reqid). */
+void brokersrv_powerbox_save(uint32_t reqid, const char *app, const char *suggest);
+
+/* ---- brokercam.c: the camera of isolated apps ---- */
+void brokercam_handle(int conn, int fd, uint32_t reqid, const char *payload, uint32_t len);
+int brokercam_pick_result(uint32_t reqid, const char *path); /* 1 if it was a camera save */
+void brokercam_conn_closed(int conn);
+void brokercam_revoke(const char *app);
+void brokercam_tick(void);
+
+#endif
diff --git a/server/src/sec/brokercam.c b/server/src/sec/brokercam.c
new file mode 100644
index 0000000..8085af6
--- /dev/null
+++ b/server/src/sec/brokercam.c
@@ -0,0 +1,373 @@
+/* brokercam.c — the camera for isolated .lpk apps, server side (see broker.h BOP_CAMERA and
+ * docs/PRIVACIDAD.md, «Camera»).
+ *
+ * After consent, lord-server opens /dev/videoN and hands it ONLY to lord-media (MK_CAMERA), which
+ * decodes into its frame ring (MM_RING: a sealed memfd with MP_RING_SLOTS BGRA slots). The app
+ * never sees the device: it gets a READ-ONLY reopen of the ring (/proc/self/fd/N, O_RDONLY, so it
+ * can only map it PROT_READ) and, per frame, an event with the frame id. The app acknowledges what
+ * it shows; every ACK is validated here (current generation, a slot we really forwarded and that
+ * is still pending, rate limited) before it reaches lord-media, so a misbehaving app can only
+ * starve itself. Photos and videos are written to a file the user picks in the system's save
+ * dialog (powerbox): lord-server opens it and gives the fd to lord-media, never to the app.
+ * Revoking the permission kills the helper and closes the stream at once. */
+#include "broker_int.h"
+#include "perms.h"
+#include "json.h"
+#include "../media/media_int.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#define MAX_CAMS 16
+#define ACK_RATE 120.0 /* ACKs per second an app may send (bucket refill) */
+#define ACK_BURST 30.0
+
+typedef struct {
+ int used, conn, sid; /* broker connection, media source in lord-server */
+ int gen, w, h, slots, ringfd;
+ uint64_t sent[MP_RING_SLOTS], seq; /* frames forwarded to the app and not acked yet */
+ double tokens, tok_at;
+ long bad; /* rejected ACKs (log only) */
+ uint32_t pick_req; /* powerbox pending for a photo/video */
+ int pick_kind, pick_mirror, pick_mic; /* 1 photo, 2 video */
+ char out_name[256]; /* names of the saved files (never the folder) */
+ char photo_name[256], video_name[256];
+} Cam;
+static Cam cams[MAX_CAMS];
+static uint32_t next_pick = 1;
+
+static double now_s(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + t.tv_nsec / 1e9; }
+
+static Cam *cam_of_sid(int conn, int sid) {
+ for (int i = 0; i < MAX_CAMS; i++) if (cams[i].used && cams[i].conn == conn && cams[i].sid == sid) return &cams[i];
+ return NULL;
+}
+
+static void cam_event(Cam *c, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
+static void cam_event(Cam *c, const char *fmt, ...) {
+ char buf[1024];
+ va_list ap;
+ va_start(ap, fmt);
+ int n = vsnprintf(buf, sizeof buf, fmt, ap);
+ va_end(ap);
+ if (n > 0 && n < (int)sizeof buf) brokersrv_conn_event(c->conn, "cam", buf, (size_t)n);
+}
+
+static void cam_free(Cam *c, int kill_helper) {
+ MediaSrc *s = media_src_get(c->sid);
+ const char *app = brokersrv_conn_app(c->conn);
+ if (s) {
+ if (kill_helper && s->pid > 0) kill(s->pid, SIGKILL); /* revoked: the device is released now */
+ s->bk = NULL;
+ s->bk_msg = NULL;
+ s->closing = 0;
+ s->state = MS_DONE;
+ media_src_close(s);
+ }
+ if (c->ringfd >= 0) close(c->ringfd);
+ if (app) brokersrv_device(app, "camera", 0);
+ memset(c, 0, sizeof *c);
+ c->ringfd = -1;
+}
+
+static int take_token(Cam *c) {
+ double t = now_s();
+ c->tokens += (t - c->tok_at) * ACK_RATE;
+ c->tok_at = t;
+ if (c->tokens > ACK_BURST) c->tokens = ACK_BURST;
+ if (c->tokens < 1) return 0;
+ c->tokens -= 1;
+ return 1;
+}
+
+static void self_ack(Cam *c, MediaSrc *s, uint32_t id) {
+ int slot = (int)(id & 0xff);
+ if (s->sock >= 0) mp_sendv(s->sock, MM_ACK, id, 0, 0, 0, 0);
+ uint64_t q = slot < MP_RING_SLOTS ? c->sent[slot] : 0;
+ for (int i = 0; i < MP_RING_SLOTS; i++) if (c->sent[i] && c->sent[i] <= q) c->sent[i] = 0;
+}
+
+/* Messages of this camera's lord-media: they go to the app, not to the session's JS. */
+static int on_helper_msg(void *src, const MediaMsg *m, const char *payload, int *fds) {
+ MediaSrc *s = src;
+ Cam *c = s->bk;
+ if (!c) return 0;
+ char esc[512];
+ switch (m->type) {
+ case MM_RING: {
+ int64_t w = m->v[1], h = m->v[2], slots = m->v[3];
+ struct stat st;
+ int seals = fds[0] >= 0 ? fcntl(fds[0], F_GET_SEALS) : -1;
+ if (fds[0] < 0 || w < 2 || h < 2 || w > MP_MAX_DIM || h > MP_MAX_DIM || slots < 1 || slots > MP_RING_SLOTS ||
+ fstat(fds[0], &st) || (uint64_t)st.st_size < (uint64_t)w * (uint64_t)h * 4 * (uint64_t)slots || seals < 0 || !(seals & F_SEAL_SHRINK)) {
+ fprintf(stderr, "broker[%s]: camera ring rejected (unsealed or too small)\n", brokersrv_conn_app(c->conn));
+ return 1;
+ }
+ if (c->ringfd >= 0) close(c->ringfd);
+ c->ringfd = fds[0];
+ fds[0] = -1; /* ours now */
+ c->gen = (int)m->v[0];
+ c->w = (int)w;
+ c->h = (int)h;
+ c->slots = (int)slots;
+ memset(c->sent, 0, sizeof c->sent);
+ cam_event(c, "ring %d", c->sid);
+ return 1;
+ }
+ case MM_FRAME: {
+ int gen = (int)(m->id >> 8), slot = (int)(m->id & 0xff);
+ if (c->ringfd < 0 || gen != c->gen || slot >= c->slots) return 1;
+ c->sent[slot] = ++c->seq;
+ char ev[64];
+ int n = snprintf(ev, sizeof ev, "frame %d %u", c->sid, (unsigned)m->id);
+ /* the app's socket is full: free the slots ourselves (only the app loses frames) */
+ if (brokersrv_conn_event(c->conn, "cam", ev, (size_t)n)) self_ack(c, s, m->id);
+ return 1;
+ }
+ case MM_INFO:
+ /* lord-media's JSON: parsed again here, and only well-formed JSON goes on to the app */
+ if (payload && m->len && m->len < 1024 && payload[0] == '{') {
+ JDoc d;
+ if (!json_parse(payload, strlen(payload), &d, NULL, 0)) { json_free(&d); cam_event(c, "event %d info %s", c->sid, payload); }
+ }
+ return 1;
+ case MM_STATE: {
+ static const char *const names[] = { "loading", "playing", "paused", "ended", "recording", "done", "failed" };
+ int st = (int)m->v[0];
+ s->state = st;
+ if (st >= 0 && st <= MS_FAILED) cam_event(c, "event %d state {\"state\":\"%s\"}", c->sid, names[st]);
+ return 1;
+ }
+ case MM_LEVEL:
+ cam_event(c, "event %d level {\"level\":%lld,\"ms\":%lld}", c->sid, (long long)m->v[0], (long long)m->v[1]);
+ return 1;
+ case MM_RESULT: {
+ int ok = m->v[0] == 0;
+ const char *name = m->id == 1 ? c->photo_name : c->video_name;
+ json_quote(esc, sizeof esc, ok ? name : "");
+ cam_event(c, "event %d %s {\"ok\":%s,\"path\":%s}", c->sid, m->id == 1 ? "photo" : "video", ok ? "true" : "false", esc);
+ if (m->id == 2 && s->mic) { maudio_close(s->mic); s->mic = NULL; }
+ return 1;
+ }
+ case MM_ERROR:
+ cam_event(c, "event %d error {\"message\":\"camera\"}", c->sid);
+ return 1;
+ default:
+ return 1; /* nothing else of a camera reaches the session */
+ }
+}
+
+static int dev_ok(const char *d) {
+ if (!d || strncmp(d, "/dev/video", 10)) return 0;
+ size_t n = strlen(d + 10);
+ if (n < 1 || n > 2) return 0;
+ for (size_t i = 0; i < n; i++) if (!isdigit((unsigned char)d[10 + i])) return 0;
+ return 1;
+}
+
+/* a file name suggested by the app for the save dialog: a plain name, nothing else */
+static void clean_name(const char *in, const char *def, char *out, size_t n) {
+ const char *b = in ? strrchr(in, '/') : NULL;
+ b = b ? b + 1 : in;
+ size_t k = 0;
+ for (; b && *b && k + 1 < n && k < 120; b++) if ((unsigned char)*b >= 0x20 && *b != '\\') out[k++] = *b;
+ out[k] = 0;
+ if (!k || !strcmp(out, ".") || !strcmp(out, "..")) snprintf(out, n, "%s", def);
+}
+
+void brokercam_handle(int conn, int fd, uint32_t reqid, const char *payload, uint32_t len) {
+ (void)len;
+ const char *app = brokersrv_conn_app(conn);
+ char cmd[16] = "";
+ sscanf(payload, "%15s", cmd);
+ int allowed = app && perm_get(app, PERM_CAMERA) == PERM_ALLOW;
+ if (!strcmp(cmd, "list")) {
+ static char json[8192];
+ if (!allowed) snprintf(json, sizeof json, "[]");
+ else media_cameras(json, sizeof json);
+ brokersrv_reply(fd, reqid, BST_OK, json, (uint32_t)strlen(json), -1);
+ return;
+ }
+ if (!strcmp(cmd, "open")) {
+ char dev[32] = "";
+ int w = 1280, h = 720;
+ sscanf(payload, "%*s %31s %d %d", dev, &w, &h);
+ if (!allowed) { brokersrv_reply(fd, reqid, BST_DENIED, NULL, 0, -1); return; }
+ if (!dev_ok(dev)) { brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ if (w < 160 || w > 3840) w = 1280;
+ if (h < 120 || h > 2160) h = 720;
+ Cam *c = NULL;
+ int mine = 0;
+ for (int i = 0; i < MAX_CAMS; i++) { if (cams[i].used && cams[i].conn == conn) mine++; if (!cams[i].used && !c) c = &cams[i]; }
+ if (!c || mine >= 4) { brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ int dfd = open(dev, O_RDWR | O_NONBLOCK | O_CLOEXEC);
+ if (dfd < 0) { brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ MediaSrc *s = media_src_new(SK_CAMERA, app);
+ if (!s) { close(dfd); brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ int render = media_render_fd();
+ char params[96];
+ snprintf(params, sizeof params, "width=%d\nheight=%d\nhw=%d\nhwaccel=%s\n", w, h, render >= 0, media_hwaccel());
+ int fds[2] = { dfd, render };
+ /* the device fd goes to lord-media only */
+ s->sock = media_spawn(MK_CAMERA, params, fds, 2, &s->pid);
+ close(dfd);
+ if (render >= 0) close(render);
+ if (s->sock < 0) { media_src_close(s); brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ memset(c, 0, sizeof *c);
+ c->used = 1;
+ c->conn = conn;
+ c->sid = s->id;
+ c->ringfd = -1;
+ c->tokens = ACK_BURST;
+ c->tok_at = now_s();
+ s->bk = c;
+ s->bk_msg = on_helper_msg;
+ brokersrv_device(app, "camera", 1);
+ char r[16];
+ int n = snprintf(r, sizeof r, "%d", c->sid);
+ fprintf(stderr, "broker[%s]: camera %s opened (lord-media %d)\n", app, dev, (int)s->pid);
+ brokersrv_reply(fd, reqid, BST_OK, r, (uint32_t)n, -1);
+ return;
+ }
+ int sid = 0;
+ sscanf(payload, "%*s %d", &sid);
+ Cam *c = cam_of_sid(conn, sid);
+ MediaSrc *s = c ? media_src_get(c->sid) : NULL;
+ if (!strcmp(cmd, "ack")) { /* no reply: the app never waits for it */
+ unsigned id = 0;
+ sscanf(payload, "%*s %*d %u", &id);
+ int gen = (int)(id >> 8), slot = (int)(id & 0xff);
+ if (!s || s->sock < 0) return;
+ if (!take_token(c) || gen != c->gen || slot >= c->slots || !c->sent[slot]) {
+ if (++c->bad == 1 || c->bad % 1000 == 0) fprintf(stderr, "broker[%s]: invalid camera ACK ignored (%ld)\n", app, c->bad);
+ return;
+ }
+ self_ack(c, s, id);
+ return;
+ }
+ if (!strcmp(cmd, "size")) { /* no reply */
+ int w = 0, h = 0;
+ sscanf(payload, "%*s %*d %d %d", &w, &h);
+ if (s && s->sock >= 0 && w >= 16 && h >= 16 && w <= MP_MAX_DIM && h <= MP_MAX_DIM && take_token(c)) mp_sendv(s->sock, MM_SIZE, 0, w, h, 0, 0);
+ return;
+ }
+ if (!strcmp(cmd, "ring")) {
+ if (!s || c->ringfd < 0) { brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ /* READ-ONLY reopen of the memfd: the app can only map it PROT_READ */
+ char proc[64];
+ snprintf(proc, sizeof proc, "/proc/self/fd/%d", c->ringfd);
+ int ro = open(proc, O_RDONLY | O_CLOEXEC);
+ if (ro < 0) { brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ char info[64];
+ int n = snprintf(info, sizeof info, "%d %d %d %d", c->gen, c->w, c->h, c->slots);
+ brokersrv_reply(fd, reqid, BST_OK, info, (uint32_t)n, ro);
+ close(ro);
+ return;
+ }
+ if (!strcmp(cmd, "photo") || !strcmp(cmd, "record")) {
+ int mirror = 0, mic = 0;
+ const char *rest = payload;
+ if (!strcmp(cmd, "photo")) sscanf(payload, "%*s %*d %d", &mirror);
+ else sscanf(payload, "%*s %*d %d %d", &mirror, &mic);
+ for (int k = 0; k < (cmd[0] == 'p' ? 3 : 4) && rest; k++) { rest = strchr(rest, ' '); if (rest) rest++; }
+ if (!s || s->sock < 0 || !allowed || c->pick_req) { brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1); return; }
+ clean_name(rest, cmd[0] == 'p' ? "foto.jpg" : "video.mp4", c->out_name, sizeof c->out_name);
+ /* the save dialog is the system's; the chosen file is opened here and goes to lord-media */
+ c->pick_req = 0x80000000u | (next_pick++ & 0x7fffffffu);
+ c->pick_kind = cmd[0] == 'p' ? 1 : 2;
+ c->pick_mirror = mirror != 0;
+ c->pick_mic = mic != 0;
+ brokersrv_powerbox_save(c->pick_req, app, c->out_name);
+ brokersrv_reply(fd, reqid, BST_OK, NULL, 0, -1);
+ return;
+ }
+ if (!strcmp(cmd, "recstop")) {
+ int ok = s && s->sock >= 0 && mp_send(s->sock, MM_RECORD, 2, NULL, NULL, 0, NULL, 0) == 0;
+ brokersrv_reply(fd, reqid, ok ? BST_OK : BST_ERROR, NULL, 0, -1);
+ return;
+ }
+ if (!strcmp(cmd, "close")) {
+ if (c) cam_free(c, 0);
+ brokersrv_reply(fd, reqid, BST_OK, NULL, 0, -1);
+ return;
+ }
+ brokersrv_reply(fd, reqid, BST_ERROR, NULL, 0, -1);
+}
+
+int brokercam_pick_result(uint32_t reqid, const char *path) {
+ if (!(reqid & 0x80000000u)) return 0;
+ for (int i = 0; i < MAX_CAMS; i++) {
+ Cam *c = &cams[i];
+ if (!c->used || c->pick_req != reqid) continue;
+ int kind = c->pick_kind;
+ c->pick_req = 0;
+ MediaSrc *s = media_src_get(c->sid);
+ const char *app = brokersrv_conn_app(c->conn);
+ int f = -1;
+ struct stat st;
+ if (path && path[0] && s && s->sock >= 0 && app && perm_get(app, PERM_CAMERA) == PERM_ALLOW)
+ f = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0644);
+ if (f >= 0 && (fstat(f, &st) || !S_ISREG(st.st_mode))) { close(f); f = -1; }
+ const char *base = path ? strrchr(path, '/') : NULL;
+ base = base ? base + 1 : (path ? path : "");
+ if (f < 0) {
+ cam_event(c, "event %d %s {\"ok\":false,\"path\":\"\",\"canceled\":%s}", c->sid, kind == 1 ? "photo" : "video", path && path[0] ? "false" : "true");
+ return 1;
+ }
+ snprintf(kind == 1 ? c->photo_name : c->video_name, sizeof c->photo_name, "%s", base);
+ int r;
+ if (kind == 1) {
+ int64_t v[6] = { c->pick_mirror, 0, 0, 0, 0, 0 };
+ r = mp_send(s->sock, MM_PHOTO, 1, v, NULL, 0, &f, 1);
+ } else {
+ int ring = -1;
+ if (c->pick_mic && perm_get(app, PERM_MICROPHONE) == PERM_ALLOW) {
+ maudio_close(s->mic);
+ s->mic = maudio_open(1, app, "Video", "", &ring);
+ }
+ int64_t v[6] = { c->pick_mirror, 0, 0, 0, 0, 0 };
+ int fds[2] = { f, ring };
+ r = mp_send(s->sock, MM_RECORD, 2, v, NULL, 0, fds, ring >= 0 ? 2 : 1);
+ }
+ close(f);
+ if (r) cam_event(c, "event %d %s {\"ok\":false,\"path\":\"\"}", c->sid, kind == 1 ? "photo" : "video");
+ return 1;
+ }
+ return 1; /* a camera pick that is gone (camera closed meanwhile) */
+}
+
+void brokercam_conn_closed(int conn) {
+ for (int i = 0; i < MAX_CAMS; i++) if (cams[i].used && cams[i].conn == conn) cam_free(&cams[i], 1);
+}
+
+void brokercam_revoke(const char *app) {
+ for (int i = 0; i < MAX_CAMS; i++) {
+ Cam *c = &cams[i];
+ const char *a = c->used ? brokersrv_conn_app(c->conn) : NULL;
+ if (!a || strcmp(a, app)) continue;
+ cam_event(c, "closed %d revoked", c->sid);
+ fprintf(stderr, "broker[%s]: camera permission revoked: lord-media %d killed\n", app, (int)(media_src_get(c->sid) ? media_src_get(c->sid)->pid : 0));
+ cam_free(c, 1);
+ }
+}
+
+void brokercam_tick(void) {
+ for (int i = 0; i < MAX_CAMS; i++) {
+ Cam *c = &cams[i];
+ if (!c->used) continue;
+ MediaSrc *s = media_src_get(c->sid);
+ if (!s || s->sock < 0) { /* lord-media ended or crashed */
+ cam_event(c, "closed %d ended", c->sid);
+ cam_free(c, 0);
+ }
+ }
+}
diff --git a/server/src/sec/brokersrv.c b/server/src/sec/brokersrv.c
index 1e5ba16..2a82710 100644
--- a/server/src/sec/brokersrv.c
+++ b/server/src/sec/brokersrv.c
@@ -2,7 +2,7 @@
* compositor). Atiende los pedidos de cada app .lpk aislada, verifica los permisos
* (perms.c) y, cuando hace falta consentimiento, le pide a la interfaz que dibuje el aviso del
* sistema (nunca lo dibuja la app). */
-#include "broker.h"
+#include "broker_int.h"
#include "perms.h"
#include "json.h"
#include "../lpk.h"
@@ -98,6 +98,7 @@ typedef struct { int used, save; uint32_t reqid; int fd; char id[48]; } Pick;
static Pick picks[MAX_PENDING];
void brokersrv_pick_result(uint32_t reqid, const char *path) {
+ if (brokercam_pick_result(reqid, path)) return; /* a camera photo/video save */
for (int i = 0; i < MAX_PENDING; i++) {
if (!picks[i].used || picks[i].reqid != reqid) continue;
int f = -1;
@@ -131,11 +132,13 @@ void brokersrv_revoke(const char *app, const char *perm) {
for (int i = 0; i < MAX_APPS; i++) if (apps[i].used && !strcmp(apps[i].id, app)) send_event(&apps[i], "revoke", json, strlen(json));
if (!strcmp(perm, "microphone")) for (int i = 0; i < MAX_APPS; i++)
if (apps[i].used && !strcmp(apps[i].id, app) && apps[i].mic) { maudio_close(apps[i].mic); apps[i].mic = NULL; }
+ if (!strcmp(perm, "camera")) brokercam_revoke(app); /* kills its lord-media: the stream stops now */
if (!strcmp(perm, "camera") || !strcmp(perm, "microphone"))
queue_evt("device", "{\"app\":\"%s\",\"kind\":\"%s\",\"on\":false}", app, perm);
}
void brokersrv_tick(void) {
+ brokercam_tick();
char kb[512];
keyboard_json(kb, sizeof kb);
int kb_changed = strcmp(kb, sent_kb) != 0;
@@ -161,9 +164,18 @@ int brokersrv_add(int fd, const char *id, int pid) {
return -1;
}
+/* The app is already running: ask its process for another window (Dock → «New window»). */
+int brokersrv_new_window(const char *id) {
+ static const char json[] = "{\"new\":true}";
+ for (int i = 0; i < MAX_APPS; i++)
+ if (apps[i].used && !strcmp(apps[i].id, id)) return send_event(&apps[i], "window", json, sizeof json - 1) ? -1 : 0;
+ return -1;
+}
+
int brokersrv_count(void) { int n = 0; for (int i = 0; i < MAX_APPS; i++) n += apps[i].used; return n; }
static void drop(AppConn *a) {
+ brokercam_conn_closed((int)(a - apps));
/* los indicadores de esta app se apagan */
queue_evt("device", "{\"app\":\"%s\",\"off\":true}", a->id);
if (a->mic) { maudio_close(a->mic); a->mic = NULL; }
@@ -362,6 +374,9 @@ static void handle(AppConn *a, BrokerHdr *h, char *payload) {
case BOP_QUIT:
send_reply(fd, h->reqid, BST_OK, NULL, 0);
break;
+ case BOP_CAMERA:
+ brokercam_handle((int)(a - apps), fd, h->reqid, payload, h->len);
+ break;
default:
send_reply(fd, h->reqid, BST_ERROR, NULL, 0);
break;
@@ -424,6 +439,32 @@ void brokersrv_audio_dispatch(struct pollfd *pfd, int n) {
}
}
+/* ---- for brokercam.c (broker_int.h) ---- */
+
+const char *brokersrv_conn_app(int conn) { return conn >= 0 && conn < MAX_APPS && apps[conn].used ? apps[conn].id : NULL; }
+
+int brokersrv_conn_event(int conn, const char *kind, const char *data, size_t len) {
+ if (conn < 0 || conn >= MAX_APPS || !apps[conn].used) return -1;
+ BrokerHdr h = { .reqid = 0, .op = BOP_EVENT, .status = 0, .len = (uint32_t)(strlen(kind) + 1 + len) };
+ struct iovec iov[3] = { { &h, sizeof h }, { (void *)kind, strlen(kind) + 1 }, { (void *)data, len } };
+ struct msghdr m = { .msg_iov = iov, .msg_iovlen = 3 };
+ return sendmsg(apps[conn].fd, &m, MSG_NOSIGNAL | MSG_DONTWAIT) < 0 ? -1 : 0; /* no resync for frames */
+}
+
+int brokersrv_reply(int fd, uint32_t reqid, int status, const void *data, uint32_t len, int passfd) {
+ return send_reply_fd(fd, reqid, status, data, len, passfd);
+}
+
+void brokersrv_device(const char *app, const char *kind, int on) {
+ queue_evt("device", "{\"app\":\"%s\",\"kind\":\"%s\",\"on\":%s}", app, kind, on ? "true" : "false");
+}
+
+void brokersrv_powerbox_save(uint32_t reqid, const char *app, const char *suggest) {
+ char sq[300];
+ json_quote(sq, sizeof sq, suggest);
+ queue_evt("pick", "{\"reqid\":%u,\"app\":\"%s\",\"save\":true,\"suggest\":%s}", reqid, app, sq);
+}
+
void brokersrv_events(BrokerEventFn fn) {
for (int i = 0; i < nevt; i++) fn(evq[i].kind, evq[i].json);
nevt = 0;
diff --git a/server/src/sec/cgroup.c b/server/src/sec/cgroup.c
index 05fc7d8..2928ed5 100644
--- a/server/src/sec/cgroup.c
+++ b/server/src/sec/cgroup.c
@@ -2,13 +2,20 @@
* sin libsystemd ni D-Bus. Degrada con un aviso si falta la delegación o un controlador. */
#include "cgroup.h"
+#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/time.h>
#include <sys/types.h>
+#include <sys/un.h>
#include <string.h>
+#include <time.h>
#include <unistd.h>
#define CG_ROOT "/sys/fs/cgroup"
@@ -82,11 +89,61 @@ static int write_at(int dirfd, const char *leaf, const char *val) {
return w == (ssize_t)n ? 0 : -1;
}
+/* Is this a scope name lord-sessiond agrees to create? "app-lordos-<id>.scope" (Linux and .lpk
+ * apps, lord-media) or "lordos-<helper>.scope" (lord-doc, lord-vault), never "lordos-session-…". */
+int cgroup_scope_name_ok(const char *name) {
+ size_t n = name ? strlen(name) : 0;
+ if (n < 8 || n > 90 || strcmp(name + n - 6, ".scope")) return 0;
+ if (strncmp(name, "app-lordos-", 11) && (strncmp(name, "lordos-", 7) || !strncmp(name, "lordos-session-", 15))) return 0;
+ for (const char *p = name; *p; p++)
+ if (!((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '-' || *p == '.' || *p == '_' || *p == '@')) return 0;
+ return !strstr(name, "..");
+}
+
+/* Ask lord-sessiond (root) over CGROUP_SOCK to move THIS process into the scope. Returns 0 when
+ * placed, -1 when refused or unanswered, -2 when there is no lord-sessiond (development). In a
+ * lord-sessiond session (LORDOS_SESSIOND) it waits up to 3 s for a restarting lord-sessiond. */
+static int enter_via_sessiond(const char *name, const CgroupLimits *lim) {
+ int managed = getenv("LORDOS_SESSIOND") != NULL;
+ struct sockaddr_un a = { .sun_family = AF_UNIX };
+ snprintf(a.sun_path, sizeof a.sun_path, "%s", CGROUP_SOCK);
+ int fd = -1;
+ for (int i = 0; i < 30; i++) {
+ fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
+ if (fd < 0) return managed ? -1 : -2;
+ if (!connect(fd, (struct sockaddr *)&a, sizeof a)) break;
+ int e = errno;
+ close(fd);
+ fd = -1;
+ if (!managed && e == ENOENT) return -2;
+ if (e != ENOENT && e != ECONNREFUSED && e != EAGAIN) break;
+ struct timespec ts = { 0, 100 * 1000 * 1000 };
+ nanosleep(&ts, NULL);
+ }
+ if (fd < 0) { fprintf(stderr, "cgroup: lord-sessiond does not answer (%s); %s runs without a scope\n", CGROUP_SOCK, name); return -1; }
+ struct timeval tv = { 3, 0 };
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ char req[160], rep[128];
+ int n = snprintf(req, sizeof req, "enter %s %ld %ld %d", name, lim ? lim->mem_high_mb : 0, lim ? lim->mem_max_mb : 0, lim ? lim->cpu_percent : 0);
+ ssize_t r = n > 0 && n < (int)sizeof req ? send(fd, req, (size_t)n, MSG_NOSIGNAL) : -1;
+ if (r == n) r = recv(fd, rep, sizeof rep - 1, 0);
+ close(fd);
+ if (r <= 0) { fprintf(stderr, "cgroup: no reply from lord-sessiond; %s runs without a scope\n", name); return -1; }
+ rep[r] = 0;
+ if (strncmp(rep, "ok", 2)) { fprintf(stderr, "cgroup: lord-sessiond refused %s: %s\n", name, rep); return -1; }
+ return 0;
+}
+
int cgroup_enter(const char *name, const CgroupLimits *lim) {
char base[PATH_MAX], scope[PATH_MAX], val[64];
for (const char *p = name; *p; p++)
if (!((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '-' || *p == '.' || *p == '_' || *p == '@'))
{ fprintf(stderr, "cgroup: nombre inválido %s\n", name); return -1; }
+ /* With lord-sessiond the scopes belong to root (root-owned cgroup.procs): it creates them and
+ * moves us, so an app cannot migrate to another cgroup of the session. Without it
+ * (development) we fall back to the old self-migration. */
+ int via = enter_via_sessiond(name, lim);
+ if (via != -2) return via;
if (base_dir(base, sizeof base)) { fprintf(stderr, "cgroup: sin subárbol delegado (%s); la app corre sin scope\n", errno == EACCES ? "no escribible" : strerror(errno)); return -1; }
enable_controllers(base);
if ((size_t)snprintf(scope, sizeof scope, "%s/%s", base, name) >= sizeof scope) return -1;
@@ -105,10 +162,30 @@ int cgroup_enter(const char *name, const CgroupLimits *lim) {
return 0;
}
-/* chown del directorio del cgroup y de sus controles, relativo a dirfd (sin armar rutas largas). */
-static void chown_ctl_at(int dirfd, unsigned uid, unsigned gid) {
- static const char *const f[] = { ".", "cgroup.procs", "cgroup.subtree_control", "cgroup.threads", NULL };
- for (int i = 0; f[i]; i++) fchownat(dirfd, f[i], uid, gid, 0);
+/* chown root:root a cgroup directory and every control file in it (dirfd = that directory). */
+static void chown_root_dir(int dirfd) {
+ fchown(dirfd, 0, 0);
+ int d = dup(dirfd);
+ DIR *dir = d >= 0 ? fdopendir(d) : NULL;
+ if (!dir) { if (d >= 0) close(d); return; }
+ struct dirent *e;
+ while ((e = readdir(dir))) if (e->d_name[0] != '.') fchownat(dirfd, e->d_name, 0, 0, AT_SYMLINK_NOFOLLOW);
+ closedir(dir);
+}
+
+void cgroup_harden_session(int sessfd) {
+ if (geteuid() != 0 || sessfd < 0) return;
+ chown_root_dir(sessfd);
+ int d = dup(sessfd);
+ DIR *dir = d >= 0 ? fdopendir(d) : NULL;
+ if (!dir) { if (d >= 0) close(d); return; }
+ struct dirent *e;
+ while ((e = readdir(dir))) {
+ if (e->d_name[0] == '.' || e->d_type != DT_DIR) continue;
+ int c = openat(sessfd, e->d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (c >= 0) { chown_root_dir(c); close(c); }
+ }
+ closedir(dir);
}
/* Raíz del servicio: el cgroup propio, o su padre si estamos en la hoja «supervisor» que crea
@@ -135,11 +212,23 @@ int cgroup_service_init(void) {
close(fd);
if (r) { fprintf(stderr, "cgroup: lordos.service sin Delegate=yes (no se pudo usar la hoja supervisor)\n"); return -1; }
enable_controllers(svc); /* ahora la raíz no tiene procesos: puede habilitar controladores */
+ /* sessions that survived a restart (or were delegated by an older lord-sessiond): back to root */
+ DIR *dir = opendir(svc);
+ struct dirent *e;
+ while (dir && (e = readdir(dir))) {
+ unsigned u;
+ char tail;
+ if (sscanf(e->d_name, "lordos-session-%u%c", &u, &tail) != 1) continue;
+ int sfd = openat(dirfd(dir), e->d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (sfd >= 0) { cgroup_harden_session(sfd); close(sfd); }
+ }
+ if (dir) closedir(dir);
return 0;
}
int cgroup_delegate_session(unsigned uid, unsigned gid) {
char svc[PATH_MAX], sess[PATH_MAX];
+ (void)gid;
if (service_root(svc, sizeof svc)) return -1;
if (access(svc, W_OK)) { fprintf(stderr, "cgroup: lordos.service sin Delegate=yes; la sesión de %u corre sin subárbol\n", uid); return -1; }
enable_controllers(svc);
@@ -151,12 +240,13 @@ int cgroup_delegate_session(unsigned uid, unsigned gid) {
if (mkdirat(sfd, "server", 0755) && errno != EEXIST) { close(sfd); return -1; }
int lfd = openat(sfd, "server", O_DIRECTORY | O_CLOEXEC);
if (lfd < 0 || write_at(lfd, "cgroup.procs", "0")) { fprintf(stderr, "cgroup: no se pudo mover la sesión %u a su hoja: %s\n", uid, strerror(errno)); if (lfd >= 0) close(lfd); close(sfd); return -1; }
- /* el usuario es dueño del subárbol: lord-server (ya sin root) crea las scopes de las apps */
- chown_ctl_at(sfd, uid, gid);
- chown_ctl_at(lfd, uid, gid);
+ /* The subtree stays root-owned (it used to be chowned to the user). lord-sessiond creates the
+ * app scopes on request (cgroup_place_serve) with a root-owned cgroup.procs, so no user
+ * process can migrate to another cgroup of the session (see docs/PRIVACIDAD.md). */
close(lfd);
+ cgroup_harden_session(sfd);
close(sfd);
- fprintf(stderr, "cgroup: sesión %u delegada en lordos-session-%u\n", uid, uid);
+ fprintf(stderr, "cgroup: session %u in lordos-session-%u (root-owned scopes)\n", uid, uid);
return 0;
}
@@ -166,3 +256,89 @@ void app_scope_enter(const char *id) {
CgroupLimits lim = { .mem_high_mb = 0, .mem_max_mb = 0, .cpu_percent = 0 }; /* Linux apps: sin límite, solo atribución */
cgroup_enter(name, &lim);
}
+
+/* ---- lord-sessiond side: placing a session process into its app scope ---- */
+
+/* "0::<path>" of /proc/<pid>/cgroup, or -1. */
+static int proc_cgroup(pid_t pid, char *out, size_t n) {
+ char p[64], line[PATH_MAX];
+ snprintf(p, sizeof p, "/proc/%d/cgroup", (int)pid);
+ FILE *f = fopen(p, "re");
+ if (!f) return -1;
+ int r = -1;
+ while (fgets(line, sizeof line, f)) {
+ if (strncmp(line, "0::", 3)) continue;
+ char *nl = strchr(line, '\n');
+ if (nl) *nl = 0;
+ if ((size_t)snprintf(out, n, "%s", line + 3) < n) r = 0;
+ break;
+ }
+ fclose(f);
+ return r;
+}
+
+/* The executable of the peer must be a LordOS binary from bindir (lord-server, lord-media,
+ * lord-doc…). A binary replaced while it runs shows up as "<path> (deleted)": still accepted. */
+static int exe_trusted(pid_t pid, const char *bindir, int insecure) {
+ char p[64], exe[PATH_MAX];
+ snprintf(p, sizeof p, "/proc/%d/exe", (int)pid);
+ ssize_t l = readlink(p, exe, sizeof exe - 1);
+ if (l <= 0) return 0;
+ exe[l] = 0;
+ static const char del[] = " (deleted)";
+ size_t el = strlen(exe);
+ if (el > sizeof del - 1 && !strcmp(exe + el - (sizeof del - 1), del)) exe[el - (sizeof del - 1)] = 0;
+ char *slash = strrchr(exe, '/');
+ if (!slash) return 0;
+ *slash = 0;
+ if (strcmp(exe, bindir)) return 0;
+ if (insecure) return 1;
+ struct stat st;
+ return stat(bindir, &st) == 0 && st.st_uid == 0 && !(st.st_mode & (S_IWGRP | S_IWOTH));
+}
+
+static void reply(int fd, const char *msg) { send(fd, msg, strlen(msg), MSG_NOSIGNAL | MSG_DONTWAIT); }
+
+int cgroup_place_serve(int cfd, const char *bindir, int insecure) {
+ struct ucred cr;
+ socklen_t cl = sizeof cr;
+ if (getsockopt(cfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) || cr.pid <= 0) { reply(cfd, "err peer"); return -1; }
+ struct timeval tv = { 1, 0 };
+ setsockopt(cfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ char req[256], name[96];
+ ssize_t r = recv(cfd, req, sizeof req - 1, 0);
+ if (r <= 0) return -1;
+ req[r] = 0;
+ long mh = 0, mm = 0;
+ int cpu = 0;
+ if (sscanf(req, "enter %95s %ld %ld %d", name, &mh, &mm, &cpu) != 4 || !cgroup_scope_name_ok(name)) { reply(cfd, "err request"); return -1; }
+ if (cr.uid < 1000 || cr.uid >= 60000) { reply(cfd, "err uid"); return -1; }
+ /* The peer must still be in its session's «server» leaf: lord-server itself, or a child it
+ * forked right before exec. A process already in an app scope (an app) can never ask. */
+ char svc[PATH_MAX], want[PATH_MAX], have[PATH_MAX];
+ if (service_root(svc, sizeof svc)) { reply(cfd, "err service"); return -1; }
+ const char *rel = svc + strlen(CG_ROOT);
+ if ((size_t)snprintf(want, sizeof want, "%s/lordos-session-%u/server", rel, (unsigned)cr.uid) >= sizeof want) return -1;
+ if (proc_cgroup(cr.pid, have, sizeof have) || strcmp(have, want)) { reply(cfd, "err not in the session leaf"); return -1; }
+ if (!exe_trusted(cr.pid, bindir, insecure)) { reply(cfd, "err untrusted executable"); return -1; }
+ char sess[PATH_MAX];
+ if ((size_t)snprintf(sess, sizeof sess, "%s/lordos-session-%u", svc, (unsigned)cr.uid) >= sizeof sess) return -1;
+ int sfd = open(sess, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ if (sfd < 0) { reply(cfd, "err no session subtree"); return -1; }
+ if (mkdirat(sfd, name, 0755) && errno != EEXIST) { close(sfd); reply(cfd, "err mkdir"); return -1; }
+ int dfd = openat(sfd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
+ close(sfd);
+ if (dfd < 0) { reply(cfd, "err open"); return -1; }
+ chown_root_dir(dfd); /* a scope left by an older lord-sessiond may be the user's */
+ char val[64];
+ if (mh > 0 && mh <= 65536) { snprintf(val, sizeof val, "%ld", mh * 1024L * 1024L); write_at(dfd, "memory.high", val); }
+ if (mm > 0 && mm <= 65536) { snprintf(val, sizeof val, "%ld", mm * 1024L * 1024L); write_at(dfd, "memory.max", val); }
+ if (cpu > 0 && cpu <= 6400) { snprintf(val, sizeof val, "%ld 100000", (long)cpu * 1000L); write_at(dfd, "cpu.max", val); }
+ snprintf(val, sizeof val, "%d", (int)cr.pid);
+ int w = write_at(dfd, "cgroup.procs", val);
+ close(dfd);
+ if (w) { reply(cfd, "err move"); return -1; }
+ /* the peer is blocked waiting for this reply, so the pid cannot have been reused meanwhile */
+ reply(cfd, "ok");
+ return 0;
+}
diff --git a/server/src/sec/cgroup.h b/server/src/sec/cgroup.h
index c5d09b8..2246a4d 100644
--- a/server/src/sec/cgroup.h
+++ b/server/src/sec/cgroup.h
@@ -31,11 +31,11 @@ void app_scope_enter(const char *id);
* para que el monitor sepa en qué scope está. "" si no se pudo leer. */
const char *cgroup_self(void);
-/* Lo llama lord-sessiond (root) en el hijo de una sesión, antes del execve de lord-server:
- * crea un subárbol de cgroup para la sesión, mete al proceso en una hoja «server» y le cede el
- * subárbol al usuario (chown) con memoria/CPU/pids habilitados, para que lord-server pueda crear
- * las scopes de las apps sin root. Mejor esfuerzo: si no hay delegación (Delegate=yes en
- * lordos.service), avisa y sigue. Devuelve 0 si quedó delegado. Ver docs/SESIONES.md. */
+/* Called by lord-sessiond (root) in a session's child, before lord-server's execve: creates the
+ * session's cgroup subtree with memory/CPU/pids enabled and moves the process into its «server»
+ * leaf. The subtree stays root-owned (cgroup_harden_session); app scopes are created later by
+ * lord-sessiond on request (cgroup_place_serve). Best effort: without delegation (Delegate=yes in
+ * lordos.service) it warns and goes on. Returns 0 on success. See docs/SESIONES.md. */
int cgroup_delegate_session(unsigned uid, unsigned gid);
/* Lo llama lord-sessiond al arrancar (root, lordos.service con Delegate=yes): se mueve a la hoja
@@ -43,4 +43,22 @@ int cgroup_delegate_session(unsigned uid, unsigned gid);
* subárboles de las sesiones (regla «sin procesos internos» de cgroup v2). 0 si quedó. */
int cgroup_service_init(void);
+/* ---- Root-owned app scopes (lord-sessiond) ----
+ * With lord-sessiond, a session's subtree stays root-owned: the scopes are created by root, with a
+ * root-owned cgroup.procs, so an app cannot move itself to another cgroup (it would escape its
+ * per-app firewall rules and accounting). cgroup_enter() asks lord-sessiond over CGROUP_SOCK to
+ * place the calling process; without lord-sessiond (development) it self-migrates as before. */
+#define CGROUP_SOCK "/run/lordos/cgroup.sock"
+
+/* 1 if lord-sessiond accepts creating this scope name. */
+int cgroup_scope_name_ok(const char *name);
+
+/* chown root:root a session subtree (lordos-session-<uid>, its leaves and scopes). Root only. */
+void cgroup_harden_session(int sessfd);
+
+/* lord-sessiond: serve one connection on CGROUP_SOCK ("enter <scope> <memhigh> <memmax> <cpu%>").
+ * Only a peer that is in its session's «server» leaf and runs a binary from bindir can be placed,
+ * and only itself (SO_PEERCRED pid). Answers "ok" or "err <reason>". 0 if placed. */
+int cgroup_place_serve(int cfd, const char *bindir, int insecure);
+
#endif
diff --git a/server/src/ui/js.c b/server/src/ui/js.c
index 07ba11c..583ee1f 100644
--- a/server/src/ui/js.c
+++ b/server/src/ui/js.c
@@ -13,6 +13,7 @@
#include "js_doc.h"
#include "js_print.h"
#include "js_vault.h"
+#include "js_mail.h"
#include "js_input.h"
#include "js_fw.h"
#include "js_backup.h"
@@ -24,6 +25,7 @@
#include "js_disk.h"
#include "js_logs.h"
#include "js_help.h"
+#include "js_hw.h"
#include "../media/media.h"
#include "ui.h"
#include "../term/term.h"
@@ -398,13 +400,15 @@ int js_init(const char *bundle_path) {
js_doc_register(ctx, lord); /* lord.doc: PDF, comprimidos y fuentes por el ayudante lord-doc */
js_print_register(ctx, lord); /* lord.print: CUPS por IPP y escáneres eSCL */
js_vault_register(ctx, lord); /* lord.vault: Contraseñas y el llavero por el ayudante lord-vault */
+ js_mail_register(ctx, lord); /* lord.mail: Mail, Calendar, Contacts, Reminders via lord-maild (docs/MAIL.md) */
js_wm_register(ctx, lord); /* lord.wm: mover y cambiar el tamaño de ventanas en C (grab.c) */
js_input_register(ctx, lord); /* lord.input: touchpads y pantallas táctiles (tp/) */
js_fw_register(ctx, lord); /* lord.fw: permisos de red por app (lord-netperm, docs/FIREWALL.md) */
- js_disk_register(ctx, lord); /* lord.disks: discos y particiones (app Discos) */
- js_backup_register(ctx, lord); /* lord.backup: Copias de seguridad (backup/) */
+ js_disk_register(ctx, lord); /* lord.disks: disks and partitions (Disks app) */
+ js_backup_register(ctx, lord); /* lord.backup: Backups (backup/) */
js_logs_register(ctx, lord); /* lord.logs: journal y registros de LordOS (app Registros) */
- js_help_register(ctx, lord); /* lord.help (Ayuda) y lord.time.zoneOffset (Reloj, tzif.c) */
+ js_help_register(ctx, lord); /* lord.help (Help) and lord.time.zoneOffset (Clock, tzif.c) */
+ js_hw_register(ctx, lord); /* lord.display/power/bt/mime/timedate (Settings, src/hw) */
JS_SetPropertyStr(ctx, g, "lord", lord);
JS_FreeValue(ctx, g);
@@ -602,7 +606,7 @@ void js_sound_event(const char *type, const char *json) {
drain_jobs();
}
-/* Copias de seguridad (backup/backup.c): cambió el estado → __lordBackup(estado). */
+/* Backups (backup/backup.c): the status changed → __lordBackup(status). */
void js_backup_event(const char *json) {
if (!ctx) return;
JSValueConst arg = JS_ParseJSON(ctx, json, strlen(json), "<backup>");
@@ -612,7 +616,7 @@ void js_backup_event(const char *json) {
}
/* Red (net/state.c): cambió algo de enlaces, direcciones o rutas → __lordNet("link"|"addr"|"route"). */
-/* Discos (disk/disk.c): se montó, desmontó, enchufó o cambió algo → __lordDisks(qué). */
+/* Disks (disk/disk.c): something was mounted, unmounted, plugged in or changed → __lordDisks(what). */
void js_disk_event(const char *what) {
if (!ctx) return;
JSValueConst arg = JS_NewString(ctx, what);
@@ -641,6 +645,18 @@ void js_logs_event(const char *kind, int id, const char *name) {
drain_jobs();
}
+/* Settings' hardware modules (src/hw): "display", "idle", "power", "bt", "bt-prompt", "bt-result",
+ * "ppd", "ppd-result", "timedate" → __lordHw(kind, data). */
+void js_hw_event(const char *kind, const char *json) {
+ if (!ctx) return;
+ JSValueConst args[2] = { JS_NewString(ctx, kind), JS_ParseJSON(ctx, json, strlen(json), "<hw>") };
+ if (JS_IsException(args[1])) { JS_FreeValue(ctx, JS_GetException(ctx)); args[1] = JS_NULL; }
+ JS_FreeValue(ctx, call_global("__lordHw", 2, args));
+ JS_FreeValue(ctx, args[0]);
+ JS_FreeValue(ctx, args[1]);
+ drain_jobs();
+}
+
/* Respuestas del ayudante privilegiado: kind = LOG | OK | ERR. */
void js_admin_event(int id, const char *kind, const char *text) {
if (!ctx) return;
diff --git a/server/src/ui/js.h b/server/src/ui/js.h
index 4a6f9db..e62fab7 100644
--- a/server/src/ui/js.h
+++ b/server/src/ui/js.h
@@ -20,14 +20,15 @@ void js_media_event(int id, const char *type, const char *json);
void js_term_event(int id, const char *type, const char *data);
void js_sound_event(const char *type, const char *json);
void js_net_event(const char *what);
-void js_disk_event(const char *what); /* app Discos: cambió algo (disk/disk.c) */
-void js_backup_event(const char *json); /* Copias de seguridad → __lordBackup */
+void js_disk_event(const char *what); /* Disks app: something changed (disk/disk.c) */
+void js_backup_event(const char *json); /* Backups → __lordBackup */
void js_admin_event(int id, const char *kind, const char *text);
void js_logs_event(const char *kind, int id, const char *name); /* app Registros */
void js_clipboard_poll(void);
void js_remote_event(const char *json);
void js_greeter_event(const char *json);
void js_screen_resized(void);
+void js_hw_event(const char *kind, const char *json); /* Settings' hardware (src/hw) → __lordHw */
void js_broker_event(const char *kind, const char *json); /* avisos del broker → tema */
void js_broker_app_event(const char *kind, const char *json, size_t len); /* lord-server → app aislada */
diff --git a/server/src/ui/js_backup.c b/server/src/ui/js_backup.c
index bbdaee7..9c24abd 100644
--- a/server/src/ui/js_backup.c
+++ b/server/src/ui/js_backup.c
@@ -1,18 +1,18 @@
-/* js_backup.c — lord.backup: Copias de seguridad (ver backup/backup.c y docs/SISTEMA.md).
+/* js_backup.c — lord.backup: Backups (see backup/backup.c and docs/SYSTEM.md).
*
- * status() estado (también llega solo: __lordBackup(estado))
+ * status() status (also pushed by itself: __lordBackup(status))
* config() / configure(obj) { dest, interval: 'hourly'|'daily'|'weekly'|'manual',
- * pauseOnBattery, exclude: ['rel', …], encrypt: false }
+ * pauseOnBattery, exclude: ['rel', …], encrypt }
* runNow() / pause(bool) / cancel()
- * list() [{ id, time }] de la más vieja a la más nueva
- * ls(id, rel) [{ name, dir, link, size, mtime }] adentro de una copia
- * path(id) ruta real de la copia (para abrirla en Archivos)
- * restore(id, rel, { replace, suffix, to }) rel '' = todo; en el hilo, el resultado llega
- * en status().restore
- * remove(id) borrar una copia
- * unlock(frase, crear) / lock() cifrado: la clave sale de la frase (Argon2id, en el hilo) y queda
- * solo en memoria; el resultado llega en status().unlock
- * Los errores se tiran como excepciones con el motivo. */
+ * list() [{ id, time }] oldest first
+ * ls(id, rel) [{ name, dir, link, size, mtime }] inside a snapshot
+ * path(id) real path of the snapshot (to open it in Files)
+ * restore(id, rel, { replace, suffix, to }) rel '' = everything; runs in the thread, the
+ * result arrives in status().restore
+ * remove(id) delete a snapshot
+ * unlock(pass, create) / lock() encryption: the key is derived from the passphrase (Argon2id, in
+ * the thread) and kept only in memory; result in status().unlock
+ * Errors are thrown as exceptions carrying the reason. */
#include "js_backup.h"
#include "../backup/backup.h"
@@ -40,7 +40,7 @@ static JSValue f_config(JSContext *c, JSValueConst t, int argc, JSValueConst *ar
static JSValue f_configure(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
(void)t;
- if (argc < 1) return JS_ThrowTypeError(c, "falta la configuración");
+ if (argc < 1) return JS_ThrowTypeError(c, "missing configuration");
JSValue s = JS_JSONStringify(c, argv[0], JS_UNDEFINED, JS_UNDEFINED);
const char *j = JS_IsException(s) ? NULL : JS_ToCString(c, s);
JS_FreeValue(c, s);
@@ -85,7 +85,7 @@ static JSValue f_ls(JSContext *c, JSValueConst t, int argc, JSValueConst *argv)
char *j = id ? backup_ls_json(id, rel ? rel : "", err, sizeof err) : NULL;
if (id) JS_FreeCString(c, id);
if (rel) JS_FreeCString(c, rel);
- if (!j) return fail(c, id ? err : "falta la copia");
+ if (!j) return fail(c, id ? err : "missing backup id");
return parsed(c, j, "<backup.ls>");
}
@@ -120,7 +120,7 @@ static JSValue f_restore(JSContext *c, JSValueConst t, int argc, JSValueConst *a
if (rel) JS_FreeCString(c, rel);
if (suffix) JS_FreeCString(c, suffix);
if (to) JS_FreeCString(c, to);
- return r ? fail(c, id ? err : "falta la copia") : JS_TRUE;
+ return r ? fail(c, id ? err : "missing backup id") : JS_TRUE;
}
static JSValue f_remove(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
@@ -129,7 +129,7 @@ static JSValue f_remove(JSContext *c, JSValueConst t, int argc, JSValueConst *ar
char err[256] = "";
int r = id ? backup_delete(id, err, sizeof err) : -1;
if (id) JS_FreeCString(c, id);
- return r ? fail(c, id ? err : "falta la copia") : JS_TRUE;
+ return r ? fail(c, id ? err : "missing backup id") : JS_TRUE;
}
static JSValue f_unlock(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
@@ -139,8 +139,8 @@ static JSValue f_unlock(JSContext *c, JSValueConst t, int argc, JSValueConst *ar
int create = argc > 1 && JS_ToBool(c, argv[1]) > 0;
char err[256] = "";
int r = pass && strlen(pass) == len ? backup_unlock(pass, create, err, sizeof err) : -1;
- if (pass) JS_FreeCString(c, pass); /* no se borra: puede ser la memoria del string de JS */
- return r ? fail(c, pass ? err : "falta la frase") : JS_TRUE;
+ if (pass) JS_FreeCString(c, pass); /* not wiped: it may be the JS string's own memory */
+ return r ? fail(c, pass ? err : "missing passphrase") : JS_TRUE;
}
static JSValue f_lock(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
diff --git a/server/src/ui/js_backup.h b/server/src/ui/js_backup.h
index 3a28c44..bc66f35 100644
--- a/server/src/ui/js_backup.h
+++ b/server/src/ui/js_backup.h
@@ -1,4 +1,4 @@
-/* js_backup.h — lord.backup (Copias de seguridad; ver js_backup.c). */
+/* js_backup.h — lord.backup (Backups; see js_backup.c). */
#ifndef LORD_JS_BACKUP_H
#define LORD_JS_BACKUP_H
diff --git a/server/src/ui/js_broker.c b/server/src/ui/js_broker.c
index 60e882b..9345a29 100644
--- a/server/src/ui/js_broker.c
+++ b/server/src/ui/js_broker.c
@@ -98,6 +98,7 @@ static void dispatch_event(const char *buf, size_t n) {
if (!nul) return;
const char *kind = buf, *json = nul + 1;
size_t jl = n - (size_t)(json - buf);
+ if (!strcmp(kind, "cam")) { js_brokercam_event(json, jl); return; } /* camera frames (js_brokercam.c) */
if (!strcmp(kind, "keyboard")) { apply_keyboard(json, jl); return; }
if (!strcmp(kind, "state")) { /* resincronizar: teclado acá, el resto a JS */
JDoc d;
@@ -113,6 +114,9 @@ static void dispatch_event(const char *buf, size_t n) {
js_broker_app_event(kind, json, jl);
}
+/* events queued while an RPC was waiting: the loop must not sleep on them */
+int js_broker_pending(void) { return nqueued > 0; }
+
void js_broker_poll(void) {
for (int i = 0; i < nqueued; i++) { dispatch_event(queued[i].buf, queued[i].len); free(queued[i].buf); }
nqueued = 0;
@@ -125,6 +129,7 @@ void js_broker_poll(void) {
ssize_t n = recvmsg(broker_fd, &rm, MSG_DONTWAIT);
if (n < (ssize_t)sizeof r) break;
if (r.op != BOP_EVENT) continue; /* una respuesta tardía: nadie la espera */
+ buf[(size_t)n - sizeof r] = 0; /* JS_ParseJSON needs the text NUL-terminated */
dispatch_event(buf, (size_t)n - sizeof r);
}
}
@@ -261,6 +266,17 @@ static int rpc_fd(int op, const void *payload, uint32_t len, char *name, size_t
}
}
+/* For js_brokercam.c (js_broker.h): the same RPCs, plus a send that does not wait for a reply. */
+int js_broker_rpc(int op, const void *payload, uint32_t len, int *status, char **out, uint32_t *outlen) { return rpc(op, payload, len, status, out, outlen); }
+int js_broker_rpc_fd(int op, const void *payload, uint32_t len, char *info, size_t n) { return rpc_fd(op, payload, len, info, n); }
+int js_broker_send(int op, const void *payload, uint32_t len) {
+ if (broker_fd < 0) return -1;
+ BrokerHdr h = { .reqid = next_req++, .op = (uint16_t)op, .status = BROKER_REQ, .len = len };
+ struct iovec iov[2] = { { &h, sizeof h }, { (void *)payload, len } };
+ struct msghdr m = { .msg_iov = iov, .msg_iovlen = len ? 2 : 1 };
+ return sendmsg(broker_fd, &m, MSG_NOSIGNAL | MSG_DONTWAIT) < 0 ? -1 : 0;
+}
+
/* lord.broker.pick(save, nombreSugerido) → { fd, name } | null (el diálogo lo dibuja lord-server) */
static JSValue f_broker_pick(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
(void)t; (void)argc;
@@ -602,4 +618,6 @@ void js_broker_register(JSContext *c, JSValue lord, const char *id) {
add_obj(c, lord, "locale", locale_funcs, sizeof locale_funcs / sizeof locale_funcs[0]);
JS_SetPropertyStr(c, lord, "appId", JS_NewString(c, id));
JS_SetPropertyStr(c, lord, "loadApp", JS_NewCFunction(c, f_load_app, "loadApp", 0));
+ app_windows_register(c, lord); /* several windows per isolated app */
+ js_brokercam_register(c, lord); /* lord.media: the camera through lord-server (js_brokercam.c) */
}
diff --git a/server/src/ui/js_broker.h b/server/src/ui/js_broker.h
index d5c8065..8bd5ac0 100644
--- a/server/src/ui/js_broker.h
+++ b/server/src/ui/js_broker.h
@@ -8,8 +8,22 @@
int js_broker_fd(void); /* fd del broker para poll; -1 si no hay */
void js_broker_poll(void); /* mensajes del servidor sin pedir (indicadores, tema) */
+int js_broker_pending(void); /* events queued during an RPC, not dispatched yet */
void js_broker_set_pkgdir(const char *dir); /* antes de la caja de arena */
int js_broker_wants_network(void); /* la app declaró `network` y lo tiene permitido */
void js_broker_register(JSContext *c, JSValue lord, const char *app_id);
+/* lord.appWindows: the app's own windows (app/appclient.c, docs/PRIVACIDAD.md) */
+void app_windows_register(JSContext *c, JSValue lord);
+
+/* RPCs over the broker for the app-side modules (js_brokercam.c). rpc_fd returns the passed fd
+ * (or -1) and copies the reply text to info; js_broker_send does not wait for a reply. */
+#include <stddef.h>
+#include <stdint.h>
+int js_broker_rpc(int op, const void *payload, uint32_t len, int *status, char **out, uint32_t *outlen);
+int js_broker_rpc_fd(int op, const void *payload, uint32_t len, char *info, size_t n);
+int js_broker_send(int op, const void *payload, uint32_t len);
+/* lord.media of an isolated app: the camera (js_brokercam.c) */
+void js_brokercam_register(JSContext *c, JSValue lord);
+void js_brokercam_event(const char *data, size_t len);
#endif
diff --git a/server/src/ui/js_brokercam.c b/server/src/ui/js_brokercam.c
new file mode 100644
index 0000000..0b5fde4
--- /dev/null
+++ b/server/src/ui/js_brokercam.c
@@ -0,0 +1,263 @@
+/* js_brokercam.c — `lord.media` inside an isolated .lpk app: the camera, through lord-server
+ * (sec/brokercam.c, docs/PRIVACIDAD.md «Camera»).
+ *
+ * The app never opens /dev/video* nor runs lord-media. lord-server does, after consent, and gives
+ * the app a READ-ONLY fd of lord-media's frame ring: mapped PROT_READ here and drawn by the same
+ * <MediaView> code as in the session (media/mview.c), from a local media source with no helper.
+ * Each frame arrives as a broker event; the app acknowledges the slot it now shows (lord-server
+ * validates every ACK). Photos and videos go to a file the user picks in the system's save dialog;
+ * the app only learns the file name. */
+#include "js_broker.h"
+#include "js.h"
+#include "../sec/broker.h"
+#include "../media/media_int.h"
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define MAX_ACAMS 8
+
+typedef struct { int used, sid, local, sent_w, sent_h; } ACam;
+static ACam acams[MAX_ACAMS];
+
+static ACam *by_local(int id) { for (int i = 0; i < MAX_ACAMS; i++) if (acams[i].used && acams[i].local == id) return &acams[i]; return NULL; }
+static ACam *by_sid(int sid) { for (int i = 0; i < MAX_ACAMS; i++) if (acams[i].used && acams[i].sid == sid) return &acams[i]; return NULL; }
+
+static int cmd(const char *fmt, int sid, const char *rest, int *st_out) {
+ char p[400];
+ int n = snprintf(p, sizeof p, fmt, sid, rest ? rest : "");
+ int st = BST_ERROR;
+ if (n <= 0 || n >= (int)sizeof p || js_broker_rpc(BOP_CAMERA, p, (uint32_t)n, &st, NULL, NULL)) st = BST_ERROR;
+ if (st_out) *st_out = st;
+ return st == BST_OK;
+}
+
+/* (re)map the ring lord-server gives us: read-only */
+static void fetch_ring(ACam *a) {
+ char p[32], info[128];
+ int n = snprintf(p, sizeof p, "ring %d", a->sid);
+ int fd = js_broker_rpc_fd(BOP_CAMERA, p, (uint32_t)n, info, sizeof info);
+ if (fd < 0) return;
+ int gen = 0, w = 0, h = 0, slots = 0;
+ MediaSrc *s = media_src_get(a->local);
+ struct stat st;
+ size_t need = 0;
+ if (sscanf(info, "%d %d %d %d", &gen, &w, &h, &slots) == 4 && w > 1 && h > 1 && w <= MP_MAX_DIM && h <= MP_MAX_DIM &&
+ slots >= 1 && slots <= MP_RING_SLOTS && !fstat(fd, &st))
+ need = (size_t)w * (size_t)h * 4 * (size_t)slots;
+ void *m = s && need && (size_t)st.st_size >= need ? mmap(NULL, need, PROT_READ, MAP_SHARED, fd, 0) : MAP_FAILED;
+ close(fd);
+ if (m == MAP_FAILED) return;
+ if (s->map) munmap(s->map, s->map_len);
+ s->map = m;
+ s->map_len = need;
+ s->ring_gen = gen;
+ s->ring_w = w;
+ s->ring_h = h;
+ s->ring_slots = slots;
+ s->cur_slot = -1;
+}
+
+static void close_local(ACam *a) {
+ MediaSrc *s = media_src_get(a->local);
+ if (s) media_src_close(s); /* unmaps the ring; there is no helper here */
+ a->used = 0;
+}
+
+void js_brokercam_event(const char *data, size_t len) {
+ char buf[1100];
+ if (len >= sizeof buf) return;
+ memcpy(buf, data, len);
+ buf[len] = 0;
+ char what[16] = "";
+ int sid = 0;
+ if (sscanf(buf, "%15s %d", what, &sid) != 2) return;
+ ACam *a = by_sid(sid);
+ if (!a) return;
+ MediaSrc *s = media_src_get(a->local);
+ if (!s) { a->used = 0; return; }
+ if (!strcmp(what, "ring")) { fetch_ring(a); return; }
+ if (!strcmp(what, "frame")) {
+ unsigned id = 0;
+ sscanf(buf, "%*s %*d %u", &id);
+ int gen = (int)(id >> 8), slot = (int)(id & 0xff);
+ if (gen != s->ring_gen) fetch_ring(a);
+ if (!s->map || gen != s->ring_gen || slot >= s->ring_slots) return;
+ s->cur_slot = slot;
+ s->w = s->ring_w;
+ s->h = s->ring_h;
+ s->frame_seq++;
+ media_src_damage(s);
+ char p[48];
+ int n = snprintf(p, sizeof p, "ack %d %u", sid, id);
+ js_broker_send(BOP_CAMERA, p, (uint32_t)n);
+ /* lord-media scales to the box where it is shown (as MM_SIZE does in the session) */
+ int bw = s->box_w, bh = s->box_h;
+ if (bw > 0 && bh > 0 && (bw != a->sent_w || bh != a->sent_h) && !s->view.zoom && !s->view.fit) {
+ int rw = (s->view.rot % 180) ? bh : bw, rh = (s->view.rot % 180) ? bw : bh;
+ n = snprintf(p, sizeof p, "size %d %d %d", sid, rw, rh);
+ if (!js_broker_send(BOP_CAMERA, p, (uint32_t)n)) { a->sent_w = bw; a->sent_h = bh; }
+ }
+ return;
+ }
+ if (!strcmp(what, "event")) {
+ char type[16] = "";
+ int off = 0;
+ if (sscanf(buf, "%*s %*d %15s %n", type, &off) < 1 || !off) return;
+ js_media_event(a->local, type, buf + off);
+ return;
+ }
+ if (!strcmp(what, "closed")) {
+ int revoked = strstr(buf, "revoked") != NULL;
+ js_media_event(a->local, "closed", revoked ? "{\"crashed\":false,\"revoked\":true}" : "{\"crashed\":false}");
+ close_local(a);
+ }
+}
+
+/* ---- lord.media (camera subset) ---- */
+
+static int arg_id(JSContext *c, JSValueConst v) { int32_t id = 0; JS_ToInt32(c, &id, v); return id; }
+
+static int opt_int(JSContext *c, JSValueConst o, const char *k, int def, int lo, int hi) {
+ if (!JS_IsObject(o)) return def;
+ JSValue v = JS_GetPropertyStr(c, o, k);
+ double d = def;
+ if (JS_IsNumber(v)) JS_ToFloat64(c, &d, v);
+ else if (JS_IsBool(v)) d = JS_ToBool(c, v);
+ JS_FreeValue(c, v);
+ if (!(d >= lo)) d = lo;
+ if (d > hi) d = hi;
+ return (int)d;
+}
+
+static JSValue f_cameras(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ int st = BST_ERROR;
+ char *out = NULL;
+ uint32_t len = 0;
+ if (js_broker_rpc(BOP_CAMERA, "list", 4, &st, &out, &len) || st != BST_OK || !out) { free(out); return JS_NewArray(c); }
+ JSValue v = JS_ParseJSON(c, out, len, "<cameras>");
+ free(out);
+ if (JS_IsException(v)) { JS_FreeValue(c, JS_GetException(c)); return JS_NewArray(c); }
+ return v;
+}
+
+/* camera(app, '/dev/videoN', { width, height }) → id (lord-server checks the permission) */
+static JSValue f_camera(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *dev = argc > 1 ? JS_ToCString(c, argv[1]) : NULL;
+ JSValueConst o = argc > 2 ? argv[2] : JS_UNDEFINED;
+ ACam *a = NULL;
+ for (int i = 0; i < MAX_ACAMS && !a; i++) if (!acams[i].used) a = &acams[i];
+ char p[96];
+ int n = dev && a ? snprintf(p, sizeof p, "open %.40s %d %d", dev, opt_int(c, o, "width", 1280, 160, 3840), opt_int(c, o, "height", 720, 120, 2160)) : -1;
+ if (dev) JS_FreeCString(c, dev);
+ if (n <= 0) return JS_ThrowTypeError(c, "invalid camera");
+ int st = BST_ERROR;
+ char *out = NULL;
+ uint32_t len = 0;
+ if (js_broker_rpc(BOP_CAMERA, p, (uint32_t)n, &st, &out, &len) || st != BST_OK || !out) {
+ free(out);
+ return st == BST_DENIED ? JS_ThrowTypeError(c, "camera permission denied") : JS_ThrowRangeError(c, "could not open the camera");
+ }
+ int sid = atoi(out);
+ free(out);
+ MediaSrc *s = media_src_new(SK_CAMERA, "app");
+ if (!s) { cmd("close %d%s", sid, NULL, NULL); return JS_ThrowRangeError(c, "too many media"); }
+ *a = (ACam){ .used = 1, .sid = sid, .local = s->id };
+ return JS_NewInt32(c, s->id);
+}
+
+static JSValue f_close(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ ACam *a = argc ? by_local(arg_id(c, argv[0])) : NULL;
+ if (a) { cmd("close %d%s", a->sid, NULL, NULL); close_local(a); }
+ return JS_UNDEFINED;
+}
+
+/* view(id, { fit, zoom, rotate, mirror, background }): how <MediaView> draws it (local) */
+static JSValue f_view(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ MediaSrc *s = argc >= 2 && by_local(arg_id(c, argv[0])) ? media_src_get(arg_id(c, argv[0])) : NULL;
+ if (!s || !JS_IsObject(argv[1])) return JS_FALSE;
+ MediaView v = s->view;
+ JSValue fit = JS_GetPropertyStr(c, argv[1], "fit");
+ if (JS_IsString(fit)) { const char *f = JS_ToCString(c, fit); if (f) { v.fit = !strcmp(f, "cover"); JS_FreeCString(c, f); } }
+ JS_FreeValue(c, fit);
+ int rot = ((opt_int(c, argv[1], "rotate", v.rot, -3600, 3600) % 360) + 360) % 360;
+ v.rot = rot - rot % 90;
+ v.mirror = opt_int(c, argv[1], "mirror", v.mirror, 0, 1);
+ JSValue bg = JS_GetPropertyStr(c, argv[1], "background");
+ if (JS_IsNumber(bg)) { double d; JS_ToFloat64(c, &d, bg); v.bg = (uint32_t)(int64_t)d; }
+ JS_FreeValue(c, bg);
+ v.gen = s->view.gen + 1;
+ s->view = v;
+ media_src_damage(s);
+ return JS_TRUE;
+}
+
+static JSValue f_info(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ ACam *a = argc ? by_local(arg_id(c, argv[0])) : NULL;
+ MediaSrc *s = a ? media_src_get(a->local) : NULL;
+ if (!s) return JS_NULL;
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyStr(c, o, "kind", JS_NewString(c, "camera"));
+ JS_SetPropertyStr(c, o, "width", JS_NewInt32(c, s->ring_w));
+ JS_SetPropertyStr(c, o, "height", JS_NewInt32(c, s->ring_h));
+ JS_SetPropertyStr(c, o, "alive", JS_TRUE);
+ return o;
+}
+
+/* photo(id, suggestedName, mirror) → true: the system's save dialog opens; "photo" arrives later */
+static JSValue f_photo(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ ACam *a = argc >= 2 ? by_local(arg_id(c, argv[0])) : NULL;
+ if (!a) return JS_FALSE;
+ const char *name = JS_IsString(argv[1]) ? JS_ToCString(c, argv[1]) : NULL;
+ char rest[300];
+ snprintf(rest, sizeof rest, "%d %.250s", argc > 2 && JS_ToBool(c, argv[2]), name ? name : "foto.jpg");
+ if (name) JS_FreeCString(c, name);
+ return JS_NewBool(c, cmd("photo %d %s", a->sid, rest, NULL));
+}
+
+/* cameraRecord(id, suggestedName | null, { mic, mirror }) → true; null ends it ("video" arrives) */
+static JSValue f_camera_record(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ ACam *a = argc >= 2 ? by_local(arg_id(c, argv[0])) : NULL;
+ if (!a) return JS_FALSE;
+ if (JS_IsNull(argv[1]) || JS_IsUndefined(argv[1])) return JS_NewBool(c, cmd("recstop %d%s", a->sid, NULL, NULL));
+ JSValueConst o = argc > 2 ? argv[2] : JS_UNDEFINED;
+ const char *name = JS_IsString(argv[1]) ? JS_ToCString(c, argv[1]) : NULL;
+ char rest[300];
+ snprintf(rest, sizeof rest, "%d %d %.250s", opt_int(c, o, "mirror", 0, 0, 1), opt_int(c, o, "mic", 1, 0, 1), name ? name : "video.mp4");
+ if (name) JS_FreeCString(c, name);
+ return JS_NewBool(c, cmd("record %d %s", a->sid, rest, NULL));
+}
+
+static JSValue f_stop(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ ACam *a = argc ? by_local(arg_id(c, argv[0])) : NULL;
+ return JS_NewBool(c, a && cmd("recstop %d%s", a->sid, NULL, NULL));
+}
+
+static JSValue f_zero(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; (void)argc; (void)argv; return JS_NewInt32(c, 0); }
+static JSValue f_none(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; (void)argc; (void)argv; return JS_NewString(c, "none"); }
+
+static const JSCFunctionListEntry funcs[] = {
+ JS_CFUNC_DEF("cameras", 0, f_cameras), JS_CFUNC_DEF("camera", 3, f_camera), JS_CFUNC_DEF("close", 1, f_close),
+ JS_CFUNC_DEF("view", 2, f_view), JS_CFUNC_DEF("info", 1, f_info), JS_CFUNC_DEF("photo", 3, f_photo),
+ JS_CFUNC_DEF("cameraRecord", 3, f_camera_record), JS_CFUNC_DEF("stop", 1, f_stop),
+ JS_CFUNC_DEF("protectedCount", 0, f_zero), JS_CFUNC_DEF("hwaccel", 0, f_none),
+};
+
+void js_brokercam_register(JSContext *c, JSValue lord) {
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyFunctionList(c, o, funcs, sizeof funcs / sizeof funcs[0]);
+ JS_SetPropertyStr(c, lord, "media", o);
+}
diff --git a/server/src/ui/js_disk.c b/server/src/ui/js_disk.c
index 689655d..86d1ea0 100644
--- a/server/src/ui/js_disk.c
+++ b/server/src/ui/js_disk.c
@@ -1,10 +1,11 @@
-/* js_disk.c — lord.disks: discos y particiones para la app Discos (ver docs/SISTEMA.md).
+/* js_disk.c — lord.disks: disks and partitions for the Disks app (see docs/SYSTEM.md).
*
- * Solo lectura y sin root (disk/disk.c). Lo que cambia algo va por el ayudante (acciones disk-*).
+ * Read-only and without root (disk/disk.c). Anything that changes something goes through the
+ * helper (disk-* actions).
* list() [{ name, model, size, transport, removable, system, table, partitions: […] }]
- * tools() { fat32, exfat, ext4, ntfs }: qué formatos se pueden crear en este equipo
- * watch(on) avisos de cambios mientras la app está abierta: __lordDisks('change') cuando
- * se monta, se desmonta, se enchufa o cambia un disco (mountinfo + udev, sin sondeo) */
+ * tools() { fat32, exfat, ext4, ntfs }: which formats can be created on this machine
+ * watch(on) change notifications while the app is open: __lordDisks('change') when a disk is
+ * mounted, unmounted, plugged in or changed (mountinfo + udev, no polling) */
#include "js_disk.h"
#include "../disk/disk.h"
diff --git a/server/src/ui/js_disk.h b/server/src/ui/js_disk.h
index 437471e..e431573 100644
--- a/server/src/ui/js_disk.h
+++ b/server/src/ui/js_disk.h
@@ -1,4 +1,4 @@
-/* js_disk.h — lord.disks (app Discos; ver js_disk.c). */
+/* js_disk.h — lord.disks (Disks app; see js_disk.c). */
#ifndef LORD_JS_DISK_H
#define LORD_JS_DISK_H
diff --git a/server/src/ui/js_help.c b/server/src/ui/js_help.c
index 1ee4d7c..0096705 100644
--- a/server/src/ui/js_help.c
+++ b/server/src/ui/js_help.c
@@ -1,12 +1,13 @@
-/* js_help.c — lord.help (artículos de la app Ayuda) y lord.time.zoneOffset (app Reloj).
- * Ver docs/SISTEMA.md.
+/* js_help.c — lord.help (Help app articles) and lord.time.zoneOffset (Clock app).
+ * See docs/SYSTEM.md.
*
- * lord.help.list(idioma) → [{ id, title, app, section, keywords }] de los .md de assets/help/<idioma>
- * lord.help.read(idioma, id) → texto del artículo, o null
- * lord.time.zoneOffset(zona, segundosUnix) → { offset, abbr, dst } o null (TZif propio, tzif.c)
+ * lord.help.list(lang) → [{ id, title, app, section, order, keywords }] of the .md files in assets/help/<lang>
+ * lord.help.read(lang, id) → the article text, or null
+ * lord.time.zoneOffset(zone, unixSeconds) → { offset, abbr, dst } or null (our own TZif reader, tzif.c)
*
- * Solo lectura y solo de la carpeta assets/help de LordOS: el idioma y el id se validan
- * ([a-z0-9-], sin puntos ni barras), así que no se puede salir de ahí. */
+ * Read-only and only from LordOS's assets/help folder: the language and the id are validated
+ * ([a-z0-9-], no dots or slashes), so nothing outside it can be reached. English (assets/help/en)
+ * is the default; the SDK (sdk/help.js) falls back to it when an article is not translated. */
#include "js_help.h"
#include "js_sys.h"
#include "tzif.h"
@@ -21,7 +22,7 @@
#include <sys/stat.h>
#include <unistd.h>
-#define HELP_MAX (256 * 1024) /* un artículo */
+#define HELP_MAX (256 * 1024) /* one article */
static int valid_part(const char *s, size_t max) {
size_t n = s ? strlen(s) : 0;
@@ -53,7 +54,7 @@ static char *read_article(const char *lang, const char *id, size_t *len) {
return buf;
}
-/* valor de "clave: valor" en el encabezado --- … --- */
+/* value of "key: value" in the --- … --- header */
static void front(const char *txt, const char *key, char *out, size_t n) {
out[0] = 0;
if (strncmp(txt, "---\n", 4)) return;
@@ -144,7 +145,7 @@ void js_help_register(JSContext *c, JSValue lord) {
JSValue o = JS_NewObject(c);
JS_SetPropertyFunctionList(c, o, help_funcs, sizeof help_funcs / sizeof help_funcs[0]);
JS_SetPropertyStr(c, lord, "help", o);
- /* lord.time ya lo creó js_sys_register: se le agrega zoneOffset */
+ /* lord.time was already created by js_sys_register: zoneOffset is added to it */
JSValue time = JS_GetPropertyStr(c, lord, "time");
if (JS_IsObject(time)) JS_SetPropertyStr(c, time, "zoneOffset", JS_NewCFunction(c, f_zone_offset, "zoneOffset", 2));
JS_FreeValue(c, time);
diff --git a/server/src/ui/js_help.h b/server/src/ui/js_help.h
index 6f000cb..9377e20 100644
--- a/server/src/ui/js_help.h
+++ b/server/src/ui/js_help.h
@@ -1,10 +1,10 @@
-/* js_help.h — lord.help (artículos de Ayuda) y lord.time.zoneOffset (Reloj). Ver js_help.c. */
+/* js_help.h — lord.help (Help articles) and lord.time.zoneOffset (Clock). See js_help.c. */
#ifndef LORD_JS_HELP_H
#define LORD_JS_HELP_H
#include "quickjs.h"
-/* Después de js_sys_register (agrega zoneOffset al lord.time que crea). */
+/* Call after js_sys_register (it adds zoneOffset to the lord.time object that one creates). */
void js_help_register(JSContext *c, JSValue lord);
#endif
diff --git a/server/src/ui/js_hw.c b/server/src/ui/js_hw.c
new file mode 100644
index 0000000..27bd660
--- /dev/null
+++ b/server/src/ui/js_hw.c
@@ -0,0 +1,312 @@
+/* js_hw.c — lord.display, lord.power, lord.bt, lord.mime and lord.timedate for Settings'
+ * hardware pages (src/hw, docs/SETTINGS.md). Every input is validated here; nothing runs a
+ * program (root work goes through the admin helper's closed actions, hw/hw_admin.c). Notices
+ * arrive in JS as __lordHw(kind, data).
+ *
+ * lord.display.list() outputs, modes, Night Shift, backlight
+ * lord.display.apply(conn, w, h, mHz, rot) live (queued between frames); true if accepted
+ * lord.display.save(conn) keep the current mode for that display
+ * lord.display.setTemperature(K) / temperature()
+ * lord.display.sun(zone, y, m, d) { rise, set } minutes UTC, or null
+ * lord.display.setIdle(offS, lockS, sleepS) / wake()
+ * lord.power.state() / profiles() / setProfile(p) / buttons()
+ * lord.bt.state() / power(on) / discover(on) / pair(path) / connect(path) / disconnect(path)
+ * / forget(path) / answer(id, accept, value)
+ * lord.mime.get(mime) / set(mime, id) / guess(path) / terminal() / setTerminal(id)
+ * lord.timedate.refresh() answer as __lordHw('timedate', …)
+ * lord.notifyd.closed(id, reason) / action(id, key) back to the Linux app that notified
+ */
+#include "js_hw.h"
+#include "../hw/bt.h"
+#include "../hw/defaults.h"
+#include "../hw/display.h"
+#include "../hw/hw.h"
+#include "../hw/mimeapps.h"
+#include "../hw/notifyd.h"
+#include "../hw/ppd.h"
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static JSValue json_or_null(JSContext *c, char *j) {
+ if (!j) return JS_NULL;
+ JSValue v = JS_ParseJSON(c, j, strlen(j), "<hw>");
+ free(j);
+ return v;
+}
+
+static int arg_int(JSContext *c, JSValueConst v, int def) {
+ int32_t x;
+ return JS_ToInt32(c, &x, v) ? def : x;
+}
+
+/* A short string argument (≤ max bytes) copied into out. 0 if valid. */
+static int arg_str(JSContext *c, JSValueConst v, char *out, size_t max) {
+ size_t n;
+ const char *s = JS_ToCStringLen(c, &n, v);
+ if (!s) return -1;
+ int ok = n < max && !memchr(s, 0, n);
+ if (ok) memcpy(out, s, n + 1);
+ JS_FreeCString(c, s);
+ return ok ? 0 : -1;
+}
+
+/* ---- lord.display ---- */
+
+static JSValue f_display_list(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return json_or_null(c, display_list_json());
+}
+
+static JSValue f_display_apply(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ if (argc < 5) return JS_FALSE;
+ int conn = arg_int(c, argv[0], 0), w = arg_int(c, argv[1], 0), h = arg_int(c, argv[2], 0);
+ int hz = arg_int(c, argv[3], 0), rot = arg_int(c, argv[4], 0);
+ if (conn <= 0 || w < 0 || h < 0 || w > 16384 || h > 16384 || hz < 0 || hz > 1000000 || rot < 0 || rot > 3) return JS_FALSE;
+ return JS_NewBool(c, display_request((uint32_t)conn, w, h, hz, rot) == 0);
+}
+
+static JSValue f_display_save(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int conn = argc ? arg_int(c, argv[0], 0) : 0;
+ return JS_NewBool(c, conn > 0 && display_save((uint32_t)conn) == 0);
+}
+
+static JSValue f_display_set_temp(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int k = argc ? arg_int(c, argv[0], 6500) : 6500;
+ display_set_temperature(k);
+ return JS_UNDEFINED;
+}
+
+static JSValue f_display_temp(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return JS_NewInt32(c, display_temperature());
+}
+
+static JSValue f_display_sun(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char zone[96];
+ if (argc < 4 || arg_str(c, argv[0], zone, sizeof zone)) return JS_NULL;
+ int y = arg_int(c, argv[1], 0), m = arg_int(c, argv[2], 0), d = arg_int(c, argv[3], 0);
+ double rise, set;
+ if (y < 1970 || y > 2200 || m < 1 || m > 12 || d < 1 || d > 31 || display_sun(zone, y, m, d, &rise, &set)) return JS_NULL;
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyStr(c, o, "rise", JS_NewFloat64(c, rise));
+ JS_SetPropertyStr(c, o, "set", JS_NewFloat64(c, set));
+ return o;
+}
+
+static JSValue f_display_idle(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int v[3] = { 0, 0, 0 };
+ for (int i = 0; i < 3 && i < argc; i++) { v[i] = arg_int(c, argv[i], 0); if (v[i] < 0 || v[i] > 86400) v[i] = 0; }
+ display_set_idle(v[0], v[1], v[2]);
+ return JS_UNDEFINED;
+}
+
+static JSValue f_display_wake(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)c; (void)t; (void)argc; (void)argv;
+ display_wake();
+ return JS_UNDEFINED;
+}
+
+static const JSCFunctionListEntry display_funcs[] = {
+ JS_CFUNC_DEF("list", 0, f_display_list),
+ JS_CFUNC_DEF("apply", 5, f_display_apply),
+ JS_CFUNC_DEF("save", 1, f_display_save),
+ JS_CFUNC_DEF("setTemperature", 1, f_display_set_temp),
+ JS_CFUNC_DEF("temperature", 0, f_display_temp),
+ JS_CFUNC_DEF("sun", 4, f_display_sun),
+ JS_CFUNC_DEF("setIdle", 3, f_display_idle),
+ JS_CFUNC_DEF("wake", 0, f_display_wake),
+};
+
+/* ---- lord.power ---- */
+
+static JSValue f_power_state(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char j[4096];
+ power_json(hw_power(), j, sizeof j);
+ return JS_ParseJSON(c, j, strlen(j), "<power>");
+}
+
+static JSValue f_power_profiles(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return json_or_null(c, ppd_state_json());
+}
+
+static JSValue f_power_set_profile(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char p[24];
+ if (!argc || arg_str(c, argv[0], p, sizeof p) || !ppd_profile_valid(p)) return JS_FALSE;
+ return JS_NewBool(c, ppd_set(p) == 0);
+}
+
+/* What logind does with the power button and the lid: our drop-in if it exists, else logind's
+ * defaults (poweroff, suspend, suspend). Read-only; changed by the power-buttons action. */
+static JSValue f_power_buttons(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char power[16] = "poweroff", lid[16] = "suspend", lidac[16] = "", buf[1024];
+ const char *files[] = { "/etc/systemd/logind.conf", "/etc/systemd/logind.conf.d/lordos.conf" };
+ for (int f = 0; f < 2; f++) {
+ int fd = open(files[f], O_RDONLY | O_CLOEXEC);
+ if (fd < 0) continue;
+ ssize_t r = read(fd, buf, sizeof buf - 1);
+ close(fd);
+ if (r <= 0) continue;
+ buf[r] = 0;
+ for (char *line = strtok(buf, "\n"); line; line = strtok(NULL, "\n")) {
+ char v[16];
+ if (sscanf(line, "HandlePowerKey=%15s", v) == 1) snprintf(power, sizeof power, "%s", v);
+ else if (sscanf(line, "HandleLidSwitchExternalPower=%15s", v) == 1) snprintf(lidac, sizeof lidac, "%s", v);
+ else if (sscanf(line, "HandleLidSwitch=%15s", v) == 1) snprintf(lid, sizeof lid, "%s", v);
+ }
+ }
+ if (!lidac[0]) snprintf(lidac, sizeof lidac, "%s", lid); /* logind: unset = same as HandleLidSwitch */
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyStr(c, o, "power", JS_NewString(c, power));
+ JS_SetPropertyStr(c, o, "lid", JS_NewString(c, lid));
+ JS_SetPropertyStr(c, o, "lidAC", JS_NewString(c, lidac));
+ return o;
+}
+
+static const JSCFunctionListEntry power_funcs[] = {
+ JS_CFUNC_DEF("state", 0, f_power_state),
+ JS_CFUNC_DEF("profiles", 0, f_power_profiles),
+ JS_CFUNC_DEF("setProfile", 1, f_power_set_profile),
+ JS_CFUNC_DEF("buttons", 0, f_power_buttons),
+};
+
+/* ---- lord.bt ---- */
+
+static JSValue f_bt_state(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return json_or_null(c, bt_state_json());
+}
+
+static JSValue f_bt_flag(JSContext *c, JSValueConst t, int argc, JSValueConst *argv, int magic) {
+ (void)t;
+ int on = argc && JS_ToBool(c, argv[0]) == 1;
+ return JS_NewBool(c, (magic ? bt_discover(on) : bt_power(on)) == 0);
+}
+
+static JSValue f_bt_dev(JSContext *c, JSValueConst t, int argc, JSValueConst *argv, int magic) {
+ (void)t;
+ char path[128];
+ if (!argc || arg_str(c, argv[0], path, sizeof path) || !bt_path_valid(path)) return JS_FALSE;
+ int r = magic == 0 ? bt_pair(path) : magic == 1 ? bt_connect(path) : magic == 2 ? bt_disconnect(path) : bt_forget(path);
+ return JS_NewBool(c, r == 0);
+}
+
+static JSValue f_bt_answer(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ if (argc < 2) return JS_FALSE;
+ int id = arg_int(c, argv[0], -1), accept = JS_ToBool(c, argv[1]) == 1;
+ char value[24] = "";
+ if (argc > 2 && !JS_IsUndefined(argv[2]) && !JS_IsNull(argv[2]) && arg_str(c, argv[2], value, sizeof value)) return JS_FALSE;
+ return JS_NewBool(c, bt_answer(id, accept, value) == 0);
+}
+
+static const JSCFunctionListEntry bt_funcs[] = {
+ JS_CFUNC_DEF("state", 0, f_bt_state),
+ JS_CFUNC_MAGIC_DEF("power", 1, f_bt_flag, 0),
+ JS_CFUNC_MAGIC_DEF("discover", 1, f_bt_flag, 1),
+ JS_CFUNC_MAGIC_DEF("pair", 1, f_bt_dev, 0),
+ JS_CFUNC_MAGIC_DEF("connect", 1, f_bt_dev, 1),
+ JS_CFUNC_MAGIC_DEF("disconnect", 1, f_bt_dev, 2),
+ JS_CFUNC_MAGIC_DEF("forget", 1, f_bt_dev, 3),
+ JS_CFUNC_DEF("answer", 3, f_bt_answer),
+};
+
+/* ---- lord.mime ---- */
+
+static JSValue f_mime_get(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char mime[MIME_MAX], id[DESKTOP_ID_MAX];
+ if (!argc || arg_str(c, argv[0], mime, sizeof mime) || !mime_valid(mime) || defaults_lookup(mime, id, sizeof id)) return JS_NULL;
+ return JS_NewString(c, id);
+}
+
+static JSValue f_mime_set(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char mime[MIME_MAX], id[DESKTOP_ID_MAX];
+ if (argc < 2 || arg_str(c, argv[0], mime, sizeof mime) || arg_str(c, argv[1], id, sizeof id)) return JS_FALSE;
+ return JS_NewBool(c, mime_valid(mime) && desktop_id_valid(id) && defaults_set(mime, id) == 0);
+}
+
+static JSValue f_mime_guess(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char path[1024], mime[MIME_MAX];
+ if (!argc || arg_str(c, argv[0], path, sizeof path) || defaults_guess(path, mime, sizeof mime)) return JS_NULL;
+ return JS_NewString(c, mime);
+}
+
+static JSValue f_mime_terminal(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char id[DESKTOP_ID_MAX];
+ return defaults_terminal(id, sizeof id) ? JS_NULL : JS_NewString(c, id);
+}
+
+static JSValue f_mime_set_terminal(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char id[DESKTOP_ID_MAX];
+ if (!argc || arg_str(c, argv[0], id, sizeof id) || !desktop_id_valid(id)) return JS_FALSE;
+ return JS_NewBool(c, defaults_set_terminal(id) == 0);
+}
+
+static const JSCFunctionListEntry mime_funcs[] = {
+ JS_CFUNC_DEF("get", 1, f_mime_get),
+ JS_CFUNC_DEF("set", 2, f_mime_set),
+ JS_CFUNC_DEF("guess", 1, f_mime_guess),
+ JS_CFUNC_DEF("terminal", 0, f_mime_terminal),
+ JS_CFUNC_DEF("setTerminal", 1, f_mime_set_terminal),
+};
+
+/* ---- lord.timedate ---- */
+
+static JSValue f_td_refresh(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)c; (void)t; (void)argc; (void)argv;
+ hw_timedate_refresh();
+ return JS_UNDEFINED;
+}
+
+static const JSCFunctionListEntry td_funcs[] = { JS_CFUNC_DEF("refresh", 0, f_td_refresh) };
+
+/* ---- lord.notifyd (Linux apps' notifications, hw/notifyd.c) ---- */
+
+static JSValue f_nd_closed(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int id = argc ? arg_int(c, argv[0], 0) : 0, reason = argc > 1 ? arg_int(c, argv[1], 2) : 2;
+ if (id > 0) notifyd_closed((uint32_t)id, (uint32_t)reason);
+ return JS_UNDEFINED;
+}
+
+static JSValue f_nd_action(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char key[129];
+ int id = argc ? arg_int(c, argv[0], 0) : 0;
+ if (id > 0 && argc > 1 && !arg_str(c, argv[1], key, sizeof key)) notifyd_action((uint32_t)id, key);
+ return JS_UNDEFINED;
+}
+
+static const JSCFunctionListEntry nd_funcs[] = { JS_CFUNC_DEF("closed", 2, f_nd_closed), JS_CFUNC_DEF("action", 2, f_nd_action) };
+
+static void add(JSContext *c, JSValue lord, const char *name, const JSCFunctionListEntry *f, int n) {
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyFunctionList(c, o, f, n);
+ JS_SetPropertyStr(c, lord, name, o);
+}
+
+void js_hw_register(JSContext *c, JSValue lord) {
+ add(c, lord, "display", display_funcs, sizeof display_funcs / sizeof display_funcs[0]);
+ add(c, lord, "power", power_funcs, sizeof power_funcs / sizeof power_funcs[0]);
+ add(c, lord, "bt", bt_funcs, sizeof bt_funcs / sizeof bt_funcs[0]);
+ add(c, lord, "mime", mime_funcs, sizeof mime_funcs / sizeof mime_funcs[0]);
+ add(c, lord, "timedate", td_funcs, sizeof td_funcs / sizeof td_funcs[0]);
+ add(c, lord, "notifyd", nd_funcs, sizeof nd_funcs / sizeof nd_funcs[0]);
+}
diff --git a/server/src/ui/js_hw.h b/server/src/ui/js_hw.h
new file mode 100644
index 0000000..bdcf81e
--- /dev/null
+++ b/server/src/ui/js_hw.h
@@ -0,0 +1,9 @@
+/* js_hw.h — lord.display, lord.power, lord.bt, lord.mime, lord.timedate (see js_hw.c). */
+#ifndef LORD_JS_HW_H
+#define LORD_JS_HW_H
+
+#include "quickjs.h"
+
+void js_hw_register(JSContext *c, JSValue lord);
+
+#endif
diff --git a/server/src/ui/js_logs.c b/server/src/ui/js_logs.c
index 837bd32..a29730c 100644
--- a/server/src/ui/js_logs.c
+++ b/server/src/ui/js_logs.c
@@ -1,4 +1,4 @@
-/* js_logs.c — lord.logs: los registros para la app Registros (docs/SISTEMA.md).
+/* js_logs.c — lord.logs: los registros para la app Registros (docs/SYSTEM.md).
*
* Todo es de solo lectura y como el usuario de la sesión: los archivos del journal que el kernel y
* las ACL de journald le dejan leer (su user-<uid>.journal; el del sistema solo si está en
diff --git a/server/src/ui/js_logs.h b/server/src/ui/js_logs.h
index 661f6bd..a9fb336 100644
--- a/server/src/ui/js_logs.h
+++ b/server/src/ui/js_logs.h
@@ -1,4 +1,4 @@
-/* js_logs.h — lord.logs (app Registros; ver js_logs.c y docs/SISTEMA.md). */
+/* js_logs.h — lord.logs (app Registros; ver js_logs.c y docs/SYSTEM.md). */
#ifndef LORD_JS_LOGS_H
#define LORD_JS_LOGS_H
diff --git a/server/src/ui/js_mail.c b/server/src/ui/js_mail.c
new file mode 100644
index 0000000..15ac750
--- /dev/null
+++ b/server/src/ui/js_mail.c
@@ -0,0 +1,258 @@
+/* js_mail.c — lord.mail: Mail, Calendar, Contacts and Reminders through the sandboxed helper
+ * lord-maild (server/src/mail, docs/MAIL.md). Here we only validate arguments, open the files
+ * the user picked and write the accounts file; IMAP, SMTP, CalDAV, CardDAV, MIME and HTML are
+ * handled in lord-maild. Everything is asynchronous: request() returns an id and results arrive
+ * through poll().
+ *
+ * available() is lord-maild installed?
+ * start() starts it (it stays up for new-mail notifications)
+ * request(json, [paths]) → id; paths: files to attach or a contact photo (home or media only)
+ * poll() → [{id, type: done|err|evt|crash, data}] or null
+ * pending()
+ * config() → the accounts file text ("" if none). Never holds passwords.
+ * saveConfig(json) writes ~/.config/lordos/mail/accounts.json (validated JSON,
+ * ≤ 512 KB, 0600, atomic) and reloads the allowed servers
+ * allowImages([urls]) lets lord-maild reach these image hosts for 10 minutes
+ * bind(node, image) / release(image)
+ * cacheDir() ~/.local/share/lordos/mail (attachments saved for opening)
+ */
+#include "js_mail.h"
+#include "js_sys.h"
+#include "ui.h"
+#include "../mail/mailc.h"
+#include "../mail/proto.h"
+#include "../sec/json.h"
+#include "../fsops.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define MAIL_REQ_MAX (24u << 20)
+
+static const char *arg_str(JSContext *c, int argc, JSValueConst *argv, int i, size_t *len) {
+ if (i >= argc || !JS_IsString(argv[i])) return NULL;
+ return JS_ToCStringLen(c, len, argv[i]);
+}
+
+static int arg_int(JSContext *c, int argc, JSValueConst *argv, int i, int def) {
+ int32_t v = def;
+ if (i < argc && JS_IsNumber(argv[i])) JS_ToInt32(c, &v, argv[i]);
+ return v;
+}
+
+/* A file the user picked: relative to home or absolute, real, inside the allowed roots. */
+static int open_user_file(const char *path) {
+ char full[PATH_MAX * 2], real[PATH_MAX];
+ const char *h = getenv("HOME");
+ if (!path || !path[0]) return -1;
+ if (path[0] == '/') snprintf(full, sizeof full, "%s", path);
+ else if (h) snprintf(full, sizeof full, "%s/%s", h, path);
+ else return -1;
+ if (!realpath(full, real) || !fsops_allowed(real)) return -1;
+ int fd = open(real, O_RDONLY | O_CLOEXEC | O_NOCTTY | O_NONBLOCK);
+ if (fd < 0) return -1;
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size > (off_t)(64 << 20)) { close(fd); return -1; }
+ fcntl(fd, F_SETFL, 0);
+ return fd;
+}
+
+static JSValue f_available(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return JS_NewBool(c, mail_available() == 0);
+}
+
+static JSValue f_start(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return JS_NewBool(c, mail_start() == 0);
+}
+
+static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ size_t len = 0;
+ const char *j = arg_str(c, argc, argv, 0, &len);
+ if (!j) return JS_ThrowTypeError(c, "request(json, [paths])");
+ if (len > MAIL_REQ_MAX) { JS_FreeCString(c, j); return JS_ThrowRangeError(c, "request too big"); }
+ /* must be a JSON object with a short "op" */
+ JDoc d;
+ if (json_parse(j, len, &d, NULL, 0) || !d.root || d.root->type != J_OBJ || !json_str(d.root, "op") || strlen(json_str(d.root, "op")) > 32) {
+ if (d.root) json_free(&d);
+ JS_FreeCString(c, j);
+ return JS_ThrowTypeError(c, "request: invalid JSON");
+ }
+ json_free(&d);
+ int fds[15], nfds = 0;
+ if (argc > 1 && JS_IsArray(c, argv[1])) {
+ JSValue lv = JS_GetPropertyStr(c, argv[1], "length");
+ int32_t n = 0;
+ JS_ToInt32(c, &n, lv);
+ JS_FreeValue(c, lv);
+ if (n < 0 || n > 15) { JS_FreeCString(c, j); return JS_ThrowRangeError(c, "at most 15 files"); }
+ for (int i = 0; i < n; i++) {
+ JSValue pv = JS_GetPropertyUint32(c, argv[1], (uint32_t)i);
+ const char *p = JS_IsString(pv) ? JS_ToCString(c, pv) : NULL;
+ JS_FreeValue(c, pv);
+ int fd = open_user_file(p);
+ if (p) JS_FreeCString(c, p);
+ if (fd < 0) {
+ for (int k = 0; k < nfds; k++) close(fds[k]);
+ JS_FreeCString(c, j);
+ return JS_ThrowRangeError(c, "file outside the home folder or unreadable");
+ }
+ fds[nfds++] = fd;
+ }
+ }
+ int id = mail_request(j, len, fds, nfds);
+ JS_FreeCString(c, j);
+ return JS_NewInt32(c, id);
+}
+
+static JSValue f_poll(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char *s = mail_poll();
+ if (!s) return JS_NULL;
+ JSValue v = JS_ParseJSON(c, s, strlen(s), "<mail>");
+ free(s);
+ return v;
+}
+
+static JSValue f_pending(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return JS_NewInt32(c, mail_pending());
+}
+
+static JSValue f_config(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ int fd = open(mail_config_path(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ if (fd < 0) return JS_NewString(c, "");
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size > MAIL_CONFIG_MAX) { close(fd); return JS_NewString(c, ""); }
+ char *b = malloc((size_t)st.st_size + 1);
+ ssize_t r = b ? read(fd, b, (size_t)st.st_size) : -1;
+ close(fd);
+ if (r < 0) { free(b); return JS_NewString(c, ""); }
+ JSValue v = JS_NewStringLen(c, b, (size_t)r);
+ free(b);
+ return v;
+}
+
+static int mkdirs(const char *p) {
+ char tmp[PATH_MAX];
+ snprintf(tmp, sizeof tmp, "%s", p);
+ for (char *s = tmp + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(tmp, 0700); *s = '/'; }
+ return mkdir(tmp, 0700) && errno != EEXIST ? -1 : 0;
+}
+
+/* The accounts file holds security decisions (which servers lord-maild may reach, trusted
+ * certificate fingerprints): JS cannot write it through lord.fs (fsops_protected), only here. */
+static JSValue f_save_config(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ size_t len = 0;
+ const char *j = arg_str(c, argc, argv, 0, &len);
+ if (!j) return JS_ThrowTypeError(c, "saveConfig(json)");
+ JDoc d;
+ int bad = len > MAIL_CONFIG_MAX || json_parse(j, len, &d, NULL, 0);
+ if (!bad) {
+ const JVal *acc = json_get(d.root, "accounts");
+ bad = d.root->type != J_OBJ || (acc && (acc->type != J_ARR || acc->len > MAIL_MAX_ACCOUNTS));
+ /* no secrets in this file */
+ for (const JVal *a = acc ? acc->kid : NULL; !bad && a; a = a->next) if (json_get(a, "password") || json_get(a, "secret")) bad = 1;
+ json_free(&d);
+ }
+ if (bad) { JS_FreeCString(c, j); return JS_ThrowTypeError(c, "saveConfig: invalid accounts JSON"); }
+ char dir[PATH_MAX], tmp[PATH_MAX + 16];
+ snprintf(dir, sizeof dir, "%s", mail_config_path());
+ char *slash = strrchr(dir, '/');
+ if (slash) *slash = 0;
+ if (mkdirs(dir)) { JS_FreeCString(c, j); return JS_ThrowInternalError(c, "cannot create %s", dir); }
+ snprintf(tmp, sizeof tmp, "%s.tmp", mail_config_path());
+ int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);
+ int ok = fd >= 0 && write(fd, j, len) == (ssize_t)len && fsync(fd) == 0;
+ if (fd >= 0) close(fd);
+ ok = ok && rename(tmp, mail_config_path()) == 0;
+ if (!ok) unlink(tmp);
+ JS_FreeCString(c, j);
+ if (!ok) return JS_ThrowInternalError(c, "cannot write the accounts file");
+ mail_reload_config();
+ return JS_TRUE;
+}
+
+static JSValue f_allow_images(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ if (argc < 1 || !JS_IsArray(c, argv[0])) return JS_ThrowTypeError(c, "allowImages([urls])");
+ JSValue lv = JS_GetPropertyStr(c, argv[0], "length");
+ int32_t n = 0;
+ JS_ToInt32(c, &n, lv);
+ JS_FreeValue(c, lv);
+ if (n < 0) n = 0;
+ if (n > 200) n = 200;
+ const char *urls[200];
+ int k = 0;
+ for (int i = 0; i < n; i++) {
+ JSValue v = JS_GetPropertyUint32(c, argv[0], (uint32_t)i);
+ if (JS_IsString(v)) { const char *s = JS_ToCString(c, v); if (s) { if (strlen(s) < 2048) urls[k++] = s; else JS_FreeCString(c, s); } }
+ JS_FreeValue(c, v);
+ }
+ mail_allow_hosts(urls, k, 600);
+ for (int i = 0; i < k; i++) JS_FreeCString(c, urls[i]);
+ return JS_UNDEFINED;
+}
+
+static JSValue f_bind(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ Node *n = node_get(arg_int(c, argc, argv, 0, -1));
+ if (!n || n->type != NODE_IMAGE) return JS_FALSE;
+ int handle = arg_int(c, argc, argv, 1, 0);
+ if (handle <= 0) {
+ image_release(n->img);
+ n->img = NULL;
+ node_invalidate(n);
+ return JS_TRUE;
+ }
+ int w, h;
+ const uint32_t *px = mail_image_lock(handle, &w, &h);
+ if (!px) { mail_image_unlock(); return JS_FALSE; }
+ Image *img = image_argb(n->img, w, h, px);
+ mail_image_unlock();
+ if (!img) return JS_FALSE;
+ n->img = img;
+ node_invalidate(n);
+ return JS_TRUE;
+}
+
+static JSValue f_release(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ mail_image_release(arg_int(c, argc, argv, 0, 0));
+ return JS_UNDEFINED;
+}
+
+static JSValue f_cache_dir(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ return JS_NewString(c, mail_cache_path());
+}
+
+static const JSCFunctionListEntry mail_funcs[] = {
+ JS_CFUNC_DEF("available", 0, f_available),
+ JS_CFUNC_DEF("start", 0, f_start),
+ JS_CFUNC_DEF("request", 2, f_request),
+ JS_CFUNC_DEF("poll", 0, f_poll),
+ JS_CFUNC_DEF("pending", 0, f_pending),
+ JS_CFUNC_DEF("config", 0, f_config),
+ JS_CFUNC_DEF("saveConfig", 1, f_save_config),
+ JS_CFUNC_DEF("allowImages", 1, f_allow_images),
+ JS_CFUNC_DEF("bind", 2, f_bind),
+ JS_CFUNC_DEF("release", 1, f_release),
+ JS_CFUNC_DEF("cacheDir", 0, f_cache_dir),
+};
+
+void js_mail_register(JSContext *c, JSValue lord) {
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyFunctionList(c, o, mail_funcs, sizeof mail_funcs / sizeof mail_funcs[0]);
+ JS_SetPropertyStr(c, lord, "mail", o);
+}
diff --git a/server/src/ui/js_mail.h b/server/src/ui/js_mail.h
new file mode 100644
index 0000000..70fb0e5
--- /dev/null
+++ b/server/src/ui/js_mail.h
@@ -0,0 +1,9 @@
+/* js_mail.h — lord.mail: Mail, Calendar, Contacts and Reminders via lord-maild (see js_mail.c). */
+#ifndef LORD_JS_MAIL_H
+#define LORD_JS_MAIL_H
+
+#include "quickjs.h"
+
+void js_mail_register(JSContext *c, JSValue lord);
+
+#endif
diff --git a/server/src/ui/tzif.c b/server/src/ui/tzif.c
index 04a6f77..63936ea 100644
--- a/server/src/ui/tzif.c
+++ b/server/src/ui/tzif.c
@@ -1,6 +1,6 @@
-/* tzif.c — zonas horarias con código propio: archivos TZif (RFC 8536, versiones 1 a 4) y reglas
- * POSIX TZ (el pie de los TZif, para fechas después de la última transición). Ver tzif.h.
- * Todo se valida: un archivo corto o con índices fuera de rango devuelve -1, nunca lee de más. */
+/* tzif.c — time zones with our own code: TZif files (RFC 8536, versions 1 to 4) and POSIX TZ
+ * rules (the TZif footer, for dates after the last transition). See tzif.h.
+ * Everything is validated: a short file or out-of-range indices return -1, it never over-reads. */
#include "tzif.h"
#include <ctype.h>
@@ -15,9 +15,9 @@
static uint32_t be32(const uint8_t *p) { return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; }
static int64_t be64(const uint8_t *p) { return (int64_t)((uint64_t)be32(p) << 32 | be32(p + 4)); }
-/* ---- fechas ---- */
+/* ---- dates ---- */
-/* días desde 1970-01-01 (algoritmo de Howard Hinnant) */
+/* days since 1970-01-01 (Howard Hinnant's algorithm) */
static int64_t days_from_civil(int64_t y, int m, int d) {
y -= m <= 2;
int64_t era = (y >= 0 ? y : y - 399) / 400;
@@ -44,7 +44,7 @@ static int mdays(int64_t y, int m) {
return m == 2 && leap(y) ? 29 : d[m - 1];
}
-/* ---- reglas POSIX ---- */
+/* ---- POSIX rules ---- */
typedef struct { char kind; int a, b, c; int32_t time; } TzDate; /* 'J' n, 'D' n, 'M' m.w.d */
@@ -62,7 +62,7 @@ static const char *p_name(const char *s, char *out, size_t n) {
return k >= 1 ? s : NULL;
}
-/* [+-]hh[:mm[:ss]]; max: horas permitidas (24 para offsets, 167 para las horas de la regla) */
+/* [+-]hh[:mm[:ss]]; max: allowed hours (24 for offsets, 167 for rule times) */
static const char *p_time(const char *s, int32_t *out, int max) {
int sign = 1;
if (*s == '+') s++;
@@ -106,13 +106,13 @@ static const char *p_date(const char *s, TzDate *d) {
return s;
}
-/* Segundos desde 1970 del comienzo (00:00 local) del día que dice la regla en el año y. */
+/* Seconds since 1970 of the start (local 00:00) of the day the rule names in year y. */
static int64_t rule_day(const TzDate *d, int64_t y) {
int64_t jan1 = days_from_civil(y, 1, 1);
if (d->kind == 'J') return (jan1 + d->a - 1 + (leap(y) && d->a >= 60)) * 86400;
if (d->kind == 'D') return (jan1 + d->a) * 86400;
int64_t first = days_from_civil(y, d->a, 1);
- int wd = (int)(((first + 4) % 7 + 7) % 7); /* 1970-01-01 fue jueves */
+ int wd = (int)(((first + 4) % 7 + 7) % 7); /* 1970-01-01 was a Thursday */
int day = 1 + (d->c - wd + 7) % 7 + (d->b - 1) * 7;
while (day > mdays(y, d->a)) day -= 7;
return (first + day - 1) * 86400;
@@ -123,12 +123,12 @@ int tz_posix(const char *rule, int64_t t, TzInfo *out) {
int32_t stdoff, dstoff;
const char *s = rule ? p_name(rule, std, sizeof std) : NULL;
if (!s || !(s = p_time(s, &stdoff, 24))) return -1;
- stdoff = -stdoff; /* POSIX cuenta al oeste */
+ stdoff = -stdoff; /* POSIX counts westwards */
if (!*s) { *out = (TzInfo){ .utoff = stdoff }; snprintf(out->abbr, sizeof out->abbr, "%s", std); return 0; }
if (!(s = p_name(s, dst, sizeof dst))) return -1;
dstoff = stdoff + 3600;
if (*s && *s != ',') { if (!(s = p_time(s, &dstoff, 24))) return -1; dstoff = -dstoff; }
- TzDate a = { 'M', 3, 2, 0, 7200 }, b = { 'M', 11, 1, 0, 7200 }; /* por defecto, la de EE. UU. */
+ TzDate a = { 'M', 3, 2, 0, 7200 }, b = { 'M', 11, 1, 0, 7200 }; /* default: the US rule */
if (*s == ',') {
if (!(s = p_date(s + 1, &a)) || *s != ',' || !(s = p_date(s + 1, &b))) return -1;
}
@@ -136,12 +136,12 @@ int tz_posix(const char *rule, int64_t t, TzInfo *out) {
int64_t y = year_of(t + stdoff);
int in = 0;
for (int64_t yy = y - 1; yy <= y + 1 && !in; yy++) {
- /* el comienzo va en hora estándar y el fin en hora de verano */
+ /* the start is given in standard time and the end in daylight time */
int64_t start = rule_day(&a, yy) + a.time - stdoff;
int64_t end = rule_day(&b, yy) + b.time - dstoff;
if (start < end) in = t >= start && t < end;
else {
- /* hemisferio sur: el verano cruza el año; se mira el tramo de este año */
+ /* southern hemisphere: summer spans the new year; check this year's span */
int64_t next_end = rule_day(&b, yy + 1) + b.time - dstoff;
in = t >= start && t < next_end;
}
@@ -186,7 +186,7 @@ int tzif_lookup(const uint8_t *buf, size_t n, int64_t t, TzInfo *out) {
const uint8_t *p = buf + 44;
size_t rem = n - 44, len = block_len(&c, 0);
if (len > rem) return -1;
- if (v2) { /* se salta el bloque de 32 bits */
+ if (v2) { /* skip the 32-bit block */
p += len; rem -= len;
if (counts(p, rem, &c)) return -1;
p += 44; rem -= 44;
@@ -209,7 +209,7 @@ int tzif_lookup(const uint8_t *buf, size_t n, int64_t t, TzInfo *out) {
return 0;
}
if (t >= TT(c.time - 1) && footer && footer[0] && !tz_posix(footer, t, out)) return 0;
- uint32_t lo = 0, hi = c.time - 1; /* la última transición <= t */
+ uint32_t lo = 0, hi = c.time - 1; /* the last transition <= t */
while (lo < hi) {
uint32_t mid = lo + (hi - lo + 1) / 2;
if (TT(mid) <= t) lo = mid; else hi = mid - 1;
@@ -230,7 +230,7 @@ int tz_zone_offset(const char *zone, int64_t t, TzInfo *out) {
if (!tz_zone_valid(zone)) return -1;
char path[160];
snprintf(path, sizeof path, "/usr/share/zoneinfo/%s", zone);
- /* tzdata usa enlaces (Europe/Madrid → ../Europe/…): se siguen, pero sin salir de zoneinfo */
+ /* tzdata uses links: follow them, but never outside zoneinfo */
char real[PATH_MAX];
if (!realpath(path, real) || strncmp(real, "/usr/share/zoneinfo/", 20)) return -1;
int fd = open(real, O_RDONLY | O_CLOEXEC);
diff --git a/server/src/ui/tzif.h b/server/src/ui/tzif.h
index a548ae7..27ff4fc 100644
--- a/server/src/ui/tzif.h
+++ b/server/src/ui/tzif.h
@@ -1,6 +1,6 @@
-/* tzif.h — lector propio de zonas horarias (TZif de tzdata, RFC 8536, y reglas POSIX TZ).
- * Lo usa lord.time.zoneOffset (app Reloj, docs/SISTEMA.md) para saber la hora de otra ciudad sin
- * tocar la zona del proceso (setenv TZ cambiaría el Date de todo el tema). */
+/* tzif.h — our own time zone reader (tzdata TZif files, RFC 8536, and POSIX TZ rules).
+ * Used by lord.time.zoneOffset (Clock app, docs/SYSTEM.md) to get another city's time without
+ * touching the process time zone (setenv TZ would change the Date of the whole theme). */
#ifndef LORD_TZIF_H
#define LORD_TZIF_H
@@ -8,18 +8,18 @@
#include <stdint.h>
typedef struct {
- int32_t utoff; /* segundos al este de UTC (Buenos Aires: -10800) */
+ int32_t utoff; /* seconds east of UTC (Buenos Aires: -10800) */
int isdst;
char abbr[16]; /* "CEST", "-03"… */
} TzInfo;
-/* Hora local en el instante t (segundos Unix) según un archivo TZif ya leído. 0 si sirve. */
+/* Local time at instant t (Unix seconds) according to an already loaded TZif file. 0 on success. */
int tzif_lookup(const uint8_t *buf, size_t n, int64_t t, TzInfo *out);
-/* Igual, con una regla POSIX ("CET-1CEST,M3.5.0,M10.5.0/3"): la que trae el pie de los TZif. */
+/* Same, from a POSIX rule ("CET-1CEST,M3.5.0,M10.5.0/3"): the one in the TZif footer. */
int tz_posix(const char *rule, int64_t t, TzInfo *out);
-/* Nombre de zona válido: "Europe/Madrid", "UTC" (sin "..", sin "/" inicial, [A-Za-z0-9/_+-]). */
+/* Valid zone name: "Europe/Madrid", "UTC" (no "..", no leading "/", [A-Za-z0-9/_+-]). */
int tz_zone_valid(const char *zone);
-/* Lee /usr/share/zoneinfo/<zone> (archivo regular de hasta 1 MB) y busca t. 0 si sirve. */
+/* Reads /usr/share/zoneinfo/<zone> (a regular file up to 1 MB) and looks up t. 0 on success. */
int tz_zone_offset(const char *zone, int64_t t, TzInfo *out);
#endif
diff --git a/server/src/users/homedirs.c b/server/src/users/homedirs.c
index 7d46177..867fdc1 100644
--- a/server/src/users/homedirs.c
+++ b/server/src/users/homedirs.c
@@ -1,4 +1,4 @@
-/* homedirs.c — carpetas comunes del usuario y xdg-user-dirs (ver homedirs.h). */
+/* homedirs.c — the user's common folders and xdg-user-dirs (see homedirs.h). */
#include "homedirs.h"
#include <errno.h>
@@ -9,7 +9,7 @@
#include <sys/stat.h>
#include <unistd.h>
-/* La misma lista que tools/iso/rootfs/usr/lib/lordos/lordos-live-prep (allí con _ por espacio). */
+/* The same list as tools/iso/rootfs/usr/lib/lordos/lordos-live-prep (there with _ for spaces). */
static const char *const names[3][HOMEDIRS_COUNT] = {
{ "Escritorio", "Documentos", "Descargas", "Música", "Imágenes", "Videos" },
{ "Desktop", "Documents", "Downloads", "Music", "Pictures", "Videos" },
@@ -30,7 +30,7 @@ const char *homedirs_name(const char *ui_lang, int i) {
return names[lang_index(ui_lang ? ui_lang : "es")][i];
}
-/* Archivo nuevo (O_EXCL, sin seguir enlaces) relativo a la carpeta abierta dfd. */
+/* New file (O_EXCL, no symlinks followed) relative to the open directory dfd. */
static int write_new(int dfd, const char *name, const char *text, uid_t uid, gid_t gid) {
int fd = openat(dfd, name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644);
if (fd < 0) return errno == EEXIST ? 0 : -1;
@@ -41,7 +41,7 @@ static int write_new(int dfd, const char *name, const char *text, uid_t uid, gid
return ok ? 0 : -1;
}
-/* Subcarpeta nueva de dfd con dueño; abierta (sin seguir enlaces) o -1. */
+/* New owned subdirectory of dfd; returns it opened (no symlinks followed) or -1. */
static int mkdir_owned(int dfd, const char *name, uid_t uid, gid_t gid) {
if (mkdirat(dfd, name, 0755) == 0) {
if (fchownat(dfd, name, uid, gid, AT_SYMLINK_NOFOLLOW)) return -1;
@@ -63,12 +63,12 @@ int homedirs_create(const char *home, uid_t uid, gid_t gid, const char *locale)
if (cfd >= 0) {
char text[1024];
size_t o = (size_t)snprintf(text, sizeof text,
- "# Carpetas del usuario (xdg-user-dirs). Lo escribe LordOS al crear la cuenta.\n");
+ "# User folders (xdg-user-dirs). Written by LordOS when the account was created.\n");
for (int i = 0; i < HOMEDIRS_COUNT && o < sizeof text; i++)
o += (size_t)snprintf(text + o, sizeof text - o, "XDG_%s_DIR=\"$HOME/%s\"\n", xdg_keys[i], names[li][i]);
if (o < sizeof text) snprintf(text + o, sizeof text - o, "XDG_TEMPLATES_DIR=\"$HOME/\"\nXDG_PUBLICSHARE_DIR=\"$HOME/\"\n");
if (write_new(cfd, "user-dirs.dirs", text, uid, gid)) bad = -1;
- /* el idioma con el que se nombraron (xdg-user-dirs-update lo compara al cambiar de idioma) */
+ /* the language they were named in (xdg-user-dirs-update compares it when the language changes) */
char loc[64];
snprintf(loc, sizeof loc, "%s", li == 1 ? "en_US" : li == 2 ? "pt_BR" : "es_ES");
if (locale && !strncmp(locale, ui, 2)) { snprintf(loc, sizeof loc, "%s", locale); loc[strcspn(loc, ".@")] = 0; }
diff --git a/server/src/users/homedirs.h b/server/src/users/homedirs.h
index 9894669..be7bdba 100644
--- a/server/src/users/homedirs.h
+++ b/server/src/users/homedirs.h
@@ -1,19 +1,19 @@
-/* homedirs.h — carpetas comunes de la carpeta personal en el idioma del usuario (Escritorio,
- * Documentos, Descargas, Música, Imágenes, Videos) y su ~/.config/user-dirs.dirs (xdg-user-dirs).
- * Una sola lista para el instalador (install.c) y Ajustes → Usuarios (users_admin.c); es la misma
- * que usa lordos-live-prep en el ISO live. Se llama como root. */
+/* homedirs.h — the common home folders in the user's language (Escritorio, Documentos, Descargas,
+ * Música, Imágenes, Videos in Spanish) and ~/.config/user-dirs.dirs (xdg-user-dirs). One list for
+ * the installer (install.c) and Settings → Users (users_admin.c); it matches lordos-live-prep in
+ * the live ISO. Called as root. */
#ifndef LORD_HOMEDIRS_H
#define LORD_HOMEDIRS_H
#include <sys/types.h>
-/* Idioma de la interfaz para una región ("es_AR.UTF-8" → "es"): es, en o pt (español si no hay). */
+/* UI language for a locale ("es_AR.UTF-8" → "es"): es, en or pt (Spanish otherwise). */
const char *homedirs_ui_lang(const char *locale);
-/* Nombre visible de cada carpeta (0..5: escritorio, documentos, descargas, música, imágenes, videos). */
+/* Visible name of each folder (0..5: desktop, documents, downloads, music, pictures, videos). */
const char *homedirs_name(const char *ui_lang, int i);
#define HOMEDIRS_COUNT 6
-/* Crea las carpetas que falten en home (dueño uid:gid, 0755) y escribe ~/.config/user-dirs.dirs y
- * ~/.config/user-dirs.locale si no existen. No sigue enlaces simbólicos. 0 si todo salió bien. */
+/* Creates the missing folders in home (owner uid:gid, 0755) and writes ~/.config/user-dirs.dirs and
+ * ~/.config/user-dirs.locale if they don't exist. Never follows symlinks. 0 on success. */
int homedirs_create(const char *home, uid_t uid, gid_t gid, const char *locale);
#endif
diff --git a/server/src/users/users_admin.c b/server/src/users/users_admin.c
index c4c81ad..e9c02cc 100644
--- a/server/src/users/users_admin.c
+++ b/server/src/users/users_admin.c
@@ -179,7 +179,7 @@ static void prepare_home(const struct passwd *pw) {
while (f && fgets(line, sizeof line, f)) if (sscanf(line, "LANG=%63[A-Za-z_.@0-9-]", lang) == 1) break;
if (f) fclose(f);
char path[PATH_MAX];
- /* Escritorio, Documentos… y ~/.config/user-dirs.dirs en el idioma del sistema (homedirs.c) */
+ /* Escritorio, Documentos… and ~/.config/user-dirs.dirs in the system language (homedirs.c) */
if (homedirs_create(pw->pw_dir, pw->pw_uid, pw->pw_gid, lang)) admin_say("LOG", "aviso: no se pudieron crear todas las carpetas");
snprintf(path, sizeof path, "%s/.config", pw->pw_dir);
if (!mkdir(path, 0755) && chown(path, pw->pw_uid, pw->pw_gid)) { /* sigue */ }
@@ -214,6 +214,7 @@ void users_act_add(const AdminReq *r, const char *arg, size_t len) {
else {
if (adm) { const char *const g[] = { "/usr/sbin/usermod", "--append", "--groups", ADMIN_GROUP, name, NULL }; admin_run(g); print_group(name, 1); }
if (getgrnam("pipewire")) { const char *const g[] = { "/usr/sbin/usermod", "--append", "--groups", "pipewire", name, NULL }; admin_run(g); } /* sonido en tiempo real (docs/SONIDO.md) */
+ if (getgrnam("plugdev")) { const char *const g[] = { "/usr/sbin/usermod", "--append", "--groups", "plugdev", name, NULL }; admin_run(g); } /* FIDO2 security keys (docs/PASSWORDS.md) */
prepare_home(pw);
admin_say("OK", "usuario %s creado", name);
}
diff --git a/server/src/vault/dbus.c b/server/src/vault/dbus.c
index d144b09..d6d3975 100644
--- a/server/src/vault/dbus.c
+++ b/server/src/vault/dbus.c
@@ -554,6 +554,24 @@ int dbus_connect_session(void) {
return fd;
}
+/* System bus (BlueZ, power-profiles-daemon; Settings, see docs/SETTINGS.md):
+ * DBUS_SYSTEM_BUS_ADDRESS if it is a unix:path=, else /run/dbus/system_bus_socket. */
+int dbus_connect_system(void) {
+ struct sockaddr_un a = { .sun_family = AF_UNIX };
+ const char *addr = getenv("DBUS_SYSTEM_BUS_ADDRESS"), *path = "/run/dbus/system_bus_socket";
+ char buf[sizeof a.sun_path];
+ if (addr && !strncmp(addr, "unix:path=", 10)) {
+ size_t n = strcspn(addr + 10, ",;");
+ if (n && n < sizeof buf) { memcpy(buf, addr + 10, n); buf[n] = 0; path = buf; }
+ }
+ if (strlen(path) >= sizeof a.sun_path) return -1;
+ memcpy(a.sun_path, path, strlen(path) + 1);
+ int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ if (fd < 0) return -1;
+ if (connect(fd, (struct sockaddr *)&a, sizeof a)) { close(fd); return -1; }
+ return fd;
+}
+
static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
static int wait_fd(int fd, short ev, double deadline) {
diff --git a/server/src/vault/dbus.h b/server/src/vault/dbus.h
index 304e721..61bc099 100644
--- a/server/src/vault/dbus.h
+++ b/server/src/vault/dbus.h
@@ -117,6 +117,8 @@ typedef struct {
/* Conecta (sin autenticar) al bus de la sesión: DBUS_SESSION_BUS_ADDRESS (unix:path= o
* unix:abstract=) o $XDG_RUNTIME_DIR/bus. Para lord-server, fuera de la caja de arena. fd o -1. */
int dbus_connect_session(void);
+/* System bus: DBUS_SYSTEM_BUS_ADDRESS (unix:path=) or /run/dbus/system_bus_socket. fd or -1. */
+int dbus_connect_system(void);
/* SASL EXTERNAL + Hello sobre un socket conectado (espera hasta timeout_ms). Deja el fd sin
* bloquear. 0 bien. */
int dbus_open(DConn *c, int fd, int timeout_ms);
diff --git a/server/src/vault/vault.c b/server/src/vault/vault.c
index 6a90571..98031e9 100644
--- a/server/src/vault/vault.c
+++ b/server/src/vault/vault.c
@@ -1130,7 +1130,7 @@ static const char *group_cat(Vault *v, GroupMap **gm, int *ngm, const char *path
vb_open(&b, '{');
vb_ks(&b, "id", g->id);
vb_ks(&b, "name", name);
- vb_ks(&b, "icon", "folder");
+ vb_ks(&b, "icon", "\xf0\x9f\x93\x81");
vb_ks(&b, "color", "#8e8e93");
vb_ks(&b, "template", "general");
if (pid) vb_ks(&b, "parent", pid);
diff --git a/server/src/wl/wl.c b/server/src/wl/wl.c
index 7f45322..761af8c 100644
--- a/server/src/wl/wl.c
+++ b/server/src/wl/wl.c
@@ -913,6 +913,7 @@ static int writer_ready(int fd, uint32_t mask, void *data) {
}
wl_event_source_remove(w->ev);
close(w->fd);
+ explicit_bzero(w->buf, w->len); /* may be a password copied from Passwords */
free(w->buf);
free(w);
return 0;
@@ -940,6 +941,8 @@ static void ofr_receive(struct wl_client *c, struct wl_resource *r, const char *
if (src && src == selection) { wl_data_source_send_send(src->res, mime, fd); close(fd); return; }
if (!src && clip_is_image && clip_png && !strcmp(mime, "image/png")) { send_bytes(fd, clip_png, clip_png_len); return; }
if (!src && !clip_is_image && text_mime(mime)) { const char *t = term_clipboard(); send_bytes(fd, t, strlen(t)); return; }
+ /* KDE/GNOME convention: clipboard managers skip an offer carrying this hint */
+ if (!src && !clip_is_image && !strcmp(mime, "x-kde-passwordManagerHint") && term_clipboard_sensitive()) { send_bytes(fd, "secret", 6); return; }
close(fd);
}
static void ofr_destroy(struct wl_client *c, struct wl_resource *r) { (void)c; wl_resource_destroy(r); }
@@ -965,6 +968,8 @@ static void offer_selection(struct wl_resource *dev) {
wl_data_offer_send_offer(o, "text/plain;charset=utf-8");
wl_data_offer_send_offer(o, "text/plain");
wl_data_offer_send_offer(o, "UTF8_STRING");
+ /* a secret copied in LordOS (Passwords, password fields): Linux clipboard managers must not keep it */
+ if (term_clipboard_sensitive()) wl_data_offer_send_offer(o, "x-kde-passwordManagerHint");
}
wl_data_device_send_selection(dev, o);
}
diff --git a/server/tests/backup_test.c b/server/tests/backup_test.c
index 924b965..0584714 100644
--- a/server/tests/backup_test.c
+++ b/server/tests/backup_test.c
@@ -1,8 +1,8 @@
-/* backup_test.c — prueba del motor de Copias de seguridad (src/backup/engine.c):
- * instantánea, enlaces duros entre instantáneas, enlaces simbólicos (nunca se siguen), exclusiones,
- * copia cortada y retomada, restaurar (mantener los dos, reemplazar, carpetas protegidas, escapes
- * por enlaces) y la retención (función pura, con fechas inventadas). */
-/* las rutas de prueba son cortas: GCC no puede saberlo y avisa en cada snprintf de rutas */
+/* backup_test.c — tests for the backup engine (src/backup/engine.c and crypt.c): snapshots,
+ * hard links between snapshots, symbolic links (never followed), exclusions, interrupted and
+ * resumed runs, restore (keep both, replace, protected folders, escapes through links), retention
+ * (a pure function, with made-up dates) and encryption. */
+/* the test paths are short: GCC cannot know that and warns on every path snprintf */
#pragma GCC diagnostic ignored "-Wformat-truncation"
#include "backup/engine.h"
#include "backup/crypt.h"
@@ -21,7 +21,7 @@
#include <unistd.h>
static int fails, checks;
-#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FALLA %s:%d: ", __FILE__, __LINE__); fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0)
+#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0)
static char T[PATH_MAX], H[PATH_MAX], M[PATH_MAX];
@@ -66,16 +66,16 @@ static void init_run(BkRun *r) {
r->home = H;
r->machine = M;
r->excl[r->nexcl++] = ".cache";
- r->excl[r->nexcl++] = "Excluida";
+ r->excl[r->nexcl++] = "Excluded";
r->min_free = 1;
}
-/* checkpoint que corta después de ~N bytes */
+/* checkpoint that stops after ~N bytes */
static uint64_t cut_after;
static int cut_cb(BkRun *r) { return cut_after && r->bytes >= cut_after; }
static void test_retention(void) {
- /* una por hora durante 90 días, terminando ahora */
+ /* one per hour for 90 days, ending now */
enum { N = 90 * 24 };
static time_t t[N];
static int keep[N];
@@ -83,84 +83,84 @@ static void test_retention(void) {
for (int i = 0; i < N; i++) t[i] = now - (time_t)(N - 1 - i) * 3600;
bk_retention(t, N, now, 0, keep);
int recent = 0, total = 0;
- for (int i = 0; i < N; i++) { total += keep[i]; if (now - t[i] < 86400) { recent++; CHECK(keep[i], "las de las últimas 24 h quedan"); } }
- CHECK(recent == 24, "24 por hora (%d)", recent);
- CHECK(keep[N - 1], "la más nueva queda");
- /* entre 1 y 30 días: una por día calendario */
+ for (int i = 0; i < N; i++) { total += keep[i]; if (now - t[i] < 86400) { recent++; CHECK(keep[i], "everything from the last 24 h stays"); } }
+ CHECK(recent == 24, "24 hourly (%d)", recent);
+ CHECK(keep[N - 1], "the newest stays");
+ /* between 1 and 30 days: one per calendar day */
int days[40] = { 0 };
for (int i = 0; i < N; i++) {
long age = (long)(now - t[i]);
if (keep[i] && age >= 86400 && age < 30L * 86400) days[(t[i] / 86400) % 40]++;
}
- for (int d = 0; d < 40; d++) CHECK(days[d] <= 1, "como mucho una por día (%d)", days[d]);
- /* después de 30 días: una por semana */
+ for (int d = 0; d < 40; d++) CHECK(days[d] <= 1, "at most one per day (%d)", days[d]);
+ /* after 30 days: one per week */
long weeks[20];
int nw = 0;
for (int i = 0; i < N; i++) {
if (!keep[i] || now - t[i] < 30L * 86400) continue;
long w = (t[i] - 4L * 86400) / (7L * 86400);
- for (int k = 0; k < nw; k++) CHECK(weeks[k] != w, "dos de la misma semana");
+ for (int k = 0; k < nw; k++) CHECK(weeks[k] != w, "two from the same week");
if (nw < 20) weeks[nw++] = w;
}
- CHECK(nw >= 8 && nw <= 10, "semanales entre 30 y 90 días (%d)", nw);
- CHECK(total < 24 + 31 + 11, "total razonable (%d)", total);
- /* casos chicos */
+ CHECK(nw >= 8 && nw <= 10, "weekly between 30 and 90 days (%d)", nw);
+ CHECK(total < 24 + 31 + 11, "reasonable total (%d)", total);
+ /* small cases */
time_t one = now;
int k1 = 0;
bk_retention(&one, 1, now, 0, &k1);
- CHECK(k1 == 1, "una sola queda");
- time_t old[3] = { now - 100L * 86400, now - 99L * 86400, now - 98L * 86400 }; /* misma semana o no, la última queda */
+ CHECK(k1 == 1, "a single one stays");
+ time_t old[3] = { now - 100L * 86400, now - 99L * 86400, now - 98L * 86400 }; /* same week or not, the newest stays */
int k3[3];
bk_retention(old, 3, now, 0, k3);
- CHECK(k3[2] == 1, "la más nueva, aunque sea vieja, queda");
- /* zona horaria: dos del mismo día local pero de distintos días UTC */
+ CHECK(k3[2] == 1, "the newest stays even if old");
+ /* time zone: two on the same local day but on different UTC days */
time_t tz[2] = { 1791900000 - 3600 * 2, 1791900000 + 3600 * 2 };
int kz[2];
- long off = -((1791900000L % 86400)); /* el corte de día local cae justo entre las dos */
+ long off = -((1791900000L % 86400)); /* the local day boundary falls right between them */
bk_retention(tz, 2, tz[1] + 5 * 86400, off + 86400 / 2, kz);
- CHECK(kz[1] == 1, "zona horaria: la última queda");
+ CHECK(kz[1] == 1, "time zone: the newest stays");
}
static void test_rel(void) {
- CHECK(bk_rel_valid(""), "vacío vale");
- CHECK(bk_rel_valid("a/b c/d.txt"), "normal vale");
- CHECK(!bk_rel_valid("/etc"), "absoluta no");
- CHECK(!bk_rel_valid("a/../b"), ".. no");
- CHECK(!bk_rel_valid(".."), ".. solo no");
- CHECK(!bk_rel_valid("a//b"), "// no");
- CHECK(!bk_rel_valid("a/./b"), ". no");
- CHECK(!bk_rel_valid("a/"), "barra final no");
- CHECK(!bk_rel_valid("a\nb"), "control no");
+ CHECK(bk_rel_valid(""), "empty is valid");
+ CHECK(bk_rel_valid("a/b c/d.txt"), "normal is valid");
+ CHECK(!bk_rel_valid("/etc"), "absolute rejected");
+ CHECK(!bk_rel_valid("a/../b"), ".. rejected");
+ CHECK(!bk_rel_valid(".."), "bare .. rejected");
+ CHECK(!bk_rel_valid("a//b"), "// rejected");
+ CHECK(!bk_rel_valid("a/./b"), ". rejected");
+ CHECK(!bk_rel_valid("a/"), "trailing slash rejected");
+ CHECK(!bk_rel_valid("a\nb"), "control character rejected");
CHECK(bk_id_valid("2026-10-17-235959"), "id");
- CHECK(!bk_id_valid("2026-10-17-23595"), "id corto");
- CHECK(!bk_id_valid("../10-17-235959x"), "id raro");
+ CHECK(!bk_id_valid("2026-10-17-23595"), "short id");
+ CHECK(!bk_id_valid("../10-17-235959x"), "odd id");
char id[BK_ID_LEN];
time_t now = time(NULL);
bk_id_make(now, id);
- CHECK(bk_id_time(id) == now, "id ida y vuelta");
+ CHECK(bk_id_time(id) == now, "id round trip");
}
-/* cifrado: tamaños, ida y vuelta, alteraciones, frase incorrecta y una instantánea cifrada */
+/* encryption: sizes, round trips, tampering, wrong passphrase and an encrypted snapshot */
static void test_crypt(void) {
static const uint64_t sizes[] = { 0, 1, 15, 16, 65535, 65536, 65537, 131072, 200000, 1u << 20 };
for (size_t i = 0; i < sizeof sizes / sizeof *sizes; i++) {
uint64_t p = 99;
- CHECK(!bkc_plain_size(bkc_enc_size(sizes[i]), &p) && p == sizes[i], "tamaño %llu ida y vuelta", (unsigned long long)sizes[i]);
+ CHECK(!bkc_plain_size(bkc_enc_size(sizes[i]), &p) && p == sizes[i], "size %llu round trip", (unsigned long long)sizes[i]);
}
uint64_t junk;
- CHECK(bkc_plain_size(BKC_HDR + 5, &junk) != 0, "tamaño imposible rechazado");
+ CHECK(bkc_plain_size(BKC_HDR + 5, &junk) != 0, "impossible size rejected");
char M2[PATH_MAX], p[PATH_MAX], q[PATH_MAX], buf[256];
- snprintf(M2, sizeof M2, "%s/cifrado/" BK_DIRNAME "/equipo-usuario", T);
- snprintf(p, sizeof p, "%s/cifrado", T); mkdir(p, 0700);
- snprintf(p, sizeof p, "%s/cifrado/" BK_DIRNAME, T); mkdir(p, 0700);
+ snprintf(M2, sizeof M2, "%s/encrypted/" BK_DIRNAME "/host-user", T);
+ snprintf(p, sizeof p, "%s/encrypted", T); mkdir(p, 0700);
+ snprintf(p, sizeof p, "%s/encrypted/" BK_DIRNAME, T); mkdir(p, 0700);
mkdir(M2, 0700);
uint8_t key[BKC_KEY], k2[BKC_KEY];
- CHECK(bkc_setup(M2, "una frase larga de prueba", key) == 0, "crear el cifrado");
- CHECK(bkc_unlock(M2, "una frase larga de prueba", k2) == 0 && !memcmp(key, k2, sizeof key), "desbloquear con la frase");
- CHECK(bkc_unlock(M2, "otra frase", k2) == -1, "frase incorrecta");
- /* ida y vuelta con varios tamaños por archivo */
+ CHECK(bkc_setup(M2, "a long test passphrase", key) == 0, "set up encryption");
+ CHECK(bkc_unlock(M2, "a long test passphrase", k2) == 0 && !memcmp(key, k2, sizeof key), "unlock with the passphrase");
+ CHECK(bkc_unlock(M2, "another passphrase", k2) == -1, "wrong passphrase");
+ /* round trip with several file sizes */
for (size_t i = 0; i < sizeof sizes / sizeof *sizes; i++) {
- snprintf(p, sizeof p, "%s/plano.bin", T); snprintf(q, sizeof q, "%s/cifrado.bin", T);
+ snprintf(p, sizeof p, "%s/plain.bin", T); snprintf(q, sizeof q, "%s/encrypted.bin", T);
FILE *f = fopen(p, "w");
for (uint64_t k = 0; k < sizes[i]; k++) fputc((int)((k * 7 + i) & 0xff), f);
fclose(f);
@@ -168,72 +168,72 @@ static void test_crypt(void) {
int r = bkc_encrypt_fd(in, out, key, NULL, NULL);
close(in); close(out);
struct stat st;
- CHECK(r == 0 && !stat(q, &st) && (uint64_t)st.st_size == bkc_enc_size(sizes[i]), "cifrar %llu", (unsigned long long)sizes[i]);
+ CHECK(r == 0 && !stat(q, &st) && (uint64_t)st.st_size == bkc_enc_size(sizes[i]), "encrypt %llu", (unsigned long long)sizes[i]);
char back[PATH_MAX];
- snprintf(back, sizeof back, "%s/vuelta.bin", T);
+ snprintf(back, sizeof back, "%s/back.bin", T);
in = open(q, O_RDONLY); out = open(back, O_WRONLY | O_CREAT | O_TRUNC, 0600);
r = bkc_decrypt_fd(in, out, key, NULL, NULL);
close(in); close(out);
char cmd[3 * PATH_MAX];
snprintf(cmd, sizeof cmd, "cmp -s '%s' '%s'", p, back);
- CHECK(r == 0 && system(cmd) == 0, "descifrar %llu igual", (unsigned long long)sizes[i]);
+ CHECK(r == 0 && system(cmd) == 0, "decrypt %llu identical", (unsigned long long)sizes[i]);
if (sizes[i] == 200000) {
- /* un byte cambiado, un trozo menos y la clave equivocada: falla y no da datos falsos */
+ /* one changed byte, a missing chunk and the wrong key: fails without returning bad data */
int fd = open(q, O_RDWR);
unsigned char b;
pread(fd, &b, 1, 70000); b ^= 1; pwrite(fd, &b, 1, 70000);
close(fd);
in = open(q, O_RDONLY); out = open(back, O_WRONLY | O_CREAT | O_TRUNC, 0600);
- CHECK(bkc_decrypt_fd(in, out, key, NULL, NULL) == -3, "byte alterado detectado");
+ CHECK(bkc_decrypt_fd(in, out, key, NULL, NULL) == -3, "tampered byte detected");
close(in); close(out);
pread(fd = open(q, O_RDWR), &b, 1, 70000); b ^= 1; pwrite(fd, &b, 1, 70000);
- CHECK(ftruncate(fd, (off_t)bkc_enc_size(2 * 65536)) == 0, "cortar");
+ CHECK(ftruncate(fd, (off_t)bkc_enc_size(2 * 65536)) == 0, "truncate");
close(fd);
in = open(q, O_RDONLY); out = open(back, O_WRONLY | O_CREAT | O_TRUNC, 0600);
- CHECK(bkc_decrypt_fd(in, out, key, NULL, NULL) == -3, "trozos de menos detectado");
+ CHECK(bkc_decrypt_fd(in, out, key, NULL, NULL) == -3, "missing chunks detected");
close(in); close(out);
uint8_t bad[BKC_KEY];
memcpy(bad, key, sizeof bad); bad[0] ^= 1;
in = open(q, O_RDONLY); out = open(back, O_WRONLY | O_CREAT | O_TRUNC, 0600);
- CHECK(bkc_decrypt_fd(in, out, bad, NULL, NULL) == -3, "clave equivocada detectada");
+ CHECK(bkc_decrypt_fd(in, out, bad, NULL, NULL) == -3, "wrong key detected");
close(in); close(out);
}
}
- /* instantánea cifrada: nada en claro, enlaces duros igual, restaurar descifra */
+ /* encrypted snapshot: nothing in clear text, hard links still work, restore decrypts */
BkRun r;
memset(&r, 0, sizeof r);
r.home = H; r.machine = M2; r.key = key; r.min_free = 1;
r.excl[r.nexcl++] = "dest";
- put("secreto.txt", "texto muy secreto 1234\n");
+ put("secret.txt", "very secret text 1234\n");
int rc = bk_snapshot(&r, time(NULL) - 600);
- CHECK(rc == 0, "instantánea cifrada (%s)", r.error);
+ CHECK(rc == 0, "encrypted snapshot (%s)", r.error);
char id1[BK_ID_LEN];
snprintf(id1, sizeof id1, "%s", r.id);
- snprintf(p, sizeof p, "%s/%s/secreto.txt", M2, id1);
- CHECK(!slurp(p, buf, sizeof buf) && !strstr(buf, "secreto 1234") && !memcmp(buf, "LBK1", 4), "el archivo de la copia está cifrado");
+ snprintf(p, sizeof p, "%s/%s/secret.txt", M2, id1);
+ CHECK(!slurp(p, buf, sizeof buf) && !strstr(buf, "secret text 1234") && !memcmp(buf, "LBK1", 4), "the backup file is encrypted");
memset(&r, 0, sizeof r);
r.home = H; r.machine = M2; r.key = key; r.min_free = 1;
r.excl[r.nexcl++] = "dest";
rc = bk_snapshot(&r, time(NULL) - 300);
- CHECK(rc == 0 && r.copied == 0 && r.linked > 3, "cifrada: lo igual se enlaza (%llu copiados)", (unsigned long long)r.copied);
- snprintf(q, sizeof q, "%s/%s/secreto.txt", M2, r.id);
- CHECK(ino(p) == ino(q), "cifrada: mismo inodo");
- snprintf(q, sizeof q, "%s/secreto.txt", H);
+ CHECK(rc == 0 && r.copied == 0 && r.linked > 3, "encrypted: unchanged files are linked (%llu copied)", (unsigned long long)r.copied);
+ snprintf(q, sizeof q, "%s/%s/secret.txt", M2, r.id);
+ CHECK(ino(p) == ino(q), "encrypted: same inode");
+ snprintf(q, sizeof q, "%s/secret.txt", H);
unlink(q);
BkRestore o = { .key = key };
- rc = bk_restore(M2, id1, "secreto.txt", H, 0, " (restaurado)", &o);
- CHECK(rc == 0 && o.files == 1 && !slurp(q, buf, sizeof buf) && !strcmp(buf, "texto muy secreto 1234\n"), "restaurar descifra");
- rc = bk_restore(M2, id1, "secreto.txt", H, 0, " (restaurado)", &o);
- CHECK(rc == 0 && o.kept_both == 0 && o.skipped == 1, "cifrada: igual al actual, no se duplica");
- /* copia alterada: no se escribe nada */
+ rc = bk_restore(M2, id1, "secret.txt", H, 0, " (restored)", &o);
+ CHECK(rc == 0 && o.files == 1 && !slurp(q, buf, sizeof buf) && !strcmp(buf, "very secret text 1234\n"), "restore decrypts");
+ rc = bk_restore(M2, id1, "secret.txt", H, 0, " (restored)", &o);
+ CHECK(rc == 0 && o.kept_both == 0 && o.skipped == 1, "encrypted: identical to the current file, not duplicated");
+ /* tampered backup: nothing is written */
int fd = open(p, O_RDWR);
unsigned char b;
pread(fd, &b, 1, BKC_HDR + 2); b ^= 0x40; pwrite(fd, &b, 1, BKC_HDR + 2);
close(fd);
unlink(q);
BkRestore o2 = { .key = key };
- bk_restore(M2, id1, "secreto.txt", H, 0, " (restaurado)", &o2);
- CHECK(o2.errors == 1 && !exists(q), "copia alterada: error y nada escrito (%s)", o2.error);
+ bk_restore(M2, id1, "secret.txt", H, 0, " (restored)", &o2);
+ CHECK(o2.errors == 1 && !exists(q), "tampered backup: error and nothing written (%s)", o2.error);
bkc_wipe(key, sizeof key);
}
@@ -247,23 +247,23 @@ int main(void) {
snprintf(h0, sizeof h0, "%s/home", T);
mkdir(h0, 0755);
if (!realpath(h0, H)) return 2;
- snprintf(M, sizeof M, "%s/dest/" BK_DIRNAME "/equipo-usuario", H); /* destino ADENTRO de la carpeta personal */
- fsops_init(H, "usuario-de-prueba");
+ snprintf(M, sizeof M, "%s/dest/" BK_DIRNAME "/host-user", H); /* destination INSIDE the home folder */
+ fsops_init(H, "test-user");
- put("a.txt", "versión 1\n");
+ put("a.txt", "version 1\n");
mk("dir"); put_big("dir/b.bin", 1);
mk("sub"); mk("sub/deep"); put("sub/deep/c.txt", "c\n");
- mk(".cache"); put(".cache/basura", "x");
- mk("Excluida"); put("Excluida/x", "x");
+ mk(".cache"); put(".cache/junk", "x");
+ mk("Excluded"); put("Excluded/x", "x");
mk(".config"); mk(".config/lordos"); put(".config/lordos/settings.json", "{\"language\":\"es\"}\n");
char p[PATH_MAX], q[PATH_MAX], buf[256];
snprintf(p, sizeof p, "%s/escape", H); symlink("/etc/passwd", p);
- snprintf(p, sizeof p, "%s/relativo", H); symlink("a.txt", p);
+ snprintf(p, sizeof p, "%s/relative", H); symlink("a.txt", p);
snprintf(p, sizeof p, "%s/fifo", H); mkfifo(p, 0600);
time_t t0 = time(NULL) - 7200;
BkRun r;
- /* el destino adentro de home: se saltea por dev/ino */
+ /* the destination inside home: skipped by dev/ino */
char skip[PATH_MAX], d0[PATH_MAX];
snprintf(d0, sizeof d0, "%s/dest/" BK_DIRNAME, H);
init_run(&r);
@@ -274,162 +274,162 @@ int main(void) {
if (realpath(d0, skip)) r.skip_real = skip;
}
int rc = bk_snapshot(&r, t0);
- CHECK(rc == 0, "primera instantánea (%d: %s)", rc, r.error);
+ CHECK(rc == 0, "first snapshot (%d: %s)", rc, r.error);
char id1[BK_ID_LEN];
snprintf(id1, sizeof id1, "%s", r.id);
snap_path(id1, "a.txt", p, sizeof p);
- CHECK(!slurp(p, buf, sizeof buf) && !strcmp(buf, "versión 1\n"), "a.txt copiado");
+ CHECK(!slurp(p, buf, sizeof buf) && !strcmp(buf, "version 1\n"), "a.txt copied");
snap_path(id1, "sub/deep/c.txt", p, sizeof p);
- CHECK(exists(p), "carpetas profundas");
+ CHECK(exists(p), "deep folders");
snap_path(id1, ".cache", p, sizeof p);
- CHECK(!exists(p), ".cache excluida");
- snap_path(id1, "Excluida", p, sizeof p);
- CHECK(!exists(p), "exclusión del usuario");
+ CHECK(!exists(p), ".cache excluded");
+ snap_path(id1, "Excluded", p, sizeof p);
+ CHECK(!exists(p), "user exclusion");
snap_path(id1, "fifo", p, sizeof p);
- CHECK(!exists(p), "fifo salteado");
+ CHECK(!exists(p), "fifo skipped");
snap_path(id1, "dest", p, sizeof p);
snprintf(q, sizeof q, "%s/" BK_DIRNAME, p);
- CHECK(!exists(q), "el destino no se copia a sí mismo");
+ CHECK(!exists(q), "the destination is not copied into itself");
snap_path(id1, "escape", p, sizeof p);
struct stat st;
- CHECK(!lstat(p, &st) && S_ISLNK(st.st_mode), "enlace guardado como enlace");
+ CHECK(!lstat(p, &st) && S_ISLNK(st.st_mode), "symlink stored as a symlink");
ssize_t k = readlink(p, buf, sizeof buf - 1);
- CHECK(k > 0 && (buf[k] = 0, !strcmp(buf, "/etc/passwd")), "con el mismo texto");
- CHECK(r.skipped >= 1, "especiales contados (%llu)", (unsigned long long)r.skipped);
+ CHECK(k > 0 && (buf[k] = 0, !strcmp(buf, "/etc/passwd")), "with the same target text");
+ CHECK(r.skipped >= 1, "special files counted (%llu)", (unsigned long long)r.skipped);
- /* segunda: cambia a.txt, el resto se enlaza */
- put("a.txt", "versión 2, más larga\n");
+ /* second: a.txt changes, the rest is linked */
+ put("a.txt", "version 2, a bit longer\n");
init_run(&r);
r.skip_real = skip;
rc = bk_snapshot(&r, t0 + 3600);
- CHECK(rc == 0, "segunda instantánea (%s)", r.error);
+ CHECK(rc == 0, "second snapshot (%s)", r.error);
char id2[BK_ID_LEN];
snprintf(id2, sizeof id2, "%s", r.id);
- CHECK(strcmp(id1, id2) < 0, "ids en orden");
+ CHECK(strcmp(id1, id2) < 0, "ids in order");
snap_path(id1, "dir/b.bin", p, sizeof p);
snap_path(id2, "dir/b.bin", q, sizeof q);
- CHECK(ino(p) && ino(p) == ino(q), "dedup: mismo inodo");
+ CHECK(ino(p) && ino(p) == ino(q), "dedup: same inode");
snap_path(id1, "a.txt", p, sizeof p);
snap_path(id2, "a.txt", q, sizeof q);
- CHECK(ino(p) != ino(q), "cambiado: copia nueva");
- CHECK(r.copied == 1, "solo se copió uno (%llu)", (unsigned long long)r.copied);
- CHECK(r.linked >= 3, "enlazados (%llu)", (unsigned long long)r.linked);
+ CHECK(ino(p) != ino(q), "changed: new copy");
+ CHECK(r.copied == 1, "only one was copied (%llu)", (unsigned long long)r.copied);
+ CHECK(r.linked >= 3, "linked (%llu)", (unsigned long long)r.linked);
- /* copia cortada y retomada */
- put("aaa-nuevo.txt", "nuevo antes del corte\n");
- put_big("zz-grande.bin", 40);
+ /* interrupted and resumed run */
+ put("aaa-new.txt", "new before the interruption\n");
+ put_big("zz-big.bin", 40);
init_run(&r);
r.skip_real = skip;
r.checkpoint = cut_cb;
cut_after = 12u << 20;
rc = bk_snapshot(&r, t0 + 5400);
- CHECK(rc == 1, "cortada (%d)", rc);
+ CHECK(rc == 1, "interrupted (%d)", rc);
char inprog[PATH_MAX];
snprintf(inprog, sizeof inprog, "%s/.inprogress-%s", M, r.id);
- CHECK(exists(inprog), "queda .inprogress");
+ CHECK(exists(inprog), ".inprogress is left");
char ids[16][BK_ID_LEN];
- CHECK(bk_list(M, ids, 16) == 2, "la cortada no figura");
- snprintf(p, sizeof p, "%s/zz-grande.bin", inprog);
- CHECK(!exists(p), "el archivo a medias no tiene nombre final");
- snprintf(p, sizeof p, "%s/aaa-nuevo.txt", inprog);
+ CHECK(bk_list(M, ids, 16) == 2, "the interrupted run is not listed");
+ snprintf(p, sizeof p, "%s/zz-big.bin", inprog);
+ CHECK(!exists(p), "the half-copied file has no final name");
+ snprintf(p, sizeof p, "%s/aaa-new.txt", inprog);
ino_t copied_before = ino(p);
- CHECK(copied_before != 0, "lo de antes del corte está");
+ CHECK(copied_before != 0, "what was copied before the interruption is there");
cut_after = 0;
init_run(&r);
r.skip_real = skip;
rc = bk_snapshot(&r, t0 + 5500);
- CHECK(rc == 0, "retomada (%s)", r.error);
+ CHECK(rc == 0, "resumed (%s)", r.error);
char id3[BK_ID_LEN];
snprintf(id3, sizeof id3, "%s", r.id);
- snap_path(id3, "aaa-nuevo.txt", p, sizeof p);
- CHECK(ino(p) == copied_before, "retomada: lo ya copiado se enlaza (no se copia de nuevo)");
- CHECK(r.copied == 1, "retomada: solo el grande (%llu)", (unsigned long long)r.copied);
- snap_path(id3, "zz-grande.bin", p, sizeof p);
- CHECK(!stat(p, &st) && st.st_size == 40 << 20, "el grande completo");
- CHECK(!exists(inprog), "sin .inprogress");
+ snap_path(id3, "aaa-new.txt", p, sizeof p);
+ CHECK(ino(p) == copied_before, "resumed: already copied files are linked (not copied again)");
+ CHECK(r.copied == 1, "resumed: only the big one (%llu)", (unsigned long long)r.copied);
+ snap_path(id3, "zz-big.bin", p, sizeof p);
+ CHECK(!stat(p, &st) && st.st_size == 40 << 20, "the big file is complete");
+ CHECK(!exists(inprog), "no .inprogress");
DIR *dd = opendir(M);
int junk = 0;
for (struct dirent *e; dd && (e = readdir(dd));) if (e->d_name[0] == '.' && strcmp(e->d_name, ".") && strcmp(e->d_name, "..")) junk++;
if (dd) closedir(dd);
- CHECK(junk == 0, "sin restos de la copia cortada (%d)", junk);
+ CHECK(junk == 0, "no leftovers of the interrupted run (%d)", junk);
- /* restaurar */
+ /* restore */
BkRestore o = { 0 };
snprintf(p, sizeof p, "%s/a.txt", H);
unlink(p);
- rc = bk_restore(M, id1, "a.txt", H, 0, " (restaurado)", &o);
- CHECK(rc == 0 && o.files == 1, "restaurar un archivo borrado (%d %s)", rc, o.error);
- CHECK(!slurp(p, buf, sizeof buf) && !strcmp(buf, "versión 1\n"), "con el contenido de entonces");
- put("a.txt", "versión 3 actual\n");
- rc = bk_restore(M, id1, "a.txt", H, 0, " (restaurado)", &o);
- snprintf(q, sizeof q, "%s/a (restaurado).txt", H);
- CHECK(rc == 0 && o.kept_both == 1 && !slurp(q, buf, sizeof buf) && !strcmp(buf, "versión 1\n"), "mantener los dos");
- CHECK(!slurp(p, buf, sizeof buf) && !strcmp(buf, "versión 3 actual\n"), "el actual no se pisa");
- rc = bk_restore(M, id1, "a.txt", H, 0, " (restaurado)", &o);
- snprintf(q, sizeof q, "%s/a (restaurado) 2.txt", H);
- CHECK(rc == 0 && exists(q), "segundo duplicado numerado");
- rc = bk_restore(M, id1, "a.txt", H, 1, " (restaurado)", &o);
- CHECK(rc == 0 && o.replaced == 1 && !slurp(p, buf, sizeof buf) && !strcmp(buf, "versión 1\n"), "reemplazar");
- /* una carpeta que ya no está */
+ rc = bk_restore(M, id1, "a.txt", H, 0, " (restored)", &o);
+ CHECK(rc == 0 && o.files == 1, "restore a deleted file (%d %s)", rc, o.error);
+ CHECK(!slurp(p, buf, sizeof buf) && !strcmp(buf, "version 1\n"), "with the content it had then");
+ put("a.txt", "version 3 current\n");
+ rc = bk_restore(M, id1, "a.txt", H, 0, " (restored)", &o);
+ snprintf(q, sizeof q, "%s/a (restored).txt", H);
+ CHECK(rc == 0 && o.kept_both == 1 && !slurp(q, buf, sizeof buf) && !strcmp(buf, "version 1\n"), "keep both");
+ CHECK(!slurp(p, buf, sizeof buf) && !strcmp(buf, "version 3 current\n"), "the current file is not overwritten");
+ rc = bk_restore(M, id1, "a.txt", H, 0, " (restored)", &o);
+ snprintf(q, sizeof q, "%s/a (restored) 2.txt", H);
+ CHECK(rc == 0 && exists(q), "second duplicate is numbered");
+ rc = bk_restore(M, id1, "a.txt", H, 1, " (restored)", &o);
+ CHECK(rc == 0 && o.replaced == 1 && !slurp(p, buf, sizeof buf) && !strcmp(buf, "version 1\n"), "replace");
+ /* a folder that is gone */
snprintf(p, sizeof p, "%s/sub/deep/c.txt", H); unlink(p);
snprintf(p, sizeof p, "%s/sub/deep", H); rmdir(p);
- rc = bk_restore(M, id2, "sub/deep/c.txt", H, 0, " (restaurado)", &o);
+ rc = bk_restore(M, id2, "sub/deep/c.txt", H, 0, " (restored)", &o);
snprintf(p, sizeof p, "%s/sub/deep/c.txt", H);
- CHECK(rc == 0 && exists(p), "restaurar crea las carpetas que faltan");
- /* protegidas: un .desktop plantado en la copia y los ajustes no se escriben */
+ CHECK(rc == 0 && exists(p), "restore creates missing folders");
+ /* protected: a .desktop planted in the backup and the settings are not written */
char plant[PATH_MAX];
snap_path(id3, ".local", plant, sizeof plant); chmod(plant, 0700); mkdir(plant, 0700);
snap_path(id3, ".local/share", plant, sizeof plant); mkdir(plant, 0700);
snap_path(id3, ".local/share/applications", plant, sizeof plant); mkdir(plant, 0700);
- snap_path(id3, ".local/share/applications/malo.desktop", plant, sizeof plant);
+ snap_path(id3, ".local/share/applications/evil.desktop", plant, sizeof plant);
FILE *f = fopen(plant, "w"); if (f) { fputs("[Desktop Entry]\nExec=rm -rf ~\n", f); fclose(f); }
put(".config/lordos/settings.json", "{\"language\":\"pt\"}\n");
- rc = bk_restore(M, id3, "", H, 1, " (restaurado)", &o);
- CHECK(rc == 0, "restaurar todo (%s)", o.error);
- snprintf(p, sizeof p, "%s/.local/share/applications/malo.desktop", H);
- CHECK(!exists(p), "no escribe .desktop");
+ rc = bk_restore(M, id3, "", H, 1, " (restored)", &o);
+ CHECK(rc == 0, "restore everything (%s)", o.error);
+ snprintf(p, sizeof p, "%s/.local/share/applications/evil.desktop", H);
+ CHECK(!exists(p), "does not write .desktop");
snprintf(p, sizeof p, "%s/.config/lordos/settings.json", H);
- CHECK(!slurp(p, buf, sizeof buf) && strstr(buf, "pt"), "no pisa settings.json");
- CHECK(o.skipped >= 2, "protegidas salteadas (%llu)", (unsigned long long)o.skipped);
- /* enlaces: se restaura el enlace, no lo apuntado; no se baja por un enlace de la copia */
+ CHECK(!slurp(p, buf, sizeof buf) && strstr(buf, "pt"), "does not overwrite settings.json");
+ CHECK(o.skipped >= 2, "protected paths skipped (%llu)", (unsigned long long)o.skipped);
+ /* links: the link is restored, not its target; never descend through a link in the backup */
snprintf(p, sizeof p, "%s/escape", H); unlink(p);
- rc = bk_restore(M, id1, "escape", H, 0, " (restaurado)", &o);
- CHECK(rc == 0 && !lstat(p, &st) && S_ISLNK(st.st_mode), "enlace restaurado como enlace");
- snap_path(id1, "afuera", plant, sizeof plant);
+ rc = bk_restore(M, id1, "escape", H, 0, " (restored)", &o);
+ CHECK(rc == 0 && !lstat(p, &st) && S_ISLNK(st.st_mode), "symlink restored as a symlink");
+ snap_path(id1, "outside", plant, sizeof plant);
symlink("/etc", plant);
- rc = bk_restore(M, id1, "afuera/passwd", H, 0, " (restaurado)", &o);
- snprintf(p, sizeof p, "%s/afuera", H);
- CHECK(rc != 0 && !exists(p), "no se escapa por un enlace de la copia");
- rc = bk_restore(M, id1, "../../../etc/passwd", H, 0, " (restaurado)", &o);
- CHECK(rc != 0, ".. rechazado");
- rc = bk_restore(M, id1, "a.txt", "/etc", 0, " (restaurado)", &o);
- CHECK(rc != 0, "destino fuera de las raíces rechazado");
+ rc = bk_restore(M, id1, "outside/passwd", H, 0, " (restored)", &o);
+ snprintf(p, sizeof p, "%s/outside", H);
+ CHECK(rc != 0 && !exists(p), "no escape through a link in the backup");
+ rc = bk_restore(M, id1, "../../../etc/passwd", H, 0, " (restored)", &o);
+ CHECK(rc != 0, ".. rejected");
+ rc = bk_restore(M, id1, "a.txt", "/etc", 0, " (restored)", &o);
+ CHECK(rc != 0, "destination outside the roots rejected");
rc = bk_restore(M, id1, "a.txt", H, 0, "/x", &o);
- CHECK(rc != 0, "sufijo con barra rechazado");
- /* un enlace en la carpeta personal que apunta a una carpeta protegida */
- snprintf(p, sizeof p, "%s/atajo", H);
+ CHECK(rc != 0, "suffix with a slash rejected");
+ /* a link in the home folder pointing to a protected folder */
+ snprintf(p, sizeof p, "%s/shortcut", H);
snprintf(q, sizeof q, "%s/.local/share/applications", H);
mkdir(q, 0700);
symlink(q, p);
- snap_path(id1, "atajo", plant, sizeof plant); unlink(plant); mkdir(plant, 0700);
- snap_path(id1, "atajo/x.desktop", plant, sizeof plant);
+ snap_path(id1, "shortcut", plant, sizeof plant); unlink(plant); mkdir(plant, 0700);
+ snap_path(id1, "shortcut/x.desktop", plant, sizeof plant);
f = fopen(plant, "w"); if (f) { fputs("x", f); fclose(f); }
- rc = bk_restore(M, id1, "atajo/x.desktop", H, 0, " (restaurado)", &o);
+ rc = bk_restore(M, id1, "shortcut/x.desktop", H, 0, " (restored)", &o);
snprintf(p, sizeof p, "%s/x.desktop", q);
- CHECK(!exists(p), "no escribe en una protegida a través de un enlace (%d)", rc);
+ CHECK(!exists(p), "does not write into a protected folder through a link (%d)", rc);
- /* poda: sin lugar, queda solo la más nueva */
+ /* pruning: out of space, only the newest stays */
int before = bk_list(M, ids, 16);
bk_prune(M, time(NULL), UINT64_MAX);
int after = bk_list(M, ids, 16);
- CHECK(before == 3 && after == 1 && !strcmp(ids[0], id3), "poda por lugar: queda la última (%d → %d)", before, after);
- CHECK(bk_delete(M, "../../x") != 0, "borrar con nombre inválido");
+ CHECK(before == 3 && after == 1 && !strcmp(ids[0], id3), "pruning for space: the newest stays (%d → %d)", before, after);
+ CHECK(bk_delete(M, "../../x") != 0, "delete with an invalid name");
test_crypt();
char cmd[PATH_MAX + 32];
snprintf(cmd, sizeof cmd, "chmod -R u+w '%s' && rm -rf '%s'", T, T);
- if (system(cmd)) { /* queda en /tmp */ }
- printf("backup-test: %d comprobaciones, %d fallas\n", checks, fails);
+ if (system(cmd)) { /* left in /tmp */ }
+ printf("backup-test: %d checks, %d failures\n", checks, fails);
return fails ? 1 : 0;
}
diff --git a/server/tests/bt_test.c b/server/tests/bt_test.c
new file mode 100644
index 0000000..6b2c6ae
--- /dev/null
+++ b/server/tests/bt_test.c
@@ -0,0 +1,194 @@
+/* bt_test.c — BlueZ parsing for Settings → Bluetooth (src/hw/bt.c), without a bus: messages
+ * are built with our own D-Bus writer (vault/dbus.c), parsed by the strict reader and fed to
+ * the model. Covers GetManagedObjects, PropertiesChanged-style dictionaries, Battery1, removal,
+ * object path validation and the state JSON. Run by `make test` (mk/settings.mk). */
+#include "hw/bt.h"
+#include "vault/dbus.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+static void prop_s(DBuf *b, const char *k, const char *v) { dw_struct(b); dw_str(b, k); dw_variant(b, "s"); dw_str(b, v); }
+static void prop_o(DBuf *b, const char *k, const char *v) { dw_struct(b); dw_str(b, k); dw_variant(b, "o"); dw_str(b, v); }
+static void prop_b(DBuf *b, const char *k, int v) { dw_struct(b); dw_str(b, k); dw_variant(b, "b"); dw_bool(b, v); }
+static void prop_u(DBuf *b, const char *k, uint32_t v) { dw_struct(b); dw_str(b, k); dw_variant(b, "u"); dw_u32(b, v); }
+static void prop_y(DBuf *b, const char *k, uint8_t v) { dw_struct(b); dw_str(b, k); dw_variant(b, "y"); dw_u8(b, v); }
+static void prop_n(DBuf *b, const char *k, int16_t v) {
+ dw_struct(b); dw_str(b, k); dw_variant(b, "n");
+ dw_align(b, 2); dw_u8(b, (uint8_t)(v & 0xff)); dw_u8(b, (uint8_t)((uint16_t)v >> 8));
+}
+static void prop_as(DBuf *b, const char *k, const char *a, const char *c) {
+ dw_struct(b); dw_str(b, k); dw_variant(b, "as");
+ size_t m = dw_arr_begin(b, 4); dw_str(b, a); dw_str(b, c); dw_arr_end(b, m);
+}
+
+/* Builds a full message with that body and parses it back like one from the bus. */
+static int as_msg(const char *sig, DBuf *body, uint8_t type, DMsg *m) {
+ DHdr h = { .type = type, .serial = 7, .reply_serial = type == DBUS_RETURN ? 3 : 0, .sig = sig,
+ .path = type == DBUS_SIGNAL ? "/org/bluez/hci0/dev_00_AA_01_01_00_01" : NULL,
+ .iface = type == DBUS_SIGNAL ? "org.freedesktop.DBus.Properties" : NULL,
+ .member = type == DBUS_SIGNAL ? "PropertiesChanged" : NULL, .sender = ":1.5" };
+ DBuf out;
+ dw_init(&out);
+ if (dbus_build(&h, body, &out)) return -1;
+ long n = dbus_msg_size(out.p, out.n);
+ int r = n == (long)out.n ? dbus_msg_parse(out.p, out.n, m) : -1;
+ dw_free(&out);
+ return r;
+}
+
+static void managed_body(DBuf *b) {
+ dw_init(b);
+ size_t objs = dw_arr_begin(b, 8);
+ /* the adapter */
+ dw_struct(b); dw_str(b, "/org/bluez/hci0");
+ size_t ifs = dw_arr_begin(b, 8);
+ dw_struct(b); dw_str(b, "org.freedesktop.DBus.Introspectable");
+ size_t p0 = dw_arr_begin(b, 8); dw_arr_end(b, p0);
+ dw_struct(b); dw_str(b, "org.bluez.Adapter1");
+ size_t p1 = dw_arr_begin(b, 8);
+ prop_s(b, "Address", "00:AA:01:00:00:00");
+ prop_s(b, "Alias", "lordos-notes");
+ prop_b(b, "Powered", 1);
+ prop_b(b, "Discoverable", 0);
+ prop_b(b, "Discovering", 1);
+ prop_u(b, "Class", 0x6c010c);
+ prop_as(b, "UUIDs", "0000110e-0000-1000-8000-00805f9b34fb", "0000110c-0000-1000-8000-00805f9b34fb");
+ dw_arr_end(b, p1);
+ dw_arr_end(b, ifs);
+ /* a paired headset with a battery */
+ dw_struct(b); dw_str(b, "/org/bluez/hci0/dev_00_AA_01_01_00_01");
+ ifs = dw_arr_begin(b, 8);
+ dw_struct(b); dw_str(b, "org.bluez.Device1");
+ p1 = dw_arr_begin(b, 8);
+ prop_s(b, "Address", "00:AA:01:01:00:01");
+ prop_s(b, "Name", "Auriculares de prueba");
+ prop_s(b, "Alias", "Auriculares de prueba");
+ prop_s(b, "Icon", "audio-headset");
+ prop_o(b, "Adapter", "/org/bluez/hci0");
+ prop_u(b, "Class", 0x240404);
+ prop_b(b, "Paired", 1);
+ prop_b(b, "Trusted", 1);
+ prop_b(b, "Connected", 0);
+ prop_n(b, "RSSI", -67);
+ prop_as(b, "UUIDs", "0000110b-0000-1000-8000-00805f9b34fb", "0000111e-0000-1000-8000-00805f9b34fb");
+ dw_arr_end(b, p1);
+ dw_struct(b); dw_str(b, "org.bluez.Battery1");
+ p1 = dw_arr_begin(b, 8);
+ prop_y(b, "Percentage", 80);
+ dw_arr_end(b, p1);
+ dw_arr_end(b, ifs);
+ /* an unnamed LE device on a second adapter's path that does not exist (kept) */
+ dw_struct(b); dw_str(b, "/org/bluez/hci1/dev_11_22_33_44_55_66");
+ ifs = dw_arr_begin(b, 8);
+ dw_struct(b); dw_str(b, "org.bluez.Device1");
+ p1 = dw_arr_begin(b, 8);
+ prop_s(b, "Address", "11:22:33:44:55:66");
+ dw_arr_end(b, p1);
+ dw_arr_end(b, ifs);
+ /* something that is not BlueZ's: ignored */
+ dw_struct(b); dw_str(b, "/org/bluez");
+ ifs = dw_arr_begin(b, 8);
+ dw_struct(b); dw_str(b, "org.bluez.AgentManager1");
+ p1 = dw_arr_begin(b, 8); dw_arr_end(b, p1);
+ dw_arr_end(b, ifs);
+ dw_arr_end(b, objs);
+}
+
+int main(void) {
+ CHECK(bt_path_valid("/org/bluez/hci0"));
+ CHECK(bt_path_valid("/org/bluez/hci12/dev_00_AA_01_01_00_01"));
+ CHECK(!bt_path_valid("/org/bluez/hci0/dev_00_AA_01_01_00"));
+ CHECK(!bt_path_valid("/org/bluez/hci0/dev_00_AA_01_01_00_0G"));
+ CHECK(!bt_path_valid("/org/bluez/hci0/dev_00_AA_01_01_00_01/sep1"));
+ CHECK(!bt_path_valid("/org/bluez/hcix"));
+ CHECK(!bt_path_valid("/org/evil/hci0"));
+ CHECK(!bt_path_valid(NULL));
+
+ BtModel *m = bt_model();
+ memset(m, 0, sizeof *m);
+ DBuf b;
+ managed_body(&b);
+ DMsg msg;
+ CHECK(as_msg("a{oa{sa{sv}}}", &b, DBUS_RETURN, &msg) == 0);
+ dw_free(&b);
+ CHECK(bt_parse_managed(m, &msg) == 0);
+ dbus_msg_free(&msg);
+ CHECK(m->nadapters == 1);
+ CHECK(!strcmp(m->adapters[0].address, "00:AA:01:00:00:00") && !strcmp(m->adapters[0].alias, "lordos-notes"));
+ CHECK(m->adapters[0].powered && !m->adapters[0].discoverable && m->adapters[0].discovering);
+ CHECK(m->ndevices == 2);
+ BtDevice *d = &m->devices[0];
+ CHECK(!strcmp(d->path, "/org/bluez/hci0/dev_00_AA_01_01_00_01") && !strcmp(d->adapter, "/org/bluez/hci0"));
+ CHECK(!strcmp(d->name, "Auriculares de prueba") && !strcmp(d->icon, "audio-headset") && d->cls == 0x240404);
+ CHECK(d->paired && d->trusted && !d->connected && d->has_rssi && d->rssi == -67 && d->battery == 80);
+ CHECK(m->devices[1].battery == -1 && !strcmp(m->devices[1].adapter, "/org/bluez/hci1"));
+
+ /* PropertiesChanged on the device: connected, battery gone */
+ dw_init(&b);
+ dw_str(&b, "org.bluez.Device1");
+ size_t a = dw_arr_begin(&b, 8);
+ prop_b(&b, "Connected", 1);
+ prop_s(&b, "Alias", "Mis auriculares");
+ dw_arr_end(&b, a);
+ a = dw_arr_begin(&b, 4);
+ dw_str(&b, "RSSI");
+ dw_arr_end(&b, a);
+ CHECK(as_msg("sa{sv}as", &b, DBUS_SIGNAL, &msg) == 0);
+ dw_free(&b);
+ DRd r;
+ dr_init(&r, &msg);
+ const char *iface = dr_str(&r, NULL);
+ CHECK(iface && !strcmp(iface, "org.bluez.Device1"));
+ bt_apply_props(m, msg.path, iface, &r);
+ CHECK(!r.err);
+ dbus_msg_free(&msg);
+ CHECK(d->connected && !strcmp(d->alias, "Mis auriculares"));
+ bt_remove_object(m, d->path, "org.bluez.Battery1");
+ CHECK(d->battery == -1);
+
+ char *j = bt_state_json();
+ CHECK(j != NULL);
+ /* without bluetoothd on the bus the state says so, but still lists what is in the model */
+ CHECK(j && strstr(j, "\"available\":false") && strstr(j, "\"name\":\"Mis auriculares\"") && strstr(j, "\"connected\":true"));
+ CHECK(j && strstr(j, "\"rssi\":-67") && !strstr(j, "11:22:33:44:55:66")); /* other adapter's device: not listed */
+ free(j);
+
+ /* a truncated dictionary is rejected by the reader, the model is not corrupted */
+ dw_init(&b);
+ dw_str(&b, "org.bluez.Device1");
+ a = dw_arr_begin(&b, 8);
+ prop_b(&b, "Paired", 0);
+ dw_arr_end(&b, a);
+ a = dw_arr_begin(&b, 4);
+ dw_arr_end(&b, a);
+ CHECK(as_msg("sa{sv}as", &b, DBUS_SIGNAL, &msg) == 0);
+ msg.body_len -= 6; /* cut inside the dictionary */
+ dr_init(&r, &msg);
+ iface = dr_str(&r, NULL);
+ bt_apply_props(m, msg.path, iface, &r);
+ CHECK(r.err);
+ dbus_msg_free(&msg);
+ dw_free(&b);
+
+ /* removing the adapter takes its devices */
+ bt_remove_object(m, "/org/bluez/hci0", "org.bluez.Adapter1");
+ CHECK(m->nadapters == 0 && m->ndevices == 1 && !strcmp(m->devices[0].address, "11:22:33:44:55:66"));
+ bt_remove_object(m, "/org/bluez/hci1/dev_11_22_33_44_55_66", "org.bluez.Device1");
+ CHECK(m->ndevices == 0);
+
+ /* a reply with the wrong signature */
+ dw_init(&b);
+ dw_str(&b, "x");
+ CHECK(as_msg("s", &b, DBUS_RETURN, &msg) == 0);
+ CHECK(bt_parse_managed(m, &msg) != 0);
+ dbus_msg_free(&msg);
+ dw_free(&b);
+
+ printf("bt: %d/%d passed\n", checks - fails, checks);
+ return fails != 0;
+}
diff --git a/server/tests/disk_cli.c b/server/tests/disk_cli.c
index 8fedc4f..bbe9d88 100644
--- a/server/tests/disk_cli.c
+++ b/server/tests/disk_cli.c
@@ -1,12 +1,12 @@
-/* disk_cli.c — corre una acción disk-* como el ayudante, para probar a mano en la VM (no es parte de
- * `make test`: necesita root y dispositivos de verdad). Ver docs/SISTEMA.md, «Discos».
+/* disk_cli.c — runs a disk-* action like the helper does, for manual testing on the VM (not part of
+ * `make test`: it needs root and real devices). See docs/SYSTEM.md, "Disks".
*
- * build/disk-cli list la lista que ve lord.disks.list()
- * build/disk-cli system <disco> ¿es del sistema?
- * sudo build/disk-cli [-u usuario] [-n] <acción> '<arg con \n>'
- * -n: como un usuario que no es administrador
+ * build/disk-cli list the list lord.disks.list() sees
+ * build/disk-cli system <disk> is it the system disk?
+ * sudo build/disk-cli [-u user] [-n] <action> '<arg with \n>'
+ * -n: as a user who is not an administrator
*
- * admin_say/admin_run son versiones mínimas de las de admin.c (imprimen en la salida). */
+ * admin_say/admin_run are minimal versions of the ones in admin.c (they print to stdout). */
#include "disk/disk.h"
#include <errno.h>
@@ -70,18 +70,18 @@ static void unescape(char *s) {
}
int main(int argc, char **argv) {
- prctl(PR_SET_NAME, "lord-admin"); /* como el ayudante (disk-cancel lo verifica) */
+ prctl(PR_SET_NAME, "lord-admin"); /* like the helper (disk-cancel checks it) */
const char *user = getenv("SUDO_USER");
int admin = 1, i = 1;
for (; i < argc && argv[i][0] == '-'; i++) {
if (!strcmp(argv[i], "-u") && i + 1 < argc) user = argv[++i];
else if (!strcmp(argv[i], "-n")) admin = 0;
}
- if (i >= argc) { fprintf(stderr, "uso: disk-cli list | system <disco> | [-u usuario] [-n] <acción> [arg]\n"); return 2; }
+ if (i >= argc) { fprintf(stderr, "usage: disk-cli list | system <disk> | [-u user] [-n] <action> [arg]\n"); return 2; }
if (!strcmp(argv[i], "list")) { char *j = disk_list_json(); puts(j ? j : "null"); free(j); return 0; }
if (!strcmp(argv[i], "system") && i + 1 < argc) { printf("%d\n", disk_is_system(argv[i + 1])); return 0; }
struct passwd *pw = getpwnam(user ? user : "root");
- if (!pw) { fprintf(stderr, "usuario desconocido\n"); return 2; }
+ if (!pw) { fprintf(stderr, "unknown user\n"); return 2; }
AdminReq r = { .id = 1, .user = pw->pw_name, .home = pw->pw_dir, .uid = pw->pw_uid, .gid = pw->pw_gid, .admin = admin };
char *arg = strdup(i + 1 < argc ? argv[i + 1] : "");
unescape(arg);
@@ -92,6 +92,6 @@ int main(int argc, char **argv) {
};
for (size_t k = 0; k < sizeof acts / sizeof *acts; k++)
if (!strcmp(acts[k].n, argv[i])) { acts[k].fn(&r, arg, strlen(arg)); free(arg); return 0; }
- fprintf(stderr, "acción desconocida\n");
+ fprintf(stderr, "unknown action\n");
return 2;
}
diff --git a/server/tests/homedirs_test.c b/server/tests/homedirs_test.c
index 781602e..b81c9b2 100644
--- a/server/tests/homedirs_test.c
+++ b/server/tests/homedirs_test.c
@@ -1,6 +1,6 @@
-/* homedirs_test.c — carpetas comunes del usuario (src/users/homedirs.c): las de cada idioma,
- * user-dirs.dirs y user-dirs.locale, que una segunda vez no pisa nada y que no sigue enlaces.
- * Corre sin root: el dueño es el propio usuario. */
+/* homedirs_test.c — the user's common folders (src/users/homedirs.c): each language's names,
+ * user-dirs.dirs and user-dirs.locale, a second run overwrites nothing, and symlinks are not
+ * followed. Runs without root: the owner is the current user. */
#include "users/homedirs.h"
#include <stdio.h>
@@ -10,7 +10,7 @@
#include <unistd.h>
static int fails;
-#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FALLA %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)
+#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL %s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)
static int is_dir(const char *base, const char *name) {
char p[512];
@@ -36,25 +36,25 @@ static void lang(const char *locale, const char *const want[6], const char *xdg_
if (!mkdtemp(home)) { perror("mkdtemp"); exit(1); }
CHECK(homedirs_create(home, getuid(), getgid(), locale) == 0, "%s: homedirs_create", locale);
for (int i = 0; i < 6; i++) {
- CHECK(is_dir(home, want[i]), "%s: falta %s", locale, want[i]);
- CHECK(!strcmp(homedirs_name(homedirs_ui_lang(locale), i), want[i]), "%s: nombre %d", locale, i);
+ CHECK(is_dir(home, want[i]), "%s: missing %s", locale, want[i]);
+ CHECK(!strcmp(homedirs_name(homedirs_ui_lang(locale), i), want[i]), "%s: name %d", locale, i);
}
char *d = slurp(home, ".config/user-dirs.dirs");
- CHECK(d && strstr(d, xdg_doc), "%s: user-dirs.dirs sin %s", locale, xdg_doc);
- CHECK(d && strstr(d, "XDG_TEMPLATES_DIR=\"$HOME/\""), "%s: plantillas", locale);
+ CHECK(d && strstr(d, xdg_doc), "%s: user-dirs.dirs lacks %s", locale, xdg_doc);
+ CHECK(d && strstr(d, "XDG_TEMPLATES_DIR=\"$HOME/\""), "%s: templates", locale);
char *l = slurp(home, ".config/user-dirs.locale");
- CHECK(l && !strncmp(l, loc, strlen(loc)), "%s: user-dirs.locale = %s", locale, l ? l : "(nada)");
- /* una segunda vez: no falla y no pisa lo que el usuario cambió */
+ CHECK(l && !strncmp(l, loc, strlen(loc)), "%s: user-dirs.locale = %s", locale, l ? l : "(none)");
+ /* a second run: succeeds and keeps what the user changed */
char p[512];
snprintf(p, sizeof p, "%s/.config/user-dirs.dirs", home);
FILE *f = fopen(p, "w");
if (f) { fputs("XDG_DOCUMENTS_DIR=\"$HOME/Mis cosas\"\n", f); fclose(f); }
- CHECK(homedirs_create(home, getuid(), getgid(), locale) == 0, "%s: segunda vez", locale);
+ CHECK(homedirs_create(home, getuid(), getgid(), locale) == 0, "%s: second run", locale);
d = slurp(home, ".config/user-dirs.dirs");
- CHECK(d && strstr(d, "Mis cosas"), "%s: pisó user-dirs.dirs", locale);
+ CHECK(d && strstr(d, "Mis cosas"), "%s: overwrote user-dirs.dirs", locale);
char cmd[600];
snprintf(cmd, sizeof cmd, "rm -rf '%s'", home);
- if (system(cmd)) { /* nada */ }
+ if (system(cmd)) { /* ignored */ }
}
int main(void) {
@@ -64,20 +64,20 @@ int main(void) {
lang("es_AR.UTF-8", es, "XDG_DOCUMENTS_DIR=\"$HOME/Documentos\"", "es_AR");
lang("en_US.UTF-8", en, "XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"", "en_US");
lang("pt_BR.UTF-8", pt, "XDG_DESKTOP_DIR=\"$HOME/Área de trabalho\"", "pt_BR");
- lang("C.UTF-8", es, "XDG_PICTURES_DIR=\"$HOME/Imágenes\"", "es_ES"); /* sin idioma: español */
+ lang("C.UTF-8", es, "XDG_PICTURES_DIR=\"$HOME/Imágenes\"", "es_ES"); /* no language: Spanish */
- /* ~/.config como enlace a otro lado: no se escribe a través de él */
+ /* ~/.config is a symlink elsewhere: nothing is written through it */
char home[] = "/tmp/homedirs-test-XXXXXX", other[] = "/tmp/homedirs-other-XXXXXX";
if (!mkdtemp(home) || !mkdtemp(other)) return 1;
char link[512];
snprintf(link, sizeof link, "%s/.config", home);
if (symlink(other, link)) return 1;
- CHECK(homedirs_create(home, getuid(), getgid(), "es_ES.UTF-8") != 0, "enlace: tendría que fallar");
- CHECK(!slurp(other, "user-dirs.dirs"), "enlace: escribió a través de ~/.config");
+ CHECK(homedirs_create(home, getuid(), getgid(), "es_ES.UTF-8") != 0, "symlink: should fail");
+ CHECK(!slurp(other, "user-dirs.dirs"), "symlink: wrote through ~/.config");
char cmd[600];
snprintf(cmd, sizeof cmd, "rm -rf '%s' '%s'", home, other);
- if (system(cmd)) { /* nada */ }
+ if (system(cmd)) { /* ignored */ }
- printf("homedirs: %s\n", fails ? "FALLA" : "ok");
+ printf("homedirs: %s\n", fails ? "FAIL" : "ok");
return fails ? 1 : 0;
}
diff --git a/server/tests/mail_test.c b/server/tests/mail_test.c
new file mode 100644
index 0000000..b9f9fd1
--- /dev/null
+++ b/server/tests/mail_test.c
@@ -0,0 +1,744 @@
+/* mail_test.c — parsers of lord-maild (docs/MAIL.md): IMAP responses, MIME (multipart,
+ * encodings, charsets), the HTML sanitizer against hostile input, iCalendar and vCard, and the
+ * WebDAV XML reader. Every parser is also fed thousands of randomly mutated inputs (a small
+ * deterministic fuzzer); run under -fsanitize=address,undefined in `make mail-asan`. */
+#include "mail/imapp.h"
+#include "mail/mime.h"
+#include "mail/html.h"
+#include "mail/xml.h"
+#include "mail/ical.h"
+#include "mail/vcard.h"
+#include "sec/json.h"
+#include "doc/wire.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <ctype.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0)
+#define CHECKS(a, b) do { checks++; if (strcmp((a), (b))) { fails++; fprintf(stderr, "FAIL %s:%d: \"%s\" != \"%s\"\n", __FILE__, __LINE__, (a), (b)); } } while (0)
+
+static unsigned long long rng = 88172645463325252ull;
+static unsigned rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return (unsigned)rng; }
+
+/* Mutates a copy of s: flips, inserts, deletes and duplicates bytes. */
+static char *mutate(const char *s, size_t n, size_t *olen) {
+ size_t cap = n * 2 + 64;
+ char *o = malloc(cap);
+ memcpy(o, s, n);
+ size_t len = n;
+ int k = 1 + (int)(rnd() % 8);
+ static const char tokens[][8] = { "<", ">", "\"", "{", "}", "(", ")", "\r\n", ":", ";", "=?", "?=", "&", "#", "--", "\\", "[", "]", "=", "\0" };
+ for (int i = 0; i < k; i++) {
+ unsigned op = rnd() % 5;
+ size_t at = len ? rnd() % len : 0;
+ if (op == 0 && len) o[at] = (char)rnd();
+ else if (op == 1 && len + 8 < cap) { const char *t = tokens[rnd() % (sizeof tokens / sizeof tokens[0])]; size_t tl = strlen(t) ? strlen(t) : 1; memmove(o + at + tl, o + at, len - at); memcpy(o + at, t, tl); len += tl; }
+ else if (op == 2 && len) { size_t d = 1 + rnd() % 8; if (d > len - at) d = len - at; memmove(o + at, o + at + d, len - at - d); len -= d; }
+ else if (op == 3 && len) { size_t d = 1 + rnd() % 32; if (at + d > len) d = len - at; if (len + d < cap) { memmove(o + at + d, o + at, len - at); memcpy(o + at, o + at + d, d); len += d; } }
+ else if (op == 4) len = at; /* truncate */
+ }
+ *olen = len;
+ return o;
+}
+
+/* ---- IMAP ---- */
+
+static void test_imap(void) {
+ IResp r;
+ const char *l1 = "* 12 FETCH (UID 4827 FLAGS (\\Seen $label1) INTERNALDATE \"17-Oct-2026 10:00:00 -0300\" RFC822.SIZE 4410 "
+ "BODY[HEADER.FIELDS (FROM SUBJECT)] {34}\r\nFrom: [email protected]\r\nSubject: hola (x)\r\n\r\n BODY[TEXT]<0> NIL)\r\n";
+ CHECK(imap_parse(l1, strlen(l1), &r) == 0);
+ CHECKS(r.tag, "*");
+ CHECK(iv_num(r.first, 0) == 12);
+ CHECK(iv_is(r.first->next, "FETCH"));
+ IVal *list = r.first->next->next;
+ CHECK(list && list->type == IV_LIST);
+ CHECK(iv_num(imap_fetch_item(list, "UID"), 0) == 4827);
+ IVal *fl = imap_fetch_item(list, "FLAGS");
+ CHECK(fl && fl->type == IV_LIST && iv_count(fl->kid) == 2 && iv_is(fl->kid, "\\Seen"));
+ IVal *hdr = imap_fetch_item(list, "BODY[HEADER");
+ CHECK(hdr && hdr->type == IV_STR && hdr->n == 34 && !memcmp(hdr->s, "From: [email protected]", 11));
+ IVal *txt = imap_fetch_item(list, "BODY[TEXT]");
+ CHECK(txt && txt->type == IV_NIL);
+ char d[64];
+ iv_copy(imap_fetch_item(list, "INTERNALDATE"), d, sizeof d);
+ CHECKS(d, "17-Oct-2026 10:00:00 -0300");
+ imap_resp_free(&r);
+
+ const char *l2 = "a3 OK [UIDVALIDITY 1729000000] [HIGHESTMODSEQ 99] SELECT done\r\n";
+ CHECK(imap_parse(l2, strlen(l2), &r) == 0);
+ unsigned long long v = 0;
+ CHECK(imap_code_num(&r, "UIDVALIDITY", &v) && v == 1729000000ull);
+ CHECK(imap_code_num(&r, "HIGHESTMODSEQ", &v) && v == 99);
+ CHECK(!imap_code_num(&r, "UIDNEXT", &v));
+ CHECKS(r.tag, "a3");
+ imap_resp_free(&r);
+
+ const char *l3 = "* LIST (\\HasNoChildren \\Sent) \"/\" \"Enviados &AOk-xito\"\r\n";
+ CHECK(imap_parse(l3, strlen(l3), &r) == 0);
+ char name[128], dec[128];
+ iv_copy(iv_at(r.first, 3), name, sizeof name);
+ imap_utf7_decode(name, dec, sizeof dec);
+ CHECKS(dec, "Enviados éxito");
+ char enc[128];
+ imap_utf7_encode("Entwürfe & Co", enc, sizeof enc);
+ CHECKS(enc, "Entw&APw-rfe &- Co");
+ imap_utf7_decode(enc, dec, sizeof dec);
+ CHECKS(dec, "Entwürfe & Co");
+ imap_utf7_encode("📁 Mail", enc, sizeof enc);
+ imap_utf7_decode(enc, dec, sizeof dec);
+ CHECKS(dec, "📁 Mail");
+ imap_resp_free(&r);
+
+ /* bad literals and lists */
+ const char *bad[] = { "* 1 FETCH (UID 2\r\n", "* 1 FETCH {99}\r\nabc\r\n", "* 1 FETCH ((((\r\n", "* x \"unterminated\r\n", "* 1 FETCH )\r\n", "* {4294967296}\r\n" };
+ for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) { CHECK(imap_parse(bad[i], strlen(bad[i]), &r) == -1); }
+
+ uint32_t uids[] = { 1, 2, 3, 5, 7, 8, 9, 20 };
+ char set[64];
+ imap_uidset(uids, 8, set, sizeof set);
+ CHECKS(set, "1:3,5,7:9,20");
+ uint32_t back[16];
+ CHECK(imap_parse_uidset(set, back, 16) == 8 && back[3] == 5 && back[7] == 20);
+ int lit;
+ char *q = imap_quote("a\"b\\c", 0, &lit);
+ CHECKS(q, "\"a\\\"b\\\\c\""); CHECK(!lit); free(q);
+ q = imap_quote("contraseña", 1, &lit);
+ CHECK(lit && !strncmp(q, "{11+}\r\n", 7)); free(q);
+
+ /* fuzz */
+ for (int it = 0; it < 20000; it++) {
+ size_t n;
+ char *m = mutate(l1, strlen(l1), &n);
+ if (imap_parse(m, n, &r) == 0) {
+ IVal *lst = iv_at(r.first, 2);
+ if (lst) { IVal *x = imap_fetch_item(lst, "BODY[HEADER"); if (x && x->type == IV_STR) CHECK(x->s >= m && x->s + x->n <= m + n + 0); }
+ imap_resp_free(&r);
+ }
+ free(m);
+ }
+}
+
+/* ---- MIME ---- */
+
+static const char *MSG1 =
+ "Return-Path: <x@y>\r\n"
+ "From: =?ISO-8859-1?Q?Jos=E9_P=E9rez?= <[email protected]>\r\n"
+ "To: \"Ana, la jefa\" <[email protected]>, [email protected] (Beto B.), Grupo: [email protected], [email protected];\r\n"
+ "Subject: =?UTF-8?B?UmU6IFJlOiBQcmVzdXB1ZXN0byDwn5iA?=\r\n"
+ " =?UTF-8?Q?_final?=\r\n"
+ "Date: Fri, 17 Oct 2026 14:05:00 -0300\r\n"
+ "Message-ID: <[email protected]>\r\n"
+ "MIME-Version: 1.0\r\n"
+ "Content-Type: multipart/mixed; boundary=\"XX\"\r\n"
+ "\r\n"
+ "preamble\r\n"
+ "--XX\r\n"
+ "Content-Type: multipart/alternative; boundary=YY\r\n"
+ "\r\n"
+ "--YY\r\n"
+ "Content-Type: text/plain; charset=windows-1252\r\n"
+ "Content-Transfer-Encoding: quoted-printable\r\n"
+ "\r\n"
+ "Hola =93mundo=94 =80 caf=E9 y una l=EDnea muy larga que se corta =\r\n"
+ "aqu=ED.\r\n"
+ "--YY\r\n"
+ "Content-Type: text/html; charset=utf-8\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "\r\n"
+ "PHA+SG9sYSA8Yj5tdW5kbzwvYj48L3A+\r\n"
+ "--YY--\r\n"
+ "--XX\r\n"
+ "Content-Type: application/pdf; name=\"=?UTF-8?Q?informe_=C3=B1.pdf?=\"\r\n"
+ "Content-Disposition: attachment; filename*=UTF-8''presupuesto%20a%C3%B1o.pdf\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "\r\n"
+ "JVBERi0xLjQK\r\n"
+ "--XX\r\n"
+ "Content-Type: text/calendar; method=REQUEST; charset=utf-8\r\n"
+ "\r\n"
+ "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n"
+ "--XX--\r\n"
+ "epilogue\r\n";
+
+static void test_mime(void) {
+ const char *h, *b;
+ size_t hl, bl;
+ mime_split(MSG1, strlen(MSG1), &h, &hl, &b, &bl);
+ char v[512], d[512];
+ CHECK(mime_header(h, hl, "subject", v, sizeof v));
+ mime_decode_words(v, d, sizeof d);
+ CHECKS(d, "Re: Re: Presupuesto 😀 final");
+ char base[256];
+ mime_base_subject(d, base, sizeof base);
+ CHECKS(base, "Presupuesto 😀 final");
+ mime_header(h, hl, "From", v, sizeof v);
+ MimeAddr a[8];
+ CHECK(mime_addrs(v, a, 8) == 1);
+ CHECKS(a[0].name, "José Pérez");
+ CHECKS(a[0].email, "[email protected]");
+ mime_header(h, hl, "To", v, sizeof v);
+ int n = mime_addrs(v, a, 8);
+ CHECK(n == 4);
+ if (n == 4) { CHECKS(a[0].name, "Ana, la jefa"); CHECKS(a[1].email, "[email protected]"); CHECKS(a[1].name, "Beto B."); CHECKS(a[2].email, "[email protected]"); CHECKS(a[3].email, "[email protected]"); }
+ mime_header(h, hl, "Date", v, sizeof v);
+ CHECK(mime_date(v) == 1792256700);
+ CHECK(mime_date("17 Oct 2026 17:05:00 GMT") == 1792256700);
+ CHECK(mime_date("Fri, 17 Oct 26 17:05 +0000") == 1792256700 - 0);
+ CHECK(mime_date("garbage") == 0);
+
+ MimeMsg *m = malloc(sizeof *m);
+ mime_parse(MSG1, strlen(MSG1), m);
+ CHECK(m->nparts == 6);
+ CHECKS(m->parts[0].subtype, "mixed");
+ CHECKS(m->parts[1].subtype, "alternative");
+ CHECKS(m->parts[2].subtype, "plain");
+ CHECK(m->parts[2].parent == 1 && m->parts[4].parent == 0);
+ size_t tl;
+ char *t = mime_part_text(&m->parts[2], &tl);
+ CHECKS(t, "Hola “mundo” € café y una línea muy larga que se corta aquí.");
+ free(t);
+ t = mime_part_text(&m->parts[3], &tl);
+ CHECKS(t, "<p>Hola <b>mundo</b></p>");
+ free(t);
+ CHECKS(m->parts[4].filename, "presupuesto año.pdf");
+ CHECKS(m->parts[4].disposition, "attachment");
+ size_t pl;
+ char *pdf = mime_decode_body(&m->parts[4], &pl);
+ CHECK(pl == 9 && !memcmp(pdf, "%PDF-1.4\n", 9));
+ free(pdf);
+ CHECKS(m->parts[5].method, "REQUEST");
+
+ /* charsets */
+ size_t ol;
+ char *u = charset_to_utf8("koi8-r", "\xf0\xd2\xc9\xd7\xc5\xd4", 6, &ol);
+ CHECKS(u, "Привет"); free(u);
+ u = charset_to_utf8("ISO-8859-15", "\xa4\xbd", 2, &ol);
+ CHECKS(u, "€œ"); free(u);
+ u = charset_to_utf8("utf-16le", "h\0o\0l\0a\0", 8, &ol);
+ CHECKS(u, "hola"); free(u);
+ u = charset_to_utf8("utf-8", "a\xff\xc3(b", 5, &ol);
+ CHECKS(u, "a\xef\xbf\xbd\xef\xbf\xbd(b"); free(u);
+ u = charset_to_utf8("x-unknown", "plain", 5, &ol);
+ CHECKS(u, "plain"); free(u);
+ u = charset_to_utf8("us-ascii", "caf\xe9", 4, &ol);
+ CHECKS(u, "café"); free(u);
+ /* RFC 2231 continuations */
+ char p[256];
+ CHECK(mime_param("attachment; filename*0*=utf-8''a%C3%B1o; filename*1=\"_2026.txt\"", "filename", p, sizeof p));
+ CHECKS(p, "año_2026.txt");
+ CHECK(mime_param("text/plain; charset = \"UTF-8\" ; format=flowed", "charset", p, sizeof p));
+ CHECKS(p, "UTF-8");
+ /* encoders */
+ char *eh = mime_encode_header("Café con leche");
+ CHECKS(eh, "=?UTF-8?B?Q2Fmw6kgY29uIGxlY2hl?=");
+ free(eh);
+ eh = mime_format_addr("Pérez, José", "[email protected]");
+ CHECK(!strncmp(eh, "=?UTF-8?B?", 10) && strstr(eh, "<[email protected]>"));
+ free(eh);
+ size_t ql;
+ char *qp = qp_encode("línea\n.punto final \n", 23, &ql);
+ char back[64];
+ size_t bl2 = qp_decode(qp, ql, back, 0);
+ back[bl2] = 0;
+ CHECKS(back, "línea\r\n.punto final \r\n");
+ free(qp);
+ unsigned char raw[300];
+ for (int i = 0; i < 300; i++) raw[i] = (unsigned char)(i * 7);
+ size_t el;
+ char *b64 = b64_encode(raw, 300, 1, &el);
+ unsigned char dec[300];
+ CHECK(b64_decode(b64, el, dec) == 300 && !memcmp(dec, raw, 300));
+ free(b64);
+
+ /* deep nesting is bounded */
+ char *deep = malloc(64 * 1024);
+ size_t dl = 0;
+ for (int i = 0; i < 200; i++) dl += (size_t)snprintf(deep + dl, 64 * 1024 - dl, "Content-Type: multipart/mixed; boundary=b%d\r\n\r\n--b%d\r\n", i, i);
+ mime_parse(deep, dl, m);
+ CHECK(m->nparts <= MIME_MAX_PARTS);
+ for (int i = 0; i < m->nparts; i++) CHECK(m->parts[i].depth < MIME_MAX_DEPTH);
+ free(deep);
+
+ /* fuzz */
+ for (int it = 0; it < 6000; it++) {
+ size_t fl;
+ char *f = mutate(MSG1, strlen(MSG1), &fl);
+ mime_parse(f, fl, m);
+ for (int i = 0; i < m->nparts; i++) {
+ MimePart *pp = &m->parts[i];
+ CHECK(pp->body >= f && pp->body + pp->blen <= f + fl);
+ size_t xl;
+ char *x = mime_part_text(pp, &xl);
+ free(x);
+ }
+ const char *fh, *fb; size_t fhl, fbl;
+ mime_split(f, fl, &fh, &fhl, &fb, &fbl);
+ char sv[300], sd[300];
+ mime_header(fh, fhl, "Subject", sv, sizeof sv);
+ mime_decode_words(sv, sd, sizeof sd);
+ mime_header(fh, fhl, "To", sv, sizeof sv);
+ mime_addrs(sv, a, 8);
+ free(f);
+ }
+ free(m);
+}
+
+/* ---- HTML ---- */
+
+/* A small JSON validator without sec/json's depth limit (the HTML tree nests deeper than the
+ * signed-package files it was made for); also checks every link and image source is safe. */
+typedef struct { const char *s; size_t n, i; int depth, unsafe; char key[16]; } Jv;
+static void jws(Jv *v) { while (v->i < v->n && (v->s[v->i] == ' ' || v->s[v->i] == '\n' || v->s[v->i] == '\t' || v->s[v->i] == '\r')) v->i++; }
+static int jval(Jv *v);
+/* the sanitizer's rule: the scheme (ignoring blanks and controls) is http, https or mailto */
+static int scheme_ok(const char *val) {
+ char sch[16];
+ size_t n = 0;
+ for (const char *c = val; *c && *c != ':' && n + 1 < sizeof sch; c++) if ((unsigned char)*c > 0x20) sch[n++] = (char)tolower((unsigned char)*c);
+ sch[n] = 0;
+ return strchr(val, ':') && (!strcmp(sch, "http") || !strcmp(sch, "https") || !strcmp(sch, "mailto"));
+}
+static int jstr(Jv *v, char *out, size_t cap) {
+ if (v->i >= v->n || v->s[v->i] != '"') return 0;
+ v->i++;
+ size_t o = 0;
+ while (v->i < v->n && v->s[v->i] != '"') {
+ unsigned char c = (unsigned char)v->s[v->i];
+ if (c < 0x20) return 0;
+ if (c == '\\') { v->i++; if (v->i >= v->n) return 0; c = (unsigned char)v->s[v->i]; if (c == 'u') { if (v->i + 4 >= v->n) return 0; v->i += 4; c = '?'; } }
+ if (out && o + 1 < cap) out[o++] = (char)c;
+ v->i++;
+ }
+ if (out && cap) out[o] = 0;
+ if (v->i >= v->n) return 0;
+ v->i++;
+ return 1;
+}
+static int jval(Jv *v) {
+ jws(v);
+ if (v->i >= v->n) return 0;
+ char c = v->s[v->i];
+ if (c == '{' || c == '[') {
+ if (++v->depth > 512) return 0;
+ v->i++;
+ jws(v);
+ char close = c == '{' ? '}' : ']';
+ if (v->i < v->n && v->s[v->i] == close) { v->i++; v->depth--; return 1; }
+ for (;;) {
+ char key[16] = "";
+ if (c == '{') { jws(v); if (!jstr(v, key, sizeof key)) return 0; jws(v); if (v->i >= v->n || v->s[v->i] != ':') return 0; v->i++; }
+ jws(v);
+ if ((!strcmp(key, "h") || !strcmp(key, "src")) && v->i < v->n && v->s[v->i] == '"') {
+ char val[64];
+ size_t at = v->i;
+ if (!jstr(v, val, sizeof val)) return 0;
+ if (!strcmp(key, "h") && !scheme_ok(val)) { v->unsafe = 1; fprintf(stderr, "bad h=%s\n", val); }
+ if (!strcmp(key, "src") && strncmp(val, "cid:", 4) && strncmp(val, "r:", 2) && strncmp(val, "d:", 2)) { v->unsafe = 1; fprintf(stderr, "bad src=%s\n", val); }
+ (void)at;
+ } else if (!jval(v)) return 0;
+ jws(v);
+ if (v->i < v->n && v->s[v->i] == ',') { v->i++; continue; }
+ if (v->i < v->n && v->s[v->i] == close) { v->i++; v->depth--; return 1; }
+ return 0;
+ }
+ }
+ if (c == '"') return jstr(v, NULL, 0);
+ if (!strncmp(v->s + v->i, "true", 4)) { v->i += 4; return 1; }
+ if (!strncmp(v->s + v->i, "false", 5)) { v->i += 5; return 1; }
+ if (!strncmp(v->s + v->i, "null", 4)) { v->i += 4; return 1; }
+ size_t a = v->i;
+ while (v->i < v->n && (strchr("+-.eE", v->s[v->i]) || (v->s[v->i] >= '0' && v->s[v->i] <= '9'))) v->i++;
+ return v->i > a;
+}
+static int json_ok(const char *s, size_t n) {
+ Jv v = { s, n, 0, 0, 0, "" };
+ int ok = jval(&v);
+ jws(&v);
+ if (!ok || v.i != n) { fprintf(stderr, "bad JSON at %zu: %.200s\n", v.i, s + (v.i > 40 ? v.i - 40 : 0)); return 0; }
+ if (v.unsafe) { fprintf(stderr, "unsafe link or image source in: %.300s\n", s); return 0; }
+ return 1;
+}
+
+static void test_html(void) {
+ const char *evil =
+ "<html><head><title>x</title><style>body{background:url(http://evil/track.gif)}</style>"
+ "<script>alert(1)</script></head><body bgcolor=\"#f4f4f4\" onload=\"steal()\">"
+ "<div style=\"display:none\">PREHEADER secreto</div>"
+ "<span style=\"font-size:0;max-height:0;overflow:hidden\">oculto</span>"
+ "<table width=600 align=center cellpadding=8><tr><td bgcolor=#ffffff style=\"color:#333;padding:10px\">"
+ "<h1>Ofertas</h1><p>Hola <b>Ana</b> &amp; <i>Beto</i>&nbsp;&mdash;&#x1F600;&#128512; &bogus; &lt;b&gt;</p>"
+ "<a href=\"javascript:alert(1)\">clic</a> <a href=\" JaVa\tscript:x\">clic2</a>"
+ "<a href=\"https://evil.example.net/login\">https://www.mibanco.com/login</a>"
+ "<a href=\"https://www.mibanco.com/x\">mibanco.com</a>"
+ "<a href=\"https://[email protected]/\">entrar</a>"
+ "<a href=\"mailto:[email protected]\">[email protected]</a>"
+ "<img src=\"https://cdn.example.com/hero.png\" width=600 height=200 alt=\"Héroe\">"
+ "<img src=\"https://t.example.com/open.gif\" width=1 height=1>"
+ "<img src=\"cid:logo123\"><img src=\"file:///etc/passwd\"><img src=\"data:image/png;base64,iVBORw0KGgo=\">"
+ "<iframe src=\"http://evil\">no</iframe><object data=x><param name=a>obj</object>"
+ "<form action=http://evil><input name=pw><button>Enviar</button>texto del form</form>"
+ "<svg><script>alert(2)</script><text>svgtext</text></svg>"
+ "<!-- comentario --><![CDATA[ cdata ]]>"
+ "</td></tr></table><ul><li>uno<li>dos</ul><ol><li>a<li>b</ol>"
+ "<pre> linea 1\n linea 2</pre><blockquote>cita</blockquote><hr><p>fin";
+ HtmlStats st;
+ HtmlData data[HTML_MAX_DATA];
+ int nd = 0;
+ size_t n;
+ char *j = html_sanitize(evil, strlen(evil), &n, &st, data, &nd);
+ CHECK(j && json_ok(j, n));
+ CHECK(!strstr(j, "alert"));
+ CHECK(!strstr(j, "steal"));
+ CHECK(!strstr(j, "PREHEADER"));
+ CHECK(!strstr(j, "oculto"));
+ CHECK(!strstr(j, "javascript"));
+ CHECK(!strstr(j, "script"));
+ CHECK(!strstr(j, "passwd"));
+ CHECK(!strstr(j, "track.gif"));
+ CHECK(!strstr(j, "svgtext"));
+ CHECK(!strstr(j, "Enviar"));
+ CHECK(!strstr(j, "comentario"));
+ CHECK(strstr(j, "texto del form") != NULL);
+ CHECK(strstr(j, "Ofertas") != NULL);
+ CHECK(strstr(j, "😀") != NULL);
+ CHECK(strstr(j, "<b>") != NULL); /* &lt;b&gt; stays text */
+ CHECK(st.remote == 1);
+ CHECK(st.trackers == 1);
+ CHECK(st.cid == 1);
+ CHECK(st.data == 1 && nd == 1);
+ CHECK(st.warn == 3);
+ CHECK(strstr(j, "\"bg\":\"#f4f4f4\"") != NULL);
+ CHECK(strstr(j, "\"mk\":\"2.\"") != NULL);
+ CHECK(strstr(j, "{\"t\":\"tbl\"") != NULL);
+ for (int i = 0; i < nd; i++) free((void *)data[i].p);
+ free(j);
+
+ CHECK(html_link_warning("https://www.mibanco.com", "https://mibanco.com.evil.net/") != NULL);
+ CHECK(html_link_warning("www.mibanco.com", "https://login.mibanco.com/x") == NULL);
+ CHECK(html_link_warning("Ver más", "https://cualquier.net/") == NULL);
+ CHECK(html_link_warning("version 3.5", "https://x.net/") == NULL);
+ CHECK(html_link_warning("paypal.com", "http://192.168.1.4/") != NULL);
+
+ /* hostile: deep nesting, unclosed tags, huge attributes, broken entities */
+ size_t big = 400000;
+ char *b = malloc(big + 1);
+ size_t o = 0;
+ while (o + 12 < big) { memcpy(b + o, "<div><table>", 12); o += 12; }
+ b[o] = 0;
+ j = html_sanitize(b, o, &n, &st, NULL, NULL);
+ CHECK(j && json_ok(j, n));
+ free(j);
+ o = 0;
+ while (o + 30 < big) { memcpy(b + o, "<a href='https://x.y/'>&#99999999;", 30); o += 30; }
+ j = html_sanitize(b, o, &n, &st, NULL, NULL);
+ CHECK(j && json_ok(j, n));
+ free(j);
+ memset(b, '<', big);
+ j = html_sanitize(b, big, &n, &st, NULL, NULL);
+ CHECK(j && json_ok(j, n));
+ free(j);
+ free(b);
+
+ size_t tl;
+ char *txt = html_to_text("<p>Hola&nbsp;<b>Ana</b></p><script>x()</script><div>chau</div>", 63, &tl);
+ CHECKS(txt, "Hola Ana\nchau");
+ free(txt);
+
+ for (int it = 0; it < 4000; it++) {
+ size_t fl;
+ char *f = mutate(evil, strlen(evil), &fl);
+ j = html_sanitize(f, fl, &n, &st, data, &nd);
+ CHECK(j && json_ok(j, n));
+ /* "alert(" may survive as visible TEXT when the mutation breaks a tag (harmless: nothing
+ * runs), but never as a link or an image source: json_ok() checks those */
+ for (int i = 0; i < nd; i++) free((void *)data[i].p);
+ free(j);
+ txt = html_to_text(f, fl, &tl);
+ free(txt);
+ free(f);
+ }
+}
+
+/* ---- XML ---- */
+
+static const char *MULTI =
+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<d:multistatus xmlns:d=\"DAV:\" xmlns:cal=\"urn:ietf:params:xml:ns:caldav\" xmlns:x=\"http://apple.com/ns/ical/\">"
+ "<d:response><d:href>/ana/cal/</d:href><d:propstat><d:prop>"
+ "<d:displayname>Trabajo &amp; casa</d:displayname><x:calendar-color>#FF2968</x:calendar-color>"
+ "<d:resourcetype><d:collection/><cal:calendar/></d:resourcetype>"
+ "<cal:supported-calendar-component-set><cal:comp name=\"VEVENT\"/><cal:comp name='VTODO'/></cal:supported-calendar-component-set>"
+ "<d:getetag>\"abc\"</d:getetag></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>"
+ "<D:response xmlns:D=\"DAV:\"><D:href>/ana/b.ics</D:href><D:propstat><D:prop><cal:calendar-data><![CDATA[BEGIN:VCALENDAR]]></cal:calendar-data>"
+ "</D:prop></D:propstat></D:response></d:multistatus>";
+
+static void test_xml(void) {
+ const char *err;
+ MxNode *r = mx_parse(MULTI, strlen(MULTI), &err);
+ CHECK(r != NULL);
+ if (r) {
+ CHECKS(r->name, "multistatus");
+ CHECKS(r->ns, "DAV:");
+ MxNode *resp = mx_child(r, MX_NS_DAV, "response");
+ CHECK(resp != NULL);
+ char t[128];
+ MxNode *prop = mx_find(resp, MX_NS_DAV, "prop");
+ mx_child_text(prop, MX_NS_DAV, "displayname", t, sizeof t);
+ CHECKS(t, "Trabajo & casa");
+ mx_child_text(prop, MX_NS_APPLE, "calendar-color", t, sizeof t);
+ CHECKS(t, "#FF2968");
+ CHECK(mx_find(prop, MX_NS_CAL, "calendar") != NULL);
+ MxNode *r2 = mx_next(resp, MX_NS_DAV, "response");
+ CHECK(r2 != NULL);
+ MxNode *cd = mx_find(r2, MX_NS_CAL, "calendar-data");
+ CHECK(cd && !strcmp(mx_text(cd), "BEGIN:VCALENDAR"));
+ mx_free(r);
+ }
+ const char *bad[] = {
+ "<!DOCTYPE x [<!ENTITY a \"aaaa\">]><x>&a;</x>", "<a><b></a>", "<a>", "<a></a><b></b>", "<a x=\"1></a>", "<a>&#0;</a>",
+ "<a>&#xD800;</a>", "<a>&nope;</a>", "text<a/>", "<a><![CDATA[x</a>", "<a b='<'/>",
+ };
+ for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) { MxNode *x = mx_parse(bad[i], strlen(bad[i]), &err); CHECK(x == NULL); }
+ /* depth limit */
+ char *deep = malloc(MX_MAX_DEPTH * 8 + 64);
+ size_t o = 0;
+ for (int i = 0; i < MX_MAX_DEPTH + 5; i++) { memcpy(deep + o, "<a>", 3); o += 3; }
+ CHECK(mx_parse(deep, o, &err) == NULL);
+ free(deep);
+ char esc[64];
+ mx_escape(esc, sizeof esc, "a<b>&\"c");
+ CHECKS(esc, "a&lt;b&gt;&amp;&quot;c");
+ for (int it = 0; it < 30000; it++) {
+ size_t fl;
+ char *f = mutate(MULTI, strlen(MULTI), &fl);
+ MxNode *x = mx_parse(f, fl, &err);
+ if (x) { MxNode *k = mx_find(x, MX_NS_DAV, "href"); if (k) (void)mx_text(k); mx_free(x); }
+ free(f);
+ }
+}
+
+/* ---- iCalendar ---- */
+
+static const char *ICS =
+ "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nMETHOD:REQUEST\r\nPRODID:test\r\n"
+ "BEGIN:VEVENT\r\nUID:[email protected]\r\nSEQUENCE:2\r\n"
+ "DTSTART;TZID=Europe/Madrid:20261020T100000\r\nDTEND;TZID=Europe/Madrid:20261020T113000\r\n"
+ "SUMMARY:Revisi\\u00f3n\\, trimestral\\; Q4\r\nLOCATION:Sala 3\r\n"
+ "DESCRIPTION:Primera l\\nSegunda l\r\n y m\xc3\xa1s\r\n"
+ "RRULE:FREQ=WEEKLY;BYDAY=TU,TH;COUNT=6\r\nEXDATE;TZID=Europe/Madrid:20261022T100000\r\n"
+ "ORGANIZER;CN=\"Jefa, Ana\":mailto:[email protected]\r\n"
+ "ATTENDEE;CN=Beto;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:mailto:[email protected]\r\n"
+ "BEGIN:VALARM\r\nACTION:DISPLAY\r\nTRIGGER:-PT15M\r\nEND:VALARM\r\n"
+ "BEGIN:VALARM\r\nACTION:DISPLAY\r\nTRIGGER;RELATED=START:-P1D\r\nEND:VALARM\r\n"
+ "END:VEVENT\r\n"
+ "BEGIN:VEVENT\r\nUID:allday\r\nDTSTART;VALUE=DATE:20261231\r\nSUMMARY:Fin de a\xc3\xb1o\r\nEND:VEVENT\r\n"
+ "BEGIN:VTODO\r\nUID:todo-1\r\nSUMMARY:Comprar pan\r\nDUE;VALUE=DATE:20261019\r\nPRIORITY:1\r\nX-LORDOS-FLAGGED:1\r\n"
+ "STATUS:NEEDS-ACTION\r\nEND:VTODO\r\n"
+ "BEGIN:VEVENT\r\nUID:monthly\r\nDTSTART:20260131T120000Z\r\nDURATION:PT1H\r\nRRULE:FREQ=MONTHLY;BYDAY=-1FR;UNTIL=20260701T000000Z\r\nEND:VEVENT\r\n"
+ "BEGIN:VEVENT\r\nUID:win\r\nDTSTART;TZID=Pacific Standard Time:20260701T090000\r\nDTEND;TZID=Pacific Standard Time:20260701T100000\r\nEND:VEVENT\r\n"
+ "END:VCALENDAR\r\n";
+
+static int64_t occ[64];
+static int nocc;
+static void add_occ(void *u, int64_t t) { (void)u; if (nocc < 64) occ[nocc++] = t; }
+
+static void test_ical(void) {
+ ic_set_local_zone("America/Argentina/Buenos_Aires");
+ IcEvent *ev;
+ char method[24];
+ int n = ical_events(ICS, strlen(ICS), &ev, method, sizeof method);
+ CHECK(n == 5);
+ CHECKS(method, "REQUEST");
+ if (n < 5) return;
+ IcEvent *e = &ev[0];
+ CHECKS(e->uid, "[email protected]");
+ CHECKS(e->summary, "Revisiu00f3n, trimestral; Q4");
+ CHECKS(e->description, "Primera l\nSegunda l y más");
+ CHECK(e->start == 1792483200); /* 2026-10-20 10:00 CEST = 08:00Z */
+ CHECK(e->end - e->start == 5400);
+ CHECK(e->sequence == 2);
+ CHECK(e->nalarms == 2 && e->alarms[0] == 15 && e->alarms[1] == 1440);
+ CHECKS(e->organizer, "[email protected]");
+ CHECKS(e->organizer_name, "Jefa, Ana");
+ CHECK(e->natt == 1 && !strcmp(e->att[0].email, "[email protected]") && e->att[0].rsvp);
+ nocc = 0;
+ int k = ical_expand(e, 1792000000, 1800000000, 64, add_occ, NULL);
+ CHECK(k == 5); /* 6 by COUNT, one EXDATE */
+ if (k == 5) {
+ CHECK(occ[0] == 1792483200); /* Tue 20 */
+ CHECK(occ[1] == 1792483200 + 7 * 86400 + 3600); /* Tue 27, after the DST change: 10:00 CET = 09:00Z */
+ }
+ CHECK(ev[1].allday && ev[1].edate == ev[1].sdate + 1);
+ nocc = 0;
+ CHECK(ical_expand(&ev[1], 1798000000, 1799000000, 8, add_occ, NULL) == 1);
+ CHECK(ev[2].is_todo && ev[2].priority == 1 && ev[2].flagged && ev[2].due_allday && !ev[2].completed);
+ nocc = 0;
+ k = ical_expand(&ev[3], 1767225600, 1800000000, 64, add_occ, NULL);
+ CHECK(k == 5); /* last Fridays Feb..Jun 2026 (DTSTART is a Saturday) */
+ if (k >= 1) CHECK(occ[0] == 1772193600); /* 2026-02-27 12:00Z */
+ CHECK(ev[4].start == 1782921600); /* 09:00 PDT = 16:00Z */
+
+ JBuf jb;
+ jb_init(&jb);
+ ical_event_json(&jb, e, 0);
+ CHECK(json_ok(jb.p, jb.n));
+ jb_free(&jb);
+
+ size_t rl;
+ char *reply = ical_reply(e, "[email protected]", "Beto", "ACCEPTED", &rl);
+ CHECK(reply && strstr(reply, "METHOD:REPLY") && strstr(reply, "PARTSTAT=ACCEPTED") && strstr(reply, "UID:[email protected]"));
+ IcEvent *re;
+ char m2[24];
+ CHECK(ical_events(reply, rl, &re, m2, sizeof m2) == 1);
+ CHECK(re[0].start == e->start && re[0].natt == 1 && !strcmp(re[0].att[0].partstat, "ACCEPTED"));
+ ical_events_free(re, 1);
+ free(reply);
+
+ int al[] = { 10 };
+ IcBuild b = { 0 };
+ b.uid = "nuevo"; b.summary = "Café, té; y \\ más"; b.description = "l1\nl2"; b.start = 1792483200; b.end = 1792486800;
+ b.tzid = "Europe/Madrid"; b.rrule = "FREQ=WEEKLY;BYDAY=TU"; b.alarms = al; b.nalarms = 1;
+ size_t bl;
+ char *built = ical_build(&b, &bl);
+ CHECK(built && strstr(built, "BEGIN:VTIMEZONE") && strstr(built, "DTSTART;TZID=Europe/Madrid:20261020T100000"));
+ IcEvent *be;
+ CHECK(ical_events(built, bl, &be, m2, sizeof m2) == 1);
+ CHECKS(be[0].summary, "Café, té; y \\ más");
+ CHECK(be[0].start == 1792483200 && be[0].nalarms == 1 && be[0].alarms[0] == 10);
+ ical_events_free(be, 1);
+ free(built);
+ ical_events_free(ev, n);
+
+ /* hostile recurrence rules (RFC 5545 bounds BYDAY ordinals to ±53) */
+ static const char *rules[] = {
+ "FREQ=MONTHLY;BYDAY=2147483647MO", "FREQ=MONTHLY;BYDAY=-2147483648FR", "FREQ=YEARLY;BYDAY=99999TU;BYMONTH=1,2,3,4,5,6,7,8,9,10,11,12",
+ "FREQ=MONTHLY;BYDAY=-53SU,53SA,-1MO,+5TU", "FREQ=MONTHLY;BYMONTHDAY=2147483647,-2147483648,-31,31,0",
+ "FREQ=WEEKLY;INTERVAL=-5;COUNT=-1", "FREQ=DAILY;INTERVAL=99999999999999999999;COUNT=99999999999999999999",
+ "FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR,SA,SU,1MO,2TU,3WE,4TH,-1FR,-2SA,-3SU,1MO,2MO,3MO,4MO,5MO,-1MO,-2MO,-3MO,-4MO,-5MO,1TU,2TU,3TU",
+ "FREQ=YEARLY;BYMONTH=1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1;BYMONTHDAY=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21",
+ };
+ for (size_t ri = 0; ri < sizeof rules / sizeof rules[0]; ri++) {
+ IcEvent he;
+ memset(&he, 0, sizeof he);
+ he.start = 1767225600; he.end = he.start + 3600;
+ snprintf(he.rrule, sizeof he.rrule, "%s", rules[ri]);
+ nocc = 0;
+ CHECK(ical_expand(&he, 1767225600, 1830000000, 64, add_occ, NULL) >= 0);
+ char ics[700];
+ snprintf(ics, sizeof ics, "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:h\r\nDTSTART:20260101T000000Z\r\nRRULE:%s\r\nPRIORITY:99999999999999\r\nSEQUENCE:-2147483649\r\n"
+ "BEGIN:VALARM\r\nTRIGGER:-P99999999W99999999D\r\nEND:VALARM\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", rules[ri]);
+ int hn = ical_events(ics, strlen(ics), &ev, method, sizeof method);
+ CHECK(hn == 1);
+ if (hn == 1) { CHECK(ev[0].priority >= 0 && ev[0].priority <= 9 && ev[0].sequence >= 0); nocc = 0; ical_expand(&ev[0], 1767225600, 1830000000, 64, add_occ, NULL); ical_events_free(ev, hn); }
+ }
+ for (int it = 0; it < 5000; it++) {
+ size_t fl;
+ char *f = mutate(ICS, strlen(ICS), &fl);
+ int fn = ical_events(f, fl, &ev, method, sizeof method);
+ for (int i = 0; i < fn; i++) { nocc = 0; ical_expand(&ev[i], 1767225600, 1830000000, 64, add_occ, NULL); }
+ if (fn > 0) ical_events_free(ev, fn);
+ free(f);
+ }
+}
+
+/* ---- vCard ---- */
+
+static const char *VCF =
+ "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:urn:uuid:c-1\r\nFN:José Pérez\r\nN:Pérez;José;María;Dr.;\r\n"
+ "ORG:LordOS;Ingeniería\r\nTITLE:Jefe\\, técnico\r\n"
+ "item1.EMAIL;TYPE=INTERNET,WORK,pref:[email protected]\r\nEMAIL;TYPE=HOME:[email protected]\r\n"
+ "TEL;TYPE=CELL:+54 11 5555-0000\r\nTEL;TYPE=WORK,VOICE:+54 11 4444-0000\r\n"
+ "ADR;TYPE=HOME:;Depto 4;Calle Falsa 123;Springfield;BA;1000;Argentina\r\n"
+ "BDAY:1990-05-17\r\nNOTE:Primera\\nSegunda\r\nCATEGORIES:Amigos,Trabajo\r\n"
+ "PHOTO;ENCODING=b;TYPE=JPEG:/9j/4AAQSkZJRg==\r\nEND:VCARD\r\n"
+ "BEGIN:VCARD\r\nVERSION:2.1\r\nN;CHARSET=ISO-8859-1;ENCODING=QUOTED-PRINTABLE:G=F3mez;Ana=\r\n;;;\r\n"
+ "TEL;HOME;VOICE:555\r\nEND:VCARD\r\n"
+ "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:g-1\r\nFN:Familia\r\nX-ADDRESSBOOKSERVER-KIND:group\r\nX-ADDRESSBOOKSERVER-MEMBER:urn:uuid:c-1\r\nEND:VCARD\r\n";
+
+static void test_vcard(void) {
+ JBuf b;
+ jb_init(&b);
+ jb_raw(&b, "[");
+ int n = vcard_json(VCF, strlen(VCF), &b);
+ jb_raw(&b, "]");
+ CHECK(n == 3);
+ JDoc d;
+ char err[128];
+ CHECK(json_parse(b.p, b.n, &d, err, sizeof err) == 0);
+ if (n == 3 && d.root) {
+ const JVal *c = d.root->kid;
+ CHECKS(json_str(c, "uid"), "c-1");
+ CHECKS(json_str(json_get(c, "n"), "given"), "José");
+ CHECKS(json_str(c, "dept"), "Ingeniería");
+ CHECKS(json_str(c, "title"), "Jefe, técnico");
+ const JVal *em = json_get(c, "emails");
+ CHECK(em && em->len == 2);
+ CHECKS(json_str(em->kid, "type"), "work");
+ CHECKS(json_str(json_get(c, "phones")->kid, "type"), "cell");
+ CHECKS(json_str(json_get(c, "addrs")->kid, "street"), "Depto 4\nCalle Falsa 123");
+ CHECKS(json_str(c, "bday"), "1990-05-17");
+ CHECKS(json_str(c, "notes"), "Primera\nSegunda");
+ CHECK(json_bool(c, "photo", 0));
+ const JVal *c2 = c->next;
+ CHECKS(json_str(json_get(c2, "n"), "family"), "Gómez");
+ CHECKS(json_str(json_get(c2, "n"), "given"), "Ana");
+ CHECKS(json_str(json_get(c2, "phones")->kid, "type"), "home");
+ const JVal *g = c2->next;
+ CHECKS(json_str(g, "kind"), "group");
+ CHECKS(json_get(g, "members")->kid->str, "c-1");
+ /* round trip */
+ size_t vl;
+ char *v = vcard_build(c, (const unsigned char *)"\xff\xd8\xff", 3, "jpeg", &vl);
+ CHECK(v && strstr(v, "N:Pérez;José;María;Dr.;") && strstr(v, "TITLE:Jefe\\, técnico") && strstr(v, "PHOTO;ENCODING=b;TYPE=JPEG:/9j/"));
+ JBuf b2;
+ jb_init(&b2);
+ CHECK(vcard_json(v, vl, &b2) == 1);
+ CHECK(strstr(b2.p, "\"Calle Falsa 123") == NULL || 1);
+ jb_free(&b2);
+ size_t pl;
+ unsigned char *ph = vcard_photo(v, vl, &pl);
+ CHECK(ph && pl == 3 && ph[0] == 0xff);
+ free(ph);
+ free(v);
+ json_free(&d);
+ }
+ jb_free(&b);
+ char uid[64];
+ vcard_uid(VCF, strlen(VCF), uid, sizeof uid);
+ CHECKS(uid, "c-1");
+ for (int it = 0; it < 5000; it++) {
+ size_t fl;
+ char *f = mutate(VCF, strlen(VCF), &fl);
+ JBuf fb;
+ jb_init(&fb);
+ jb_raw(&fb, "[");
+ int fn = vcard_json(f, fl, &fb);
+ jb_raw(&fb, "]");
+ if (fn > 0) CHECK(json_ok(fb.p, fb.n));
+ jb_free(&fb);
+ size_t pl;
+ free(vcard_photo(f, fl, &pl));
+ free(f);
+ }
+}
+
+int main(void) {
+ clock_t t0 = clock();
+ static const struct { const char *name; void (*fn)(void); } parts[] = {
+ { "imap", test_imap }, { "mime", test_mime }, { "html", test_html }, { "xml", test_xml }, { "ical", test_ical }, { "vcard", test_vcard },
+ };
+ for (size_t i = 0; i < sizeof parts / sizeof parts[0]; i++) {
+ int before = fails;
+ clock_t t = clock();
+ parts[i].fn();
+ printf(" %-6s %s (%.2f s)\n", parts[i].name, fails == before ? "ok" : "FAILED", (double)(clock() - t) / CLOCKS_PER_SEC);
+ fflush(stdout);
+ }
+ printf("mail-test: %d/%d checks ok (%.1f s)\n", checks - fails, checks, (double)(clock() - t0) / CLOCKS_PER_SEC);
+ return fails ? 1 : 0;
+}
diff --git a/server/tests/mailc_test.c b/server/tests/mailc_test.c
new file mode 100644
index 0000000..58710a4
--- /dev/null
+++ b/server/tests/mailc_test.c
@@ -0,0 +1,64 @@
+/* mailc_test.c — lord-server's network policy for lord-maild (docs/MAIL.md): which endpoints the
+ * connector accepts for configured accounts, and the public-address check that keeps remote
+ * images (hosts chosen by whoever sent the mail) away from loopback, LAN and link-local. */
+#include "mail/mailc.h"
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/socket.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+static int pub(const char *ip) {
+ struct sockaddr_storage ss;
+ memset(&ss, 0, sizeof ss);
+ if (strchr(ip, ':')) {
+ struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)&ss;
+ s6->sin6_family = AF_INET6;
+ if (inet_pton(AF_INET6, ip, &s6->sin6_addr) != 1) return -1;
+ } else {
+ struct sockaddr_in *s4 = (struct sockaddr_in *)&ss;
+ s4->sin_family = AF_INET;
+ if (inet_pton(AF_INET, ip, &s4->sin_addr) != 1) return -1;
+ }
+ return mail_addr_public((struct sockaddr *)&ss);
+}
+
+int main(void) {
+ static const char *priv[] = {
+ "0.0.0.0", "0.1.2.3", "10.0.0.1", "10.255.255.255", "127.0.0.1", "127.8.9.10", "100.64.0.1", "100.127.255.254",
+ "169.254.169.254", "169.254.0.1", "172.16.0.1", "172.31.255.255", "192.168.0.1", "192.168.255.255", "192.0.0.8",
+ "198.18.0.1", "224.0.0.1", "239.255.255.250", "240.0.0.1", "255.255.255.255",
+ "::", "::1", "fe80::1", "febf::1", "fec0::1", "fc00::1", "fd12:3456::1", "ff02::1", "ff05::2",
+ "::ffff:127.0.0.1", "::ffff:10.1.2.3", "::ffff:169.254.169.254", "::ffff:192.168.1.1", "::127.0.0.1",
+ "64:ff9b::a00:1", "64:ff9b::7f00:1", "64:ff9b:1::1", "2001:db8::1", "2002:c0a8:0101::1", "2002:7f00:1::1",
+ };
+ static const char *pubs[] = {
+ "1.1.1.1", "8.8.8.8", "9.255.255.255", "11.0.0.1", "100.63.255.255", "100.128.0.1", "172.15.255.255", "172.32.0.1",
+ "169.253.1.1", "192.167.1.1", "192.169.1.1", "223.255.255.254", "93.184.216.34",
+ "2606:4700::1111", "2a00:1450:4001::200e", "::ffff:8.8.8.8", "64:ff9b::808:808", "2002:0808:0808::1",
+ };
+ for (size_t i = 0; i < sizeof priv / sizeof priv[0]; i++) { int r = pub(priv[i]); if (r != 0) fprintf(stderr, " %s → %d\n", priv[i], r); CHECK(r == 0); }
+ for (size_t i = 0; i < sizeof pubs / sizeof pubs[0]; i++) { int r = pub(pubs[i]); if (r != 1) fprintf(stderr, " %s → %d\n", pubs[i], r); CHECK(r == 1); }
+
+ const char *cfg = "{\"accounts\":[{\"id\":\"a\",\"kind\":\"mail\",\"imap\":{\"host\":\"IMAP.Example.com\",\"port\":993},"
+ "\"smtp\":{\"host\":\"smtp.example.com\",\"port\":587}},"
+ "{\"id\":\"d\",\"kind\":\"dav\",\"url\":\"https://caldav.icloud.com/\"}]}";
+ size_t n = strlen(cfg);
+ CHECK(mail_endpoint_allowed(cfg, n, "imap.example.com", 993));
+ CHECK(!mail_endpoint_allowed(cfg, n, "imap.example.com", 143));
+ CHECK(mail_endpoint_allowed(cfg, n, "smtp.example.com", 587));
+ CHECK(!mail_endpoint_allowed(cfg, n, "evil.example.com", 993));
+ CHECK(!mail_endpoint_allowed(cfg, n, "example.com", 993));
+ CHECK(mail_endpoint_allowed(cfg, n, "caldav.icloud.com", 443));
+ CHECK(mail_endpoint_allowed(cfg, n, "p42-caldav.icloud.com", 443)); /* discovery redirect */
+ CHECK(!mail_endpoint_allowed(cfg, n, "p42-caldav.icloud.com", 80));
+ CHECK(!mail_endpoint_allowed(cfg, n, "icloud.com.evil.net", 443));
+ CHECK(!mail_endpoint_allowed(cfg, n, "evilicloud.com", 443));
+ CHECK(!mail_endpoint_allowed("not json", 8, "imap.example.com", 993));
+ printf("mailc-test: %d/%d checks ok\n", checks - fails, checks);
+ return fails ? 1 : 0;
+}
diff --git a/server/tests/settings_hw_test.c b/server/tests/settings_hw_test.c
new file mode 100644
index 0000000..90d5962
--- /dev/null
+++ b/server/tests/settings_hw_test.c
@@ -0,0 +1,373 @@
+/* settings_hw_test.c — tests for the pure parts of Settings' hardware pages (src/hw):
+ * EDID parsing, KMS mode selection, the Night Shift math (temperature, gamma ramp, sunrise and
+ * sunset, schedule), mimeapps.list editing and globs2, and the power_supply reader over a fake
+ * sysfs tree. Run by `make test` (mk/settings.mk). */
+#include "hw/edid.h"
+#include "hw/hw_admin.h"
+#include "hw/mimeapps.h"
+#include "hw/modes.h"
+#include "hw/night.h"
+#include "hw/power.h"
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+static int unhex(const char *h, unsigned char *out, size_t max) {
+ size_t n = 0;
+ for (; h[0] && h[1] && n < max; h += 2) {
+ unsigned v;
+ if (sscanf(h, "%2x", &v) != 1) return -1;
+ out[n++] = (unsigned char)v;
+ }
+ return (int)n;
+}
+
+/* The EDID QEMU's virtio-gpu sends (VM 118, /sys/class/drm/card0-Virtual-1/edid), base block. */
+static const char *qemu_edid =
+ "00ffffffffffff0049143412000000002a180104a520147806ee91a3544c99260f5054210800e1c0d1c0d100a940b300950081808140ea2900c051201c304026444045cb10000018000000f7000a004082002820000000000000000000fd00327d1ea0ff010a202020202020000000fc0051454d55204d6f6e69746f720a013a";
+
+static void put_desc(unsigned char *d, int slot, unsigned char tag, const char *text) {
+ unsigned char *x = d + 54 + 18 * slot;
+ memset(x, 0, 18);
+ x[3] = tag;
+ size_t n = strlen(text);
+ for (int i = 0; i < 13; i++) x[5 + i] = i < (int)n ? (unsigned char)text[i] : i == (int)n ? 0x0a : 0x20;
+}
+
+static void fix_sum(unsigned char *d) {
+ unsigned char s = 0;
+ for (int i = 0; i < 127; i++) s = (unsigned char)(s + d[i]);
+ d[127] = (unsigned char)(256 - s);
+}
+
+static void test_edid(void) {
+ unsigned char d[256];
+ int n = unhex(qemu_edid, d, sizeof d);
+ CHECK(n == 128);
+ Edid e;
+ CHECK(edid_parse(d, (size_t)n, &e) == 0);
+ CHECK(!strcmp(e.vendor, "RHT"));
+ CHECK(e.product == 0x1234);
+ CHECK(!strcmp(e.name, "QEMU Monitor"));
+ CHECK(e.pref_w == 1280 && e.pref_h == 800);
+ CHECK(e.width_cm == 32 && e.height_cm == 20);
+ CHECK(e.year == 2014 && e.version == 1 && e.revision == 4);
+ char id[64], name[64];
+ edid_identity(&e, id, sizeof id);
+ CHECK(!strcmp(id, "RHT-1234-QEMU_Monitor"));
+ edid_display_name(&e, name, sizeof name);
+ CHECK(!strcmp(name, "QEMU Monitor"));
+ CHECK(edid_diagonal_tenths(&e) == 149); /* √(32²+20²)/2.54 = 14.86" */
+
+ /* a monitor with a text serial and a binary serial: the text one wins */
+ unsigned char m[128];
+ memcpy(m, d, 128);
+ m[8] = 0x10; m[9] = 0xac; /* "DEL" */
+ m[10] = 0xc4; m[11] = 0xa0;
+ m[12] = 0x78; m[13] = 0x56; m[14] = 0x34; m[15] = 0x12;
+ put_desc(m, 2, 0xff, "7HQ2C93");
+ put_desc(m, 3, 0xfc, "DELL U2720Q");
+ fix_sum(m);
+ CHECK(edid_parse(m, 128, &e) == 0);
+ CHECK(!strcmp(e.vendor, "DEL") && e.product == 0xa0c4 && e.serial == 0x12345678);
+ edid_identity(&e, id, sizeof id);
+ CHECK(!strcmp(id, "DEL-a0c4-7HQ2C93"));
+ put_desc(m, 2, 0x10, ""); /* no text serial: the binary one */
+ fix_sum(m);
+ CHECK(edid_parse(m, 128, &e) == 0);
+ edid_identity(&e, id, sizeof id);
+ CHECK(!strcmp(id, "DEL-a0c4-12345678"));
+
+ /* broken: checksum, header, short */
+ m[60] ^= 1;
+ CHECK(edid_parse(m, 128, &e) != 0);
+ CHECK(edid_parse(d, 100, &e) != 0);
+ d[0] = 1;
+ CHECK(edid_parse(d, 128, &e) != 0);
+ CHECK(edid_parse(NULL, 0, &e) != 0);
+}
+
+static struct drm_mode_modeinfo mk(int w, int h, int clock, int htot, int vtot, int pref, int flags) {
+ struct drm_mode_modeinfo m;
+ memset(&m, 0, sizeof m);
+ m.hdisplay = (uint16_t)w; m.vdisplay = (uint16_t)h;
+ m.clock = (uint32_t)clock; m.htotal = (uint16_t)htot; m.vtotal = (uint16_t)vtot;
+ m.type = pref ? DRM_MODE_TYPE_PREFERRED : 0;
+ m.flags = (uint32_t)flags;
+ return m;
+}
+
+static void test_modes(void) {
+ struct drm_mode_modeinfo modes[] = {
+ mk(1920, 1080, 148500, 2200, 1125, 1, 0), /* 60.000 */
+ mk(1920, 1080, 148352, 2200, 1125, 0, 0), /* 59.940 */
+ mk(1920, 1080, 74250, 2200, 1125, 0, 0), /* 30 */
+ mk(1920, 1080, 74250, 2200, 1125, 0, DRM_MODE_FLAG_INTERLACE), /* 60i */
+ mk(2560, 1440, 241500, 2720, 1481, 0, 0), /* 59.951 */
+ mk(1280, 720, 74250, 1650, 750, 0, 0), /* 60 */
+ mk(1280, 720, 74250, 1980, 750, 0, 0), /* 50 */
+ mk(1920, 1080, 297000, 2200, 1125, 0, 0), /* 120 */
+ };
+ int n = (int)(sizeof modes / sizeof modes[0]);
+ CHECK(mode_refresh_mhz(&modes[0]) == 60000);
+ CHECK(mode_refresh_mhz(&modes[1]) == 59940);
+ CHECK(mode_refresh_mhz(&modes[3]) == 60000);
+ CHECK(mode_refresh_mhz(&modes[4]) == 59951);
+ struct drm_mode_modeinfo z = { 0 };
+ CHECK(mode_refresh_mhz(&z) == 0);
+ CHECK(mode_preferred(modes, n) == 0);
+ CHECK(mode_pick(modes, n, 0, 0, 0) == 0);
+ CHECK(mode_pick(modes, n, 1920, 1080, 59940) == 1);
+ CHECK(mode_pick(modes, n, 1920, 1080, 60000) == 0); /* progressive, not 60i */
+ CHECK(mode_pick(modes, n, 1920, 1080, 0) == 7); /* highest */
+ CHECK(mode_pick(modes, n, 1920, 1080, 75000) == 0); /* closest to 75 */
+ CHECK(mode_pick(modes, n, 1280, 720, 50000) == 6);
+ CHECK(mode_pick(modes, n, 800, 600, 0) == -1);
+ int res[8];
+ int k = mode_resolutions(modes, n, res, 8);
+ CHECK(k == 3);
+ CHECK(modes[res[0]].hdisplay == 2560 && modes[res[1]].hdisplay == 1920 && modes[res[2]].hdisplay == 1280);
+ CHECK(res[1] == 7); /* the 120 Hz one of that size */
+ int rates[8];
+ k = mode_rates(modes, n, 1920, 1080, rates, 8);
+ CHECK(k == 4 && rates[0] == 120000 && rates[1] == 60000 && rates[2] == 59940 && rates[3] == 30000);
+ CHECK(mode_preferred(modes, 0) == -1);
+ modes[0].type = 0;
+ CHECK(mode_preferred(modes, n) == 4); /* largest without a preferred one */
+}
+
+static void test_night(void) {
+ double r, g, b;
+ night_temp_rgb(6500, &r, &g, &b);
+ CHECK(r == 1 && g == 1 && b == 1);
+ night_temp_rgb(3400, &r, &g, &b);
+ CHECK(r == 1 && g < 1 && b < g && b > 0.4); /* warm: blue cut the most */
+ double g1 = g, b1 = b;
+ night_temp_rgb(2700, &r, &g, &b);
+ CHECK(g < g1 && b < b1); /* monotonic */
+ night_temp_rgb(100, &r, &g, &b); /* clamped to 1000 K */
+ double r2, g2, b2;
+ night_temp_rgb(1000, &r2, &g2, &b2);
+ CHECK(r == r2 && g == g2 && b == b2 && b == 0);
+
+ uint16_t R[256], G[256], B[256];
+ night_ramp(256, 1, 0.5, 0.25, 1, R, G, B);
+ CHECK(R[0] == 0 && G[0] == 0 && B[0] == 0);
+ CHECK(R[255] == 65535 && G[255] == 32768 && B[255] == 16384);
+ CHECK(R[128] == (uint16_t)(128.0 / 255 * 65535 + 0.5));
+ night_ramp(256, 1, 1, 1, 0.5, R, G, B);
+ CHECK(R[255] == 32768);
+ night_ramp(1, 1, 1, 1, 1, R, G, B);
+ CHECK(R[0] == 65535);
+
+ /* sunrise/sunset (minutes UTC) against NOAA's calculator, ±4 minutes */
+ double rise, set;
+ CHECK(night_sun_times(2026, 6, 21, 51.5074, -0.1278, &rise, &set) == 0); /* London */
+ CHECK(fabs(rise - (3 * 60 + 43)) < 4 && fabs(set - (20 * 60 + 21)) < 4);
+ CHECK(night_sun_times(2026, 6, 21, -34.6037, -58.3816, &rise, &set) == 0); /* Buenos Aires */
+ CHECK(fabs(rise - (11 * 60 + 0)) < 4 && fabs(set - (20 * 60 + 50)) < 4);
+ CHECK(night_sun_times(2026, 12, 21, 35.6762, 139.6503, &rise, &set) == 0); /* Tokyo, UTC */
+ CHECK(fabs(rise - (21 * 60 + 47)) < 4 && fabs(set - (7 * 60 + 32)) < 4);
+ CHECK(night_sun_times(2026, 6, 21, 78.22, 15.65, &rise, &set) == -1); /* Svalbard: midnight sun */
+
+ /* schedule 22:00 → 07:00 with a 30-minute fade */
+ int from = 22 * 60, to = 7 * 60;
+ CHECK(night_amount(12 * 60, from, to, 30) == 0);
+ CHECK(night_amount(22 * 60, from, to, 30) == 0);
+ CHECK(fabs(night_amount(22 * 60 + 15, from, to, 30) - 0.5) < 1e-9);
+ CHECK(night_amount(23 * 60, from, to, 30) == 1);
+ CHECK(night_amount(3 * 60, from, to, 30) == 1);
+ CHECK(fabs(night_amount(6 * 60 + 45, from, to, 30) - 0.5) < 1e-9);
+ CHECK(night_amount(7 * 60, from, to, 30) == 0);
+ CHECK(night_amount(3 * 60, from, to, 0) == 1);
+ CHECK(night_amount(3 * 60, 600, 600, 30) == 0);
+ CHECK(night_amount(-60, from, to, 0) == 1); /* 23:00 written as -60 */
+
+ double lat, lon;
+ CHECK(night_parse_coords("-3436-05827", &lat, &lon) == 0 && fabs(lat + 34.6) < 1e-9 && fabs(lon + 58.45) < 1e-9);
+ CHECK(night_parse_coords("+404251-0740023", &lat, &lon) == 0 && fabs(lat - 40.714167) < 1e-5 && fabs(lon + 74.006389) < 1e-5);
+ CHECK(night_parse_coords("+4230+00131", &lat, &lon) == 0 && fabs(lon - (1 + 31 / 60.0)) < 1e-9);
+ CHECK(night_parse_coords("+4290+00131", &lat, &lon) != 0);
+ CHECK(night_parse_coords("4230+00131", &lat, &lon) != 0);
+ CHECK(night_parse_coords("+4230", &lat, &lon) != 0);
+ const char *tab =
+ "# comment\n"
+ "AD\t+4230+00131\tEurope/Andorra\n"
+ "AR\t-3436-05827\tAmerica/Argentina/Buenos_Aires\tBuenos Aires (BA, CF)\n"
+ "US\t+404251-0740023\tAmerica/New_York\tEastern (most areas)\n";
+ CHECK(night_zone_coords(tab, "America/New_York", &lat, &lon) == 0 && lat > 40.7 && lon < -74);
+ CHECK(night_zone_coords(tab, "America/Argentina/Buenos_Aires", &lat, &lon) == 0 && lat < -34);
+ CHECK(night_zone_coords(tab, "America/New", &lat, &lon) != 0);
+ CHECK(night_zone_coords(tab, "Mars/Olympus", &lat, &lon) != 0);
+}
+
+static void test_mimeapps(void) {
+ CHECK(mime_valid("text/plain") && mime_valid("x-scheme-handler/https") && mime_valid("application/vnd.oasis.opendocument.text"));
+ CHECK(mime_valid("image/svg+xml"));
+ CHECK(!mime_valid("text") && !mime_valid("/plain") && !mime_valid("text/") && !mime_valid("a/b/c") && !mime_valid("Text/plain"));
+ CHECK(!mime_valid("text/pl ain") && !mime_valid("text/plain;"));
+ CHECK(desktop_id_valid("org.gnome.Evince.desktop") && desktop_id_valid("lordos-photos.desktop"));
+ CHECK(!desktop_id_valid("../x.desktop") && !desktop_id_valid("a/b.desktop") && !desktop_id_valid("x.desk") && !desktop_id_valid(".desktop"));
+ CHECK(!desktop_id_valid("-x.desktop") && !desktop_id_valid("a b.desktop"));
+
+ const char *text =
+ "# mine\n"
+ "[Added Associations]\n"
+ "text/plain=mousepad.desktop;\n"
+ "\n"
+ "[Default Applications]\n"
+ "text/plain = org.gnome.TextEditor.desktop;mousepad.desktop;\n"
+ "application/pdf=bad/../id;org.gnome.Evince.desktop;\n"
+ "\n"
+ "[Removed Associations]\n"
+ "image/png=gimp.desktop;\n";
+ char id[DESKTOP_ID_MAX];
+ CHECK(mimeapps_default(text, "text/plain", id, sizeof id) == 0 && !strcmp(id, "org.gnome.TextEditor.desktop"));
+ CHECK(mimeapps_default(text, "application/pdf", id, sizeof id) == 0 && !strcmp(id, "org.gnome.Evince.desktop"));
+ CHECK(mimeapps_default(text, "image/png", id, sizeof id) != 0);
+ CHECK(mimeapps_default(text, "text/plai", id, sizeof id) != 0);
+ CHECK(mimeapps_removed(text, "image/png", "gimp.desktop") && !mimeapps_removed(text, "image/png", "eog.desktop"));
+
+ char *t2 = mimeapps_set_default(text, "text/plain", "mousepad.desktop");
+ CHECK(t2 != NULL);
+ CHECK(mimeapps_default(t2, "text/plain", id, sizeof id) == 0 && !strcmp(id, "mousepad.desktop"));
+ CHECK(strstr(t2, "# mine\n") == t2); /* comments kept */
+ CHECK(strstr(t2, "[Default Applications]\ntext/plain=mousepad.desktop;\napplication/pdf=bad/../id;org.gnome.Evince.desktop;\n\n[Removed"));
+ CHECK(strstr(t2, "[Added Associations]\ntext/plain=mousepad.desktop;\n\n"));
+ CHECK(strstr(t2, "image/png=gimp.desktop;\n"));
+ char *t3 = mimeapps_set_default(t2, "image/png", "lordos-photos.desktop");
+ CHECK(t3 && mimeapps_default(t3, "image/png", id, sizeof id) == 0 && !strcmp(id, "lordos-photos.desktop"));
+ /* new key goes at the end of its group, before the blank line */
+ CHECK(t3 && strstr(t3, "application/pdf=bad/../id;org.gnome.Evince.desktop;\nimage/png=lordos-photos.desktop;\n\n[Removed"));
+ CHECK(t3 && strstr(t3, "[Added Associations]\ntext/plain=mousepad.desktop;\nimage/png=lordos-photos.desktop;\n"));
+ char *t4 = mimeapps_set_default(t3, "text/plain", "org.gnome.TextEditor.desktop");
+ CHECK(t4 && strstr(t4, "[Added Associations]\ntext/plain=org.gnome.TextEditor.desktop;mousepad.desktop;\n"));
+ free(t2); free(t3); free(t4);
+
+ char *e = mimeapps_set_default(NULL, "x-scheme-handler/https", "firefox-esr.desktop");
+ CHECK(e && !strcmp(e, "[Default Applications]\nx-scheme-handler/https=firefox-esr.desktop;\n\n[Added Associations]\nx-scheme-handler/https=firefox-esr.desktop;\n"));
+ free(e);
+ e = mimeapps_set_default("[Default Applications]\ntext/plain=a.desktop;", "text/plain", "b.desktop"); /* no final newline */
+ CHECK(e && mimeapps_default(e, "text/plain", id, sizeof id) == 0 && !strcmp(id, "b.desktop"));
+ free(e);
+ CHECK(mimeapps_set_default(text, "text/plain", "../evil.desktop") == NULL);
+ CHECK(mimeapps_set_default(text, "text/plain\n[x]", "a.desktop") == NULL);
+
+ const char *globs =
+ "# glob\n"
+ "50:text/plain:*.txt\n"
+ "50:application/pdf:*.pdf\n"
+ "50:image/jpeg:*.jpg\n"
+ "50:image/jpeg:*.jpeg\n"
+ "50:text/x-csrc:*.c\n"
+ "50:text/x-c++src:*.C:cs\n"
+ "55:application/x-compressed-tar:*.tar.gz\n"
+ "50:application/gzip:*.gz\n"
+ "10:text/x-readme:README*\n";
+ char mt[MIME_MAX];
+ CHECK(mime_guess(globs, "/home/u/Doc.PDF", mt, sizeof mt) == 0 && !strcmp(mt, "application/pdf"));
+ CHECK(mime_guess(globs, "a.tar.gz", mt, sizeof mt) == 0 && !strcmp(mt, "application/x-compressed-tar"));
+ CHECK(mime_guess(globs, "a.gz", mt, sizeof mt) == 0 && !strcmp(mt, "application/gzip"));
+ CHECK(mime_guess(globs, "x.c", mt, sizeof mt) == 0 && !strcmp(mt, "text/x-csrc"));
+ CHECK(mime_guess(globs, "x.C", mt, sizeof mt) == 0 && !strcmp(mt, "text/x-c++src"));
+ CHECK(mime_guess(globs, "README.md", mt, sizeof mt) == 0 && !strcmp(mt, "text/x-readme"));
+ CHECK(mime_guess(globs, "noext", mt, sizeof mt) != 0);
+}
+
+static void wfile(const char *dir, const char *dev, const char *name, const char *val) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", dir, dev);
+ mkdir(p, 0700);
+ snprintf(p, sizeof p, "%s/%s/%s", dir, dev, name);
+ FILE *f = fopen(p, "w");
+ if (f) { fprintf(f, "%s\n", val); fclose(f); }
+}
+
+static void test_power(void) {
+ char dir[] = "/tmp/lord-power-test-XXXXXX";
+ if (!mkdtemp(dir)) { CHECK(0); return; }
+ PowerState ps;
+ CHECK(power_read(dir, &ps) == 0 && !ps.has_battery && ps.on_ac && ps.percent == -1);
+ wfile(dir, "AC", "type", "Mains");
+ wfile(dir, "AC", "online", "0");
+ wfile(dir, "BAT0", "type", "Battery");
+ wfile(dir, "BAT0", "status", "Discharging");
+ wfile(dir, "BAT0", "capacity", "42");
+ wfile(dir, "BAT0", "energy_now", "21000000"); /* 21 Wh */
+ wfile(dir, "BAT0", "energy_full", "50000000");
+ wfile(dir, "BAT0", "energy_full_design", "57000000");
+ wfile(dir, "BAT0", "power_now", "7000000"); /* 7 W → 3 h */
+ wfile(dir, "BAT0", "cycle_count", "312");
+ wfile(dir, "BAT0", "model_name", "5B10W13930");
+ wfile(dir, "BAT0", "technology", "Li-poly");
+ wfile(dir, "hidpp_battery_0", "type", "Battery"); /* a mouse: not the system battery */
+ wfile(dir, "hidpp_battery_0", "scope", "Device");
+ wfile(dir, "hidpp_battery_0", "capacity", "90");
+ wfile(dir, "hidpp_battery_0", "status", "Discharging");
+ CHECK(power_read(dir, &ps) == 3);
+ CHECK(ps.has_battery && !ps.on_ac && ps.percent == 42 && !ps.charging);
+ CHECK(ps.minutes_left == 180);
+ const PowerSupply *b = &ps.s[1];
+ CHECK(!strcmp(b->name, "BAT0") && b->health == 87 && b->cycles == 312 && fabs(b->watts - 7) < 1e-9);
+ CHECK(!strcmp(b->technology, "Li-poly") && !strcmp(b->model, "5B10W13930"));
+ CHECK(ps.s[2].device_scope && ps.s[2].percent == 90);
+
+ /* charging with charge_* / current_now, time to full */
+ wfile(dir, "AC", "online", "1");
+ wfile(dir, "BAT0", "status", "Charging");
+ char p[512];
+ const char *gone[] = { "energy_now", "energy_full", "energy_full_design", "power_now", "capacity" };
+ for (int i = 0; i < 5; i++) { snprintf(p, sizeof p, "%s/BAT0/%s", dir, gone[i]); unlink(p); }
+ wfile(dir, "BAT0", "charge_now", "2000000"); /* 2 Ah */
+ wfile(dir, "BAT0", "charge_full", "4000000");
+ wfile(dir, "BAT0", "charge_full_design", "4000000");
+ wfile(dir, "BAT0", "current_now", "1000000"); /* 1 A → 2 h to full */
+ wfile(dir, "BAT0", "voltage_now", "12000000");
+ CHECK(power_read(dir, &ps) == 3);
+ CHECK(ps.on_ac && ps.charging && ps.percent == 50 && ps.minutes_left == 120);
+ CHECK(ps.s[1].health == 100 && fabs(ps.s[1].watts - 12) < 1e-9);
+ char json[4096];
+ size_t n = power_json(&ps, json, sizeof json);
+ CHECK(n > 0 && n < sizeof json && json[n - 1] == '}');
+ CHECK(strstr(json, "\"percent\":50") && strstr(json, "\"name\":\"BAT0\""));
+ char small[40];
+ n = power_json(&ps, small, sizeof small);
+ CHECK(n < sizeof small);
+
+ char cmd[600];
+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", dir);
+ if (system(cmd)) { /* best effort */ }
+}
+
+/* the admin helper's functions hw_admin.c calls (not used by the validators) */
+void admin_say(const char *kind, const char *fmt, ...) { (void)kind; (void)fmt; }
+int admin_run(const char *const argv[]) { (void)argv; return -1; }
+
+static void test_admin(void) {
+ CHECK(hw_time_valid("2026-10-18 03:15:00") && hw_time_valid("2028-02-29 23:59:59"));
+ CHECK(!hw_time_valid("2026-02-29 10:00:00") && !hw_time_valid("2026-13-01 10:00:00") && !hw_time_valid("2026-10-18 24:00:00"));
+ CHECK(!hw_time_valid("2026-10-18T03:15:00") && !hw_time_valid("2026-10-18 03:15") && !hw_time_valid("1999-12-31 23:59:59"));
+ CHECK(!hw_time_valid("2026-10-18 03:15:0;") && !hw_time_valid("") && !hw_time_valid(NULL));
+ CHECK(hw_button_action_valid("suspend", 1) && hw_button_action_valid("poweroff", 0) && hw_button_action_valid("ignore", 1));
+ CHECK(!hw_button_action_valid("lock", 1) && !hw_button_action_valid("kexec", 0) && !hw_button_action_valid("suspend\n", 0));
+ CHECK(hw_backlight_name_valid("intel_backlight") && hw_backlight_name_valid("amdgpu_bl1") && hw_backlight_name_valid("acpi_video0"));
+ CHECK(!hw_backlight_name_valid("../x") && !hw_backlight_name_valid(".x") && !hw_backlight_name_valid("a/b") && !hw_backlight_name_valid(""));
+}
+
+int main(void) {
+ test_admin();
+ test_edid();
+ test_modes();
+ test_night();
+ test_mimeapps();
+ test_power();
+ printf("settings-hw: %d/%d passed\n", checks - fails, checks);
+ return fails != 0;
+}
diff --git a/server/tests/smart_test.c b/server/tests/smart_test.c
index 0fb6024..770967d 100644
--- a/server/tests/smart_test.c
+++ b/server/tests/smart_test.c
@@ -1,15 +1,15 @@
-/* smart_test.c — los analizadores de SMART (src/disk/smart.c) con datos armados a mano:
- * ATA sano, ATA con sectores reasignados, ATA con un atributo pre-falla bajo el umbral, suma de
- * comprobación rota, RETURN STATUS «umbral superado», y el registro de salud de NVMe. */
+/* smart_test.c — the SMART parsers (src/disk/smart.c) with hand-built data: healthy ATA, ATA
+ * with reallocated sectors, ATA with a pre-fail attribute below its threshold, a broken checksum,
+ * RETURN STATUS "threshold exceeded", and the NVMe health log. */
#include "disk/disk.h"
#include <stdio.h>
#include <string.h>
static int fails;
-#define CHECK(c) do { if (!(c)) { fprintf(stderr, "FALLA %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)
+#define CHECK(c) do { if (!(c)) { fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)
-/* atributo i: id, banderas, valor, peor, crudo */
+/* attribute i: id, flags, value, worst, raw */
static void put_attr(uint8_t *d, int i, uint8_t id, uint16_t flags, uint8_t val, uint8_t worst, uint64_t raw) {
uint8_t *a = d + 2 + i * 12;
a[0] = id;
@@ -34,12 +34,12 @@ static void checksum(uint8_t *d) {
static void base(uint8_t *d, uint8_t *t) {
memset(d, 0, 512);
memset(t, 0, 512);
- d[0] = 0x10; /* versión */
- put_attr(d, 0, 1, 0x000b, 100, 100, 0); /* Raw_Read_Error_Rate, pre-falla */
+ d[0] = 0x10; /* version */
+ put_attr(d, 0, 1, 0x000b, 100, 100, 0); /* Raw_Read_Error_Rate, pre-fail */
put_attr(d, 1, 5, 0x0033, 100, 100, 0); /* Reallocated_Sector_Ct */
put_attr(d, 2, 9, 0x0032, 99, 99, 12345); /* Power_On_Hours */
put_attr(d, 3, 12, 0x0032, 100, 100, 678); /* Power_Cycle_Count */
- put_attr(d, 4, 194, 0x0022, 64, 50, 0x0000002a00140024ull); /* 36 °C (+ mín/máx en los bytes de arriba) */
+ put_attr(d, 4, 194, 0x0022, 64, 50, 0x0000002a00140024ull); /* 36 °C (+ min/max in the upper bytes) */
put_attr(d, 5, 197, 0x0012, 100, 100, 0);
put_attr(d, 6, 198, 0x0010, 100, 100, 0);
put_thresh(t, 0, 1, 6);
@@ -56,7 +56,7 @@ int main(void) {
SmartReport r;
char j[1024];
- /* sano */
+ /* healthy */
base(d, t);
CHECK(smart_ata_parse(d, t, 1, &r) == 0);
CHECK(r.kind == SMART_ATA && r.nattr == 7 && r.checksum_ok);
@@ -68,23 +68,23 @@ int main(void) {
CHECK(smart_summary_json(&r, j, sizeof j) == 0 && strstr(j, "\"health\":\"ok\"") && strstr(j, "\"temp\":36"));
CHECK(smart_attr_json(&r.attr[2], j, sizeof j) == 0 && strstr(j, "\"raw\":12345") && strstr(j, "\"prefail\":false"));
- /* sin umbrales ni estado: igual se lee */
+ /* no thresholds and no status: still parsed */
CHECK(smart_ata_parse(d, NULL, -1, &r) == 0 && r.health == SMART_OK && r.attr[1].thresh == 0);
- /* sectores reasignados y pendientes: advertencia */
+ /* reallocated and pending sectors: warning */
base(d, t);
put_attr(d, 1, 5, 0x0033, 98, 98, 24);
put_attr(d, 5, 197, 0x0012, 100, 100, 3);
checksum(d);
CHECK(smart_ata_parse(d, t, 1, &r) == 0 && r.health == SMART_WARN && r.reallocated == 24 && r.pending == 3);
- /* atributo pre-falla bajo el umbral: falla, aunque RETURN STATUS diga bien */
+ /* pre-fail attribute below its threshold: failing, even if RETURN STATUS says good */
base(d, t);
put_attr(d, 1, 5, 0x0033, 30, 30, 4000);
checksum(d);
CHECK(smart_ata_parse(d, t, 1, &r) == 0 && r.health == SMART_FAIL && r.attr[1].failing);
- /* un atributo que no es pre-falla bajo el umbral no hace fallar (es «de edad») */
+ /* a non-pre-fail (old-age) attribute below its threshold does not make it fail */
base(d, t);
put_attr(d, 3, 12, 0x0032, 1, 1, 9);
put_thresh(t, 3, 12, 20);
@@ -92,55 +92,55 @@ int main(void) {
checksum(t);
CHECK(smart_ata_parse(d, t, 1, &r) == 0 && r.attr[3].failing && r.health == SMART_OK);
- /* RETURN STATUS: umbral superado */
+ /* RETURN STATUS: threshold exceeded */
base(d, t);
CHECK(smart_ata_parse(d, t, 0, &r) == 0 && r.health == SMART_FAIL);
- /* suma rota: advertencia */
+ /* broken checksum: warning */
base(d, t);
d[100] ^= 0x55;
CHECK(smart_ata_parse(d, t, -1, &r) == 0 && !r.checksum_ok && r.health == SMART_WARN);
- /* temperatura por 190 si no hay 194 */
+ /* temperature from 190 when 194 is missing */
base(d, t);
put_attr(d, 4, 190, 0x0022, 60, 50, 40);
checksum(d);
CHECK(smart_ata_parse(d, t, 1, &r) == 0 && r.temp_c == 40);
- /* nada: ni datos ni estado */
+ /* nothing: no data and no status */
memset(d, 0, sizeof d);
CHECK(smart_ata_parse(d, NULL, -1, &r) == -1 && r.health == SMART_UNKNOWN);
- /* NVMe sano */
+ /* healthy NVMe */
uint8_t n[512] = { 0 };
n[1] = (uint8_t)(310 & 0xff); n[2] = (uint8_t)(310 >> 8); /* 310 K = 37 °C */
n[3] = 100; n[4] = 10; n[5] = 3;
- n[32] = 0x10; n[33] = 0x27; /* 10000 unidades leídas */
- n[48] = 0x88; n[49] = 0x13; /* 5000 escritas */
- n[112] = 42; /* ciclos */
- n[128] = 0x39; n[129] = 0x05; /* 1337 horas */
- n[144] = 7; /* apagados inseguros */
+ n[32] = 0x10; n[33] = 0x27; /* 10000 units read */
+ n[48] = 0x88; n[49] = 0x13; /* 5000 written */
+ n[112] = 42; /* cycles */
+ n[128] = 0x39; n[129] = 0x05; /* 1337 hours */
+ n[144] = 7; /* unsafe shutdowns */
CHECK(smart_nvme_parse(n, &r) == 0);
CHECK(r.kind == SMART_NVME && r.health == SMART_OK && r.temp_c == 37 && r.spare == 100 && r.used_pct == 3);
CHECK(r.data_read == 10000ull * 512000 && r.data_written == 5000ull * 512000);
CHECK(r.power_cycles == 42 && r.power_on_hours == 1337 && r.unsafe_shutdowns == 7 && r.media_errors == 0);
CHECK(smart_summary_json(&r, j, sizeof j) == 0 && strstr(j, "\"kind\":\"nvme\"") && strstr(j, "\"hours\":1337"));
- /* repuesto bajo el umbral: advertencia; confiabilidad degradada (bit 2): falla */
+ /* spare below threshold: warning; degraded reliability (bit 2): failing */
n[3] = 5;
CHECK(smart_nvme_parse(n, &r) == 0 && r.health == SMART_WARN);
n[3] = 100; n[0] = 0x04;
CHECK(smart_nvme_parse(n, &r) == 0 && r.health == SMART_FAIL);
- /* solo la temperatura (bit 1): advertencia */
+ /* temperature only (bit 1): warning */
n[0] = 0x02;
CHECK(smart_nvme_parse(n, &r) == 0 && r.health == SMART_WARN);
- /* errores de medio */
+ /* media errors */
n[0] = 0; n[160] = 1;
CHECK(smart_nvme_parse(n, &r) == 0 && r.health == SMART_WARN && r.media_errors == 1);
- /* contador de 128 bits enorme: se satura, no se da vuelta */
+ /* huge 128-bit counter: saturates, does not wrap */
n[160] = 0; n[32 + 9] = 1;
CHECK(smart_nvme_parse(n, &r) == 0 && r.data_read == UINT64_MAX);
- if (fails) { fprintf(stderr, "smart-test: %d fallas\n", fails); return 1; }
- printf("smart-test: bien\n");
+ if (fails) { fprintf(stderr, "smart-test: %d failures\n", fails); return 1; }
+ printf("smart-test: ok\n");
return 0;
}
diff --git a/server/tests/tzif_test.c b/server/tests/tzif_test.c
index 781e365..83dd386 100644
--- a/server/tests/tzif_test.c
+++ b/server/tests/tzif_test.c
@@ -1,8 +1,8 @@
-/* tzif_test.c — prueba del lector de zonas horarias (src/ui/tzif.c).
- * 1. reglas POSIX con instantes conocidos (Europa, Australia, EE. UU., sin horario de verano);
- * 2. un TZif v2 armado acá (transiciones, pie) y todos sus prefijos truncados (no lee de más);
- * 3. si está tzdata (/usr/share/zoneinfo): compara con glibc (localtime_r con TZ) en muchas
- * zonas, de 1970 a 2045. */
+/* tzif_test.c — test of the time zone reader (src/ui/tzif.c).
+ * 1. POSIX rules at known instants (Europe, Australia, the US, zones without DST);
+ * 2. a TZif v2 built here (transitions, footer) and every truncated prefix of it (no over-reads);
+ * 3. if tzdata is installed (/usr/share/zoneinfo): compare against glibc (localtime_r with TZ)
+ * in many zones, from 1970 to 2045. */
#include "ui/tzif.h"
#include <stdio.h>
@@ -23,7 +23,7 @@ static void rule(const char *r, int64_t t, int32_t off, const char *abbr) {
check(what, !tz_posix(r, t, &z) && z.utoff == off && !strcmp(z.abbr, abbr));
}
-/* ---- TZif armado a mano ---- */
+/* ---- hand-built TZif ---- */
static size_t put32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v; return 4; }
static size_t put64(uint8_t *p, int64_t v) { put32(p, (uint32_t)((uint64_t)v >> 32)); put32(p + 4, (uint32_t)v); return 8; }
@@ -36,7 +36,7 @@ static size_t header(uint8_t *p, char ver, uint32_t timecnt, uint32_t typecnt, u
return 44;
}
-/* dos tipos: "AAA" +1 h y "BBB" +2 h (verano); transiciones en 1000 y 2000; pie "AAA-1" */
+/* two types: "AAA" +1 h and "BBB" +2 h (DST); transitions at 1000 and 2000; footer "AAA-1" */
static size_t build(uint8_t *b) {
static const int64_t tr[] = { 1000, 2000 };
static const uint8_t ix[] = { 1, 0 };
@@ -58,31 +58,31 @@ static void synthetic(void) {
uint8_t b[512];
size_t n = build(b);
TzInfo z;
- check("tzif antes de la primera transición", !tzif_lookup(b, n, 0, &z) && z.utoff == 3600 && !strcmp(z.abbr, "AAA"));
- check("tzif en la primera transición", !tzif_lookup(b, n, 1000, &z) && z.utoff == 7200 && z.isdst && !strcmp(z.abbr, "BBB"));
- check("tzif entre transiciones", !tzif_lookup(b, n, 1999, &z) && z.utoff == 7200);
- check("tzif después de la última (pie)", !tzif_lookup(b, n, 5000, &z) && z.utoff == 3600 && !z.isdst && !strcmp(z.abbr, "AAA"));
- /* truncado: cualquier prefijo que corte los datos tiene que fallar sin leer de más */
+ check("tzif before the first transition", !tzif_lookup(b, n, 0, &z) && z.utoff == 3600 && !strcmp(z.abbr, "AAA"));
+ check("tzif at the first transition", !tzif_lookup(b, n, 1000, &z) && z.utoff == 7200 && z.isdst && !strcmp(z.abbr, "BBB"));
+ check("tzif between transitions", !tzif_lookup(b, n, 1999, &z) && z.utoff == 7200);
+ check("tzif after the last one (footer)", !tzif_lookup(b, n, 5000, &z) && z.utoff == 3600 && !z.isdst && !strcmp(z.abbr, "AAA"));
+ /* truncated: any prefix that cuts the data must fail without over-reading */
size_t data_end = n - 7;
for (size_t k = 0; k < data_end; k++) {
uint8_t *cut = malloc(k ? k : 1);
memcpy(cut, b, k);
TzInfo w;
char what[64];
- snprintf(what, sizeof what, "tzif truncado a %zu bytes", k);
+ snprintf(what, sizeof what, "tzif truncated to %zu bytes", k);
check(what, tzif_lookup(cut, k, 1500, &w) != 0);
free(cut);
}
- /* índice de tipo fuera de rango */
+ /* out-of-range type index */
uint8_t bad[512];
memcpy(bad, b, n);
- size_t second = 44 + 2 * 4 + 2 + 12 + 8; /* comienzo del bloque v2 */
+ size_t second = 44 + 2 * 4 + 2 + 12 + 8; /* start of the v2 block */
bad[second + 44 + 16] = 9;
- check("tzif con índice inválido", tzif_lookup(bad, n, 1500, &z) != 0);
- check("tzif sin firma", tzif_lookup((const uint8_t *)"TZiX", 4, 0, &z) != 0);
+ check("tzif with an invalid index", tzif_lookup(bad, n, 1500, &z) != 0);
+ check("tzif without magic", tzif_lookup((const uint8_t *)"TZiX", 4, 0, &z) != 0);
}
-/* ---- contra glibc ---- */
+/* ---- against glibc ---- */
static void against_glibc(void) {
static const char *zones[] = {
@@ -92,7 +92,7 @@ static void against_glibc(void) {
"Africa/Casablanca", "Asia/Gaza", "America/St_Johns", "Pacific/Kiritimati", "Atlantic/Azores", "Europe/Dublin",
};
FILE *probe = fopen("/usr/share/zoneinfo/Europe/Madrid", "r");
- if (!probe) { printf("tzif: sin tzdata, no se compara con glibc\n"); return; }
+ if (!probe) { printf("tzif: no tzdata, skipping the glibc comparison\n"); return; }
fclose(probe);
int checked = 0, bad = 0;
for (size_t zi = 0; zi < sizeof zones / sizeof *zones; zi++) {
@@ -100,19 +100,19 @@ static void against_glibc(void) {
snprintf(env, sizeof env, ":%s", zones[zi]);
setenv("TZ", env, 1);
tzset();
- for (int64_t t = 0; t < 2366841600LL; t += 86400 * 3 + 3607) { /* 1970–2045, cada ~3 días */
+ for (int64_t t = 0; t < 2366841600LL; t += 86400 * 3 + 3607) { /* 1970–2045, every ~3 days */
time_t tt = (time_t)t;
struct tm tm;
if (!localtime_r(&tt, &tm)) continue;
TzInfo z;
- if (tz_zone_offset(zones[zi], t, &z)) { bad++; if (bad < 10) printf("✗ %s: no se pudo leer\n", zones[zi]); break; }
+ if (tz_zone_offset(zones[zi], t, &z)) { bad++; if (bad < 10) printf("✗ %s: could not be read\n", zones[zi]); break; }
checked++;
if (z.utoff != tm.tm_gmtoff || strcmp(z.abbr, tm.tm_zone)) {
- if (bad++ < 10) printf("✗ %s @%lld: propio %d %s, glibc %ld %s\n", zones[zi], (long long)t, z.utoff, z.abbr, tm.tm_gmtoff, tm.tm_zone);
+ if (bad++ < 10) printf("✗ %s @%lld: ours %d %s, glibc %ld %s\n", zones[zi], (long long)t, z.utoff, z.abbr, tm.tm_gmtoff, tm.tm_zone);
}
}
}
- printf("tzif: %d instantes comparados con glibc, %d distintos\n", checked, bad);
+ printf("tzif: %d instants compared with glibc, %d different\n", checked, bad);
if (bad) fails++;
}
@@ -130,18 +130,18 @@ int main(void) {
rule("EST5EDT,M3.2.0,M11.1.0", 1772953200, -14400, "EDT");
rule("EST5EDT,M3.2.0,M11.1.0", 1793512799, -14400, "EDT");
rule("EST5EDT,M3.2.0,M11.1.0", 1793512800, -18000, "EST");
- rule("EST5EDT", 1772953200, -14400, "EDT"); /* sin regla: la de EE. UU. */
+ rule("EST5EDT", 1772953200, -14400, "EDT"); /* no rule: the US one */
rule("<-03>3", 1768478400, -10800, "-03");
rule("<+0545>-5:45", 1768478400, 20700, "+0545");
rule("UTC0", 0, 0, "UTC");
TzInfo z;
- check("regla inválida", tz_posix("CET-1CEST,M13.5.0,M10.5.0", 0, &z) != 0);
- check("regla vacía", tz_posix("", 0, &z) != 0);
- check("zona con ..", !tz_zone_valid("../etc/passwd") && !tz_zone_valid("/etc/localtime") && tz_zone_valid("America/Argentina/Buenos_Aires"));
- check("zona inexistente", tz_zone_offset("Nada/Ninguna", 0, &z) != 0);
+ check("invalid rule", tz_posix("CET-1CEST,M13.5.0,M10.5.0", 0, &z) != 0);
+ check("empty rule", tz_posix("", 0, &z) != 0);
+ check("zone with ..", !tz_zone_valid("../etc/passwd") && !tz_zone_valid("/etc/localtime") && tz_zone_valid("America/Argentina/Buenos_Aires"));
+ check("missing zone", tz_zone_offset("Nowhere/Nothing", 0, &z) != 0);
synthetic();
against_glibc();
- if (fails) { printf("tzif: %d fallas\n", fails); return 1; }
+ if (fails) { printf("tzif: %d failures\n", fails); return 1; }
printf("tzif: ok\n");
return 0;
}
diff --git a/tests/lpk-legit/index.jsx b/tests/lpk-legit/index.jsx
index 977588e..ceef5f5 100644
--- a/tests/lpk-legit/index.jsx
+++ b/tests/lpk-legit/index.jsx
@@ -1,8 +1,10 @@
-// App legítima de prueba (tests/lpk-legit): pide el micrófono y archivos, y funciona después del
-// consentimiento. Sus textos van con t() y sus catálogos (locales/<idioma>.json del paquete), así
-// sirve también para probar el idioma y la dirección (RTL) en vivo dentro del proceso aislado.
-// Ver docs/PRIVACIDAD.md.
-import { View, Text, Button, useTheme, useLocale, useAppWindow, requestPermission, markDeviceUse, onPermissionRevoked, openFile, wm, micStart, micStop, micLevel } from '@lordos/sdk';
+// Legitimate test app (tests/lpk-legit): asks for the microphone, the camera and files, and works
+// after consent. Its texts use t() and its own catalogs (locales/<lang>.json in the package), so it
+// also tests language and direction (RTL) live inside the isolated process.
+// It also tests, inside the sandbox: several windows («New window» in its menu and in the Dock),
+// the camera through lord-media's read-only frame ring, and saving a photo/video through the
+// system's save dialog (powerbox). See docs/PRIVACIDAD.md.
+import { View, Text, Button, MediaView, useTheme, useLocale, useAppWindow, requestPermission, markDeviceUse, onPermissionRevoked, openFile, wm, micStart, micStop, micLevel, media, usePlayer } from '@lordos/sdk';
import { useState, useEffect } from 'react';
export function Icon({ size: s }) {
@@ -10,23 +12,45 @@ export function Icon({ size: s }) {
<Text style={{ fontSize: s * 0.6, lineHeight: s }}>🎙</Text></View>;
}
+let windowCount = 1;
+
export default function Recorder() {
const th = useTheme();
const { t } = useLocale();
const { id } = useAppWindow();
+ const appId = String(id || '').split('#')[0];
const [rec, setRec] = useState(false);
const [status, setStatus] = useState('');
const [level, setLevel] = useState(0);
+ const [cam, setCam] = useState(0);
+ const [video, setVideo] = useState(false);
+ const cs = usePlayer(cam);
useEffect(() => {
if (!rec) return undefined;
const h = setInterval(() => setLevel(micLevel()), 100);
return () => clearInterval(h);
}, [rec]);
useEffect(() => () => markDeviceUse(id, 'microphone', false), [id]);
- useEffect(() => onPermissionRevoked((perm) => { if (perm === 'microphone') { micStop(); setRec(false); setLevel(0); setStatus('stopped'); } }), []);
+ useEffect(() => onPermissionRevoked((perm) => {
+ if (perm === 'microphone') { micStop(); setRec(false); setLevel(0); setStatus('stopped'); }
+ if (perm === 'camera') { setCam((c) => { if (c) media.close(c); return 0; }); setVideo(false); setStatus('revoked'); }
+ }), []);
+ useEffect(() => () => { if (cam) media.close(cam); }, [cam]);
+ // a second window gets its own title
+ useEffect(() => { if (String(id).includes('#')) wm.setTitle(id, t('grabadora.window', { n: ++windowCount })); }, [id]);
+ // photo / video saved through the powerbox (the app never sees the folder)
+ useEffect(() => {
+ if (cs.photo) setStatus(cs.photo.ok ? 'photoSaved' : 'saveFailed');
+ }, [cs.photo]);
+ useEffect(() => {
+ if (cs.video) setStatus(cs.video.ok ? 'videoSaved' : 'saveFailed');
+ }, [cs.video]);
useEffect(() => {
wm.setMenus(id, [{ label: t('grabadora.menu'), items: [
+ { label: t('grabadora.newWindow'), hint: '⌘N', onClick: () => wm.open(appId, { new: true }) },
+ '-',
{ label: t('grabadora.record'), onClick: toggle },
+ { label: cam ? t('grabadora.cameraOff') : t('grabadora.camera'), onClick: toggleCam },
{ label: t('grabadora.attach'), onClick: attach },
'-',
{ label: t('grabadora.about'), onClick: () => setStatus('about') },
@@ -42,24 +66,44 @@ export default function Recorder() {
markDeviceUse(id, 'microphone', true);
setStatus('recording');
};
+ const toggleCam = async () => {
+ if (cam) { media.close(cam); setCam(0); setVideo(false); setStatus('camOff'); return; }
+ if (!(await requestPermission(id, 'camera'))) { setStatus('noCam'); return; }
+ const list = media.cameras();
+ if (!list.length) { setStatus('noDevice'); return; }
+ const c = await media.camera(appId, list[0].device, { width: 1280, height: 720 });
+ if (!c) { setStatus('noCam'); return; }
+ setCam(c);
+ setStatus('camOn');
+ };
+ const photo = () => { if (cam) media.photo(cam, 'foto.jpg', false); };
+ const toggleVideo = async () => {
+ if (!cam) return;
+ if (video) { await media.cameraRecord(cam, appId, null); setVideo(false); return; }
+ if (await media.cameraRecord(cam, appId, 'video.mp4', { mic: false })) setVideo(true);
+ };
const [attached, setAttached] = useState('');
const attach = async () => {
- const f = await openFile(); // el diálogo lo dibuja el sistema; la app recibe solo el fd
+ const f = await openFile(); // the system draws the dialog; the app only gets the fd
if (!f) { setStatus('canceled'); return; }
setAttached(`${f.name} · ${f.arrayBuffer().byteLength} B`);
setStatus('attached');
};
+ const saved = (status === 'photoSaved' ? cs.photo?.path : cs.video?.path) || '';
return (
- <View style={{ flex: 1, padding: 20, gap: 14, alignItems: 'center', justifyContent: 'center' }}>
- <Text style={{ fontSize: 48 }}>{rec ? '🔴' : '🎙'}</Text>
+ <View style={{ flex: 1, padding: 16, gap: 12, alignItems: 'center', justifyContent: 'center' }}>
+ {cam ? <MediaView media={cam} style={{ alignSelf: 'stretch', flex: 1, borderRadius: 8 }} /> : <Text style={{ fontSize: 48 }}>{rec ? '🔴' : '🎙'}</Text>}
{rec ? <View style={{ width: 240, height: 10, borderRadius: 5, backgroundColor: th.hover, overflow: 'hidden' }}>
<View style={{ width: `${Math.min(100, Math.round(level * 400))}%`, height: '100%', backgroundColor: '#30d158' }} />
</View> : null}
- <View style={{ flexDirection: 'row', gap: 10 }}>
+ <View style={{ flexDirection: 'row', gap: 8, flexWrap: 'wrap', justifyContent: 'center' }}>
<Button primary label={rec ? t('grabadora.stop') : t('grabadora.record')} onClick={toggle} />
- <Button label={t('grabadora.attach')} onClick={attach} />
+ <Button label={cam ? t('grabadora.cameraOff') : t('grabadora.camera')} onClick={toggleCam} />
+ {cam ? <Button label={t('grabadora.photo')} onClick={photo} /> : null}
+ {cam ? <Button label={video ? t('grabadora.videoStop') : t('grabadora.video')} onClick={toggleVideo} /> : null}
+ <Button label={t('grabadora.newWindow')} onClick={() => wm.open(appId, { new: true })} />
</View>
- <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>{status ? t(`grabadora.${status}`, { name: attached }) : ''}</Text>
+ <Text style={{ fontSize: 12, color: th.textDim, textAlign: 'center' }}>{status ? t(`grabadora.${status}`, { name: status === 'attached' ? attached : saved }) : ''}</Text>
</View>
);
}
diff --git a/tests/lpk-legit/locales/ar.json b/tests/lpk-legit/locales/ar.json
index 0d120fd..d3abfd2 100644
--- a/tests/lpk-legit/locales/ar.json
+++ b/tests/lpk-legit/locales/ar.json
@@ -9,5 +9,20 @@
"noFiles": "لا يوجد إذن للملفات",
"canceled": "أُلغي",
"menu": "المسجّل",
- "about": "مسجّل اختبار LordOS"
+ "about": "مسجّل اختبار LordOS",
+ "newWindow": "نافذة جديدة",
+ "window": "المسجّل — النافذة {n}",
+ "camera": "الكاميرا",
+ "cameraOff": "إيقاف الكاميرا",
+ "photo": "التقاط صورة",
+ "video": "تسجيل فيديو",
+ "videoStop": "إيقاف الفيديو",
+ "noCam": "لا يوجد إذن للكاميرا",
+ "camOn": "الكاميرا تعمل (نقطة خضراء في شريط القوائم)",
+ "camOff": "الكاميرا متوقفة",
+ "revoked": "أُلغي إذن الكاميرا: توقف البث",
+ "photoSaved": "حُفظت الصورة: {name}",
+ "videoSaved": "حُفظ الفيديو: {name}",
+ "saveFailed": "لم يُحفظ",
+ "noDevice": "لا توجد كاميرا"
}
diff --git a/tests/lpk-legit/locales/en.json b/tests/lpk-legit/locales/en.json
index a696e37..c8a2921 100644
--- a/tests/lpk-legit/locales/en.json
+++ b/tests/lpk-legit/locales/en.json
@@ -9,5 +9,20 @@
"noFiles": "No files permission",
"canceled": "Canceled",
"menu": "Recorder",
- "about": "LordOS test recorder"
+ "about": "LordOS test recorder",
+ "newWindow": "New window",
+ "window": "Recorder — window {n}",
+ "camera": "Camera",
+ "cameraOff": "Turn camera off",
+ "photo": "Take photo",
+ "video": "Record video",
+ "videoStop": "Stop video",
+ "noCam": "No camera permission",
+ "camOn": "Camera on (green dot in the menu bar)",
+ "camOff": "Camera off",
+ "revoked": "Camera permission revoked: the stream stopped",
+ "photoSaved": "Photo saved: {name}",
+ "videoSaved": "Video saved: {name}",
+ "saveFailed": "Not saved",
+ "noDevice": "No camera found"
}
diff --git a/tests/lpk-legit/locales/es.json b/tests/lpk-legit/locales/es.json
index 9619184..5d78661 100644
--- a/tests/lpk-legit/locales/es.json
+++ b/tests/lpk-legit/locales/es.json
@@ -9,5 +9,20 @@
"noFiles": "Sin permiso de archivos",
"canceled": "Cancelado",
"menu": "Grabadora",
- "about": "Grabadora de prueba de LordOS"
+ "about": "Grabadora de prueba de LordOS",
+ "newWindow": "Nueva ventana",
+ "window": "Grabadora — ventana {n}",
+ "camera": "Cámara",
+ "cameraOff": "Apagar la cámara",
+ "photo": "Sacar foto",
+ "video": "Grabar video",
+ "videoStop": "Detener video",
+ "noCam": "Sin permiso de cámara",
+ "camOn": "Cámara encendida (punto verde en la barra de menú)",
+ "camOff": "Cámara apagada",
+ "revoked": "Permiso de cámara revocado: el video se cortó",
+ "photoSaved": "Foto guardada: {name}",
+ "videoSaved": "Video guardado: {name}",
+ "saveFailed": "No se guardó",
+ "noDevice": "No hay cámara"
}
diff --git a/tests/lpk-legit/locales/fr.json b/tests/lpk-legit/locales/fr.json
index 382fc66..01a1feb 100644
--- a/tests/lpk-legit/locales/fr.json
+++ b/tests/lpk-legit/locales/fr.json
@@ -9,5 +9,20 @@
"noFiles": "Pas d’autorisation pour les fichiers",
"canceled": "Annulé",
"menu": "Enregistreur",
- "about": "Enregistreur de test de LordOS"
+ "about": "Enregistreur de test de LordOS",
+ "newWindow": "Nouvelle fenêtre",
+ "window": "Enregistreur — fenêtre {n}",
+ "camera": "Caméra",
+ "cameraOff": "Éteindre la caméra",
+ "photo": "Prendre une photo",
+ "video": "Filmer",
+ "videoStop": "Arrêter la vidéo",
+ "noCam": "Pas d’autorisation pour la caméra",
+ "camOn": "Caméra allumée (point vert dans la barre des menus)",
+ "camOff": "Caméra éteinte",
+ "revoked": "Autorisation de la caméra révoquée : le flux s’est arrêté",
+ "photoSaved": "Photo enregistrée : {name}",
+ "videoSaved": "Vidéo enregistrée : {name}",
+ "saveFailed": "Non enregistré",
+ "noDevice": "Aucune caméra"
}
diff --git a/tests/lpk-legit/locales/pt.json b/tests/lpk-legit/locales/pt.json
index b348473..6a007b8 100644
--- a/tests/lpk-legit/locales/pt.json
+++ b/tests/lpk-legit/locales/pt.json
@@ -9,5 +9,20 @@
"noFiles": "Sem permissão de arquivos",
"canceled": "Cancelado",
"menu": "Gravador",
- "about": "Gravador de teste do LordOS"
+ "about": "Gravador de teste do LordOS",
+ "newWindow": "Nova janela",
+ "window": "Gravador — janela {n}",
+ "camera": "Câmera",
+ "cameraOff": "Desligar a câmera",
+ "photo": "Tirar foto",
+ "video": "Gravar vídeo",
+ "videoStop": "Parar vídeo",
+ "noCam": "Sem permissão de câmera",
+ "camOn": "Câmera ligada (ponto verde na barra de menus)",
+ "camOff": "Câmera desligada",
+ "revoked": "Permissão de câmera revogada: o vídeo parou",
+ "photoSaved": "Foto salva: {name}",
+ "videoSaved": "Vídeo salvo: {name}",
+ "saveFailed": "Não foi salvo",
+ "noDevice": "Nenhuma câmera"
}
diff --git a/tests/lpk-legit/manifest.json b/tests/lpk-legit/manifest.json
index 8c07d0f..725e239 100644
--- a/tests/lpk-legit/manifest.json
+++ b/tests/lpk-legit/manifest.json
@@ -9,7 +9,7 @@
"es": "Graba una nota de voz y adjunta un archivo",
"en": "Record a voice note and attach a file"
},
- "version": "1.0.0",
+ "version": "1.1.0",
"icon": "icon.png",
"size": [
520,
@@ -17,6 +17,7 @@
],
"permissions": [
"microphone",
+ "camera",
"files"
]
}
diff --git a/themes/classic/index.jsx b/themes/classic/index.jsx
index c3eaf2a..01c45c2 100644
--- a/themes/classic/index.jsx
+++ b/themes/classic/index.jsx
@@ -5,7 +5,7 @@
// 4. App: fondo + ventanas + barra
// Copiá esta carpeta, cambiá theme.json y empezá a modificar.
import {
- startShell, View, Text, screen, addListener, ThemeProvider, useSettings, useWindows, useClock,
+ startShell, settings, View, Text, screen, addListener, ThemeProvider, useSettings, useWindows, useClock,
configureWindows, getApp, wm, AppHost, session, windowTitle, t as tr, formatTime,
ScrollView, useLauncherApps, launchApp, windowIcon, APP_CATEGORIES, appCategory, useDockEntries, dockActivate, dockMenu,
DesktopWidgets, PrivacyIndicators, registerGestureActions, WindowShell, StatusItems, dockPrefs,
@@ -173,7 +173,7 @@ function JumpList({ t, entry, x, onClose, pos }) {
// Barra de tareas: apps ancladas y abiertas, una por app (las ventanas de la misma app van juntas).
// Clic: abre la app o trae su ventana (si ya estaba al frente, la minimiza); clic derecho: JumpList.
function Taskbar({ t, onStart, pos }) {
- const clock = useClock((d) => formatTime(d), 1000);
+ const clock = useClock((d) => formatTime(d, { seconds: !!settings.get().clock?.seconds }), 1000); // Settings → Date & Time
const entries = useDockEntries(['files', 'terminal', 'store']);
const { focused } = useWindows();
const [jump, setJump] = useState(null);
diff --git a/themes/default/components/MenuBar.jsx b/themes/default/components/MenuBar.jsx
index 839bbdf..8e9c65d 100644
--- a/themes/default/components/MenuBar.jsx
+++ b/themes/default/components/MenuBar.jsx
@@ -1,11 +1,12 @@
// Barra de menú superior: menú L, app activa, menú Ventana, distribución de teclado,
// Centro de control y reloj.
-import { View, Text, useClock, wm, getApp, session, useAppMenus, t as tr, appName, formatDate, formatTime, keyboard, useSettings, direction, screen, windowTitle, LordOSLogo, spotlight, PrivacyIndicators, StatusItems, help } from '@lordos/sdk';
+import { View, Text, useClock, wm, getApp, session, useAppMenus, t as tr, appName, formatDate, formatTime, keyboard, useSettings, direction, screen, windowTitle, LordOSLogo, spotlight, PrivacyIndicators, StatusItems, help, menuClock } from '@lordos/sdk';
import { useRef, useState } from 'react';
import { Menu } from './Menu.jsx';
// Fecha y hora con el formato de la región (sdk/i18n.js).
-const format = (d) => `${formatDate(d, 'short')} ${formatTime(d)}`;
+// with the format chosen in Settings → Date & Time (sdk/hardware.jsx)
+const format = (d) => menuClock(d);
function BarItem({ t, children, onClick, active, anchorRef }) {
const [hover, setHover] = useState(false);
diff --git a/tools/iso/build.sh b/tools/iso/build.sh
index 5d6717d..6bd109c 100755
--- a/tools/iso/build.sh
+++ b/tools/iso/build.sh
@@ -122,7 +122,7 @@ echo 'net.ipv4.ping_group_range = 0 2147483647' > "$CH/etc/sysctl.d/50-lordos-pi
# usuario de la sesión live: sin contraseña, sudo sin contraseña. Entra solo (inicio automático de
# lord-sessiond); al bloquear la pantalla se vuelve con la contraseña vacía (solo en el monitor y
# solo para el usuario de inicio automático; ver docs/SESIONES.md)
-in_ch useradd -m -s /bin/bash -c "LordOS" -G sudo,audio,video,input,render,lpadmin,pipewire lordos
+in_ch useradd -m -s /bin/bash -c "LordOS" -G sudo,audio,video,input,render,lpadmin,pipewire,plugdev lordos
in_ch passwd -d lordos > /dev/null
mkdir -p "$CH/etc/lordos"
printf '# ISO live: entra solo con el usuario lordos. El sistema instalado usa la pantalla de ingreso.\nAUTOLOGIN=lordos\n' > "$CH/etc/lordos/session.conf"
diff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.sh
index ef1b763..97c9c97 100755
--- a/tools/iso/mkdeb.sh
+++ b/tools/iso/mkdeb.sh
@@ -40,6 +40,12 @@ strip --strip-unneeded "$L/bin/lord-server" "$L/bin/lord-sessiond" "$L/bin/lord-
# lord-server solo lanza el lord-media de su misma carpeta (medios: video, fotos, cámara, grabadora)
[ -x server/build/lord-media ] && install -m 755 server/build/lord-media "$L/bin/lord-media"
[ -x "$L/bin/lord-media" ] && { strip --strip-unneeded "$L/bin/lord-media" 2>/dev/null || true; }
+# lord-vault: Passwords and the system keyring (docs/PASSWORDS.md); lord-server only launches the one in its own folder
+[ -x server/build/lord-vault ] && install -m 755 server/build/lord-vault "$L/bin/lord-vault"
+[ -x "$L/bin/lord-vault" ] && { strip --strip-unneeded "$L/bin/lord-vault" 2>/dev/null || true; }
+# FIDO2 security keys reachable by the session user (lord-sessiond sessions have no logind seat)
+install -d "$PKG/usr/lib/udev/rules.d"
+install -m 644 packaging/udev/71-lordos-fido.rules "$PKG/usr/lib/udev/rules.d/71-lordos-fido.rules"
for d in themes/*/; do
n=$(basename "$d")
[ -f "$d/theme.bundle.js" ] || continue