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.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Checkpoint: fan control work in progress (lord-fand, curves, Settings Cooling), Raspberry Pi kernel build and board verification scripts, locales
Federico Pereirac1a281667e2b
diff --git a/apps/monitor/Cooling.jsx b/apps/monitor/Cooling.jsxnew file mode 100644index 0000000..7a80c19--- /dev/null+++ b/apps/monitor/Cooling.jsx@@ -0,0 +1,79 @@+// Monitor → Cooling (docs/FANS.md): the cooling hardware drawn live (the fan turns with the real+// duty, the heatsink warms with the temperature), the active profile and step on its curve, a+// temperature/fan history and a quick "full speed" button. The profile and the curve are changed in+// Settings → Cooling; both use lord.fan (lord-fand).+import {+ View, Text, Button, useTheme, useLocale, useFan, useStore, fanHistory, fanCase, fanControl, coolingVariant, CoolingArt,+ FanCurveChart, formatTemp, formatNumber, typeScale, wm, FAN_HISTORY,+} from '@lordos/sdk';+import { useMemo, useState } from 'react';+import { Card, Big, Stat, useCardStyle } from './index.jsx';+import { Chart } from './Chart.jsx';++const C = { temp: '#ff9f0a', fan: '#32ade6' };++export function CoolingTab() {+ const t = useTheme();+ const { t: tr } = useLocale();+ const s = useFan();+ const caseId = useStore(fanCase);+ const hist = useStore(fanHistory);+ const card = useCardStyle();+ const [err, setErr] = useState('');+ const series = useMemo(() => ({ times: hist.map((x) => x.t), temp: hist.map((x) => x.temp), pct: hist.map((x) => x.pct) }), [hist]);+ if (s === undefined) return null;+ const variant = coolingVariant(s, caseId);+ const fan = s?.fans?.[0];+ const pct = fan && fan.pct >= 0 ? fan.pct : 0;+ const forced = !!s && s.force !== 'off';+ const profile = !s ? '—' : forced ? tr('cooling.forcedNow') : tr(`cooling.profiles.${s.profile}`);+ const step = !s || !s.fans.length || s.profile === 'auto' || forced ? '—'+ : s.step < 0 ? tr('cooling.stepOff') : tr('cooling.stepOf', { n: s.step + 1, total: s.curve.length });+ const toggleForce = () => {+ const r = fanControl.force(forced ? 'off' : 30);+ setErr(r ? tr(`errors.${r}`) : '');+ };+ const openSettings = () => wm.open('settings', { args: { section: 'cooling', nonce: Date.now() } });+ return (+ <>+ <View style={{ flexDirection: 'row', gap: 12 }}>+ <Card icon="fan" title={tr(`cooling.variant.${variant}`)} style={{ flex: 1 }}+ right={s && s.fans.length ? <Button small primary={!forced} label={forced ? tr('cooling.stopForce') : tr('cooling.force100')} onClick={toggleForce} /> : null}>+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 16 }}>+ <CoolingArt variant={variant} pct={pct} temp={s?.temp} width={280} height={156} />+ <View style={{ flex: 1, minWidth: 0, gap: 10 }}>+ <Big value={formatTemp(s?.temp)} small={tr('monitor.cpuTemp')} />+ <Big value={fan ? tr('cooling.fanPct', { v: pct }) : '—'} small={fan && fan.rpm >= 0 ? tr('cooling.rpm', { v: formatNumber(fan.rpm, 0) }) : null} />+ <Text style={{ fontSize: 11, color: err ? '#ff453a' : t.textDim }}>{err || (!s ? tr('cooling.serviceOff') : !s.fans.length ? tr(s.firmwareFans?.length ? 'cooling.firmwareManaged' : 'cooling.noFans') : '')}</Text>+ </View>+ </View>+ </Card>+ </View>+ {s && s.fans.length > 0 && (+ <View style={{ flexDirection: 'row', gap: 12 }}>+ <Card icon="activity" title={tr('cooling.curve')} style={{ flex: 1 }}+ right={<View onClick={openSettings}><Text style={{ fontSize: 11, color: t.accent, whiteSpace: 'nowrap' }}>{tr('cooling.customize')}</Text></View>}>+ {s.profile === 'auto'+ ? <Text style={{ fontSize: 12, color: t.textDim }}>{tr('cooling.systemManaged')}</Text>+ : <FanCurveChart curve={s.curve} floor={s.floor} hyst={s.hyst} step={forced ? -1 : s.step} temp={s.temp} pct={pct} height={150} />}+ </Card>+ <Card icon="temp" title={tr('cooling.history')} style={{ flex: 1 }}>+ <Chart series={[{ label: tr('cooling.temperature'), values: series.temp, color: C.temp }, { label: tr('cooling.fanSpeed'), values: series.pct, color: C.fan }]}+ max={100} format={(v) => formatNumber(Math.round(v), 0)} times={series.times} capacity={FAN_HISTORY} height={150} bg={card.bg} />+ </Card>+ </View>+ )}+ <View style={{ flexDirection: 'row', gap: 10 }}>+ <Stat icon="temp" label={tr('monitor.cpuTemp')} value={s?.temp != null ? formatNumber(Math.round(s.temp), 0) : '—'} unit={s?.temp != null ? '°C' : null} />+ <Stat label={tr('cooling.profile')} value={profile} />+ <Stat label={tr('cooling.step')} value={step} />+ {(s?.fans || []).map((f) => (+ <Stat key={f.id} icon="fan" label={tr('cooling.fanN', { n: f.id + 1 })} value={f.pct >= 0 ? `${f.pct}` : '—'} unit={f.rpm >= 0 ? tr('cooling.pctRpm', { v: formatNumber(f.rpm, 0) }) : '%'} />+ ))}+ {(s?.firmwareFans || []).map((f, i) => (+ <Stat key={`r${i}`} icon="fan" label={tr('cooling.firmwareFan', { n: i + 1 })} value={f.rpm >= 0 ? formatNumber(f.rpm, 0) : '—'} unit={tr('monitor.rpm')} />+ ))}+ </View>+ </>+ );+}diff --git a/apps/monitor/index.jsx b/apps/monitor/index.jsxindex ef2e514..235718c 100644--- a/apps/monitor/index.jsx+++ b/apps/monitor/index.jsx@@ -14,6 +14,7 @@ import { Glyph, MonitorIcon } from './icons.jsx';import { NetworkTab } from './Network.jsx';import { MonitorPrivacy } from './Privacy.jsx';import { FirewallPrivacy } from './Firewall.jsx';+import { CoolingTab } from './Cooling.jsx';export function Icon({ size }) { return <MonitorIcon size={size} />; }@@ -461,7 +462,7 @@ export default function Monitor() {const ready = useStore(monitorSamples, (l) => l.length > 0);const tabs = [['overview', tr('monitor.tab.overview')], ['cpu', tr('monitor.cpu')], ['memory', tr('monitor.memory')],- ['network', tr('monitor.network')], ['disks', tr('monitor.disks')], ['processes', tr('monitor.processes')],+ ['network', tr('monitor.network')], ['disks', tr('monitor.disks')], ['processes', tr('monitor.processes')], ['cooling', tr('monitor.tab.cooling')],];if (!monitor.available()) {return <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text style={{ fontSize: 13, color: t.textDim }}>{tr('monitor.unavailable')}</Text></View>;@@ -479,6 +480,10 @@ export default function Monitor() {<View style={{ flex: 1, padding: 20 }}><Text style={{ fontSize: 13, color: t.textDim }}>{tr('monitor.waiting')}</Text></View>) : tab === 'network' ? (<Network prefs={prefs} />+ ) : tab === 'cooling' ? (+ <ScrollView style={{ flex: 1 }}>+ <View style={{ paddingHorizontal: 20, paddingTop: 20, paddingBottom: 24, gap: 16 }}><CoolingTab /></View>+ </ScrollView>) : tab === 'processes' ? (<ScrollView style={{ flex: 1 }}><View style={{ paddingHorizontal: 20, paddingTop: 20, paddingBottom: 24, gap: 16 }}><ProcessesTab /></View>diff --git a/apps/settings/Cooling.jsx b/apps/settings/Cooling.jsxnew file mode 100644index 0000000..660500a--- /dev/null+++ b/apps/settings/Cooling.jsx@@ -0,0 +1,143 @@+// Settings → Cooling (docs/FANS.md): the detected cooling hardware drawn at the top with the live+// temperature and fan speed, the fan profile (or "let the system decide"), the curve (draggable in+// the custom profile), "full speed for a while" and, on a Raspberry Pi 5, the case. lord-fand (root)+// does the work; this page only sends validated requests through lord.fan.+import {+ View, Text, useTheme, useLocale, Segmented, Toggle, Button, admin, useFan, useStore, fanCase, fanControl, refreshFan,+ coolingVariant, CoolingArt, FanCurveChart, formatTemp, formatNumber, spacing, typeScale,+} from '@lordos/sdk';+import { useState } from 'react';+import { GroupBox, SettingRow, ValueRow, PopUp, Stack, Note, tint } from './ui.jsx';++const PROFILES = ['quiet', 'balanced', 'performance', 'always', 'custom'];+const PRESET_CURVE = [[55, 30], [60, 55], [65, 100]];++const minutesLabel = (tr, s) => {+ const m = Math.ceil(s / 60);+ return m >= 60 ? tr('cooling.leftHM', { h: Math.floor(m / 60), m: m % 60 }) : tr('cooling.leftM', { m });+};++function Header({ s, variant, tr }) {+ const t = useTheme();+ const fan = s?.fans?.[0];+ const pct = fan && fan.pct >= 0 ? fan.pct : 0;+ const forced = s && s.force !== 'off';+ const stepText = !s ? tr('cooling.serviceOff')+ : !s.fans.length ? tr(s.firmwareFans?.length ? 'cooling.firmwareManaged' : 'cooling.noFans')+ : forced ? tr('cooling.forcedNow')+ : s.profile === 'auto' ? tr('cooling.systemManaged')+ : s.step < 0 ? tr('cooling.belowFirst', { temp: s.curve[0]?.[0] ?? '' })+ : tr('cooling.stepOf', { n: s.step + 1, total: s.curve.length });+ return (+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: spacing.l, padding: spacing.m, borderRadius: 12,+ backgroundColor: t.mode === 'dark' ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.025)', border: `1px solid ${t.separator}` }}>+ <CoolingArt variant={variant} pct={pct} temp={s?.temp} width={300} height={164} />+ <View style={{ flex: 1, minWidth: 0, gap: spacing.s }}>+ <Text style={{ fontSize: typeScale.caption, color: t.textDim, textAlign: 'start' }}>{tr(`cooling.variant.${variant}`)}</Text>+ <Text style={{ fontSize: 30, fontWeight: 600, color: t.text, textAlign: 'start' }}>{formatTemp(s?.temp)}</Text>+ {fan ? (+ <View style={{ gap: 2 }}>+ <Text style={{ fontSize: typeScale.headline, fontWeight: 600, color: t.text, textAlign: 'start' }}>{tr('cooling.fanPct', { v: pct })}</Text>+ {fan.rpm >= 0 ? <Text style={{ fontSize: typeScale.callout, color: t.textDim, textAlign: 'start' }}>{tr('cooling.rpm', { v: formatNumber(fan.rpm, 0) })}</Text> : null}+ </View>+ ) : null}+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>+ <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: !s ? tint.off : forced ? tint.warn : tint.ok }} />+ <Text style={{ flex: 1, minWidth: 0, fontSize: typeScale.callout, color: t.textDim, textAlign: 'start' }}>{stepText}</Text>+ </View>+ </View>+ </View>+ );+}++export function CoolingSettings() {+ const { t: tr } = useLocale();+ const s = useFan();+ const caseId = useStore(fanCase);+ const [err, setErr] = useState('');+ const [caseMsg, setCaseMsg] = useState(null);+ const isAdmin = admin.available();+ const variant = coolingVariant(s, caseId);+ const run = (code) => setErr(code ? tr(`errors.${code}`) : '');++ if (s === undefined) return <Stack><Note>{tr('cooling.loading')}</Note></Stack>;+ const controllable = !!s && s.fans.length > 0;+ const custom = s?.custom?.length ? s.custom : PRESET_CURVE;+ const shown = s?.profile === 'custom' ? custom : s?.curve || [];+ const fan = s?.fans?.[0];+ const forceValue = !s || s.force === 'off' ? 'off' : s.force === 'on' ? 'on' : 'timed';+ const forceOpts = [['off', tr('cooling.forceOff')], ['30', tr('cooling.force30')], ['60', tr('cooling.force60')], ['120', tr('cooling.force120')], ['on', tr('cooling.forceOn')]];+ if (forceValue === 'timed') forceOpts.unshift(['timed', minutesLabel(tr, s.forceLeft)]);+ const setForce = (v) => { if (v !== 'timed') run(fanControl.force(v === 'off' || v === 'on' ? v : Number(v))); };+ const editCurve = (pts) => run(fanControl.setCurve(pts));+ const addPoint = () => {+ const last = custom[custom.length - 1];+ if (custom.length >= 8 || last[0] >= 90) return;+ editCurve([...custom, [Math.min(90, last[0] + 5), Math.min(100, last[1] + 10)]]);+ };+ const removePoint = () => { if (custom.length > 1) editCurve(custom.slice(0, -1)); };++ return (+ <Stack>+ <Header s={s} variant={variant} tr={tr} />+ {!s && <Note tone="warn">{tr('cooling.serviceOffHint')}</Note>}+ {s && !controllable && (+ <GroupBox title={tr('cooling.fans')} footer={tr(s.firmwareFans?.length ? 'cooling.firmwareHint' : 'cooling.noFansHint')}>+ {s.firmwareFans?.length+ ? s.firmwareFans.map((f, i) => <ValueRow key={i} label={tr('cooling.fanN', { n: i + 1 })} value={f.rpm >= 0 ? tr('cooling.rpm', { v: formatNumber(f.rpm, 0) }) : '—'} />)+ : <ValueRow label={tr('cooling.cooling')} value={tr('cooling.passive')} />}+ </GroupBox>+ )}+ {controllable && (+ <GroupBox title={tr('cooling.profile')} footer={err || (isAdmin ? tr(`cooling.profileHint.${s.profile}`) : tr('cooling.needAdmin'))}>+ <SettingRow label={tr('cooling.systemControl')} hint={tr('cooling.systemControlHint')} disabled={!isAdmin}>+ <Toggle small on={s.profile === 'auto'} onChange={(on) => isAdmin && run(fanControl.setProfile(on ? 'auto' : 'balanced'))} />+ </SettingRow>+ {s.profile !== 'auto' && (+ <SettingRow label={tr('cooling.curveProfile')} stack disabled={!isAdmin}>+ <Segmented small value={s.profile} onChange={(p) => isAdmin && run(fanControl.setProfile(p))}+ options={PROFILES.map((p) => [p, tr(`cooling.profiles.${p}`)])} />+ </SettingRow>+ )}+ </GroupBox>+ )}+ {controllable && s.profile !== 'auto' && (+ <GroupBox title={tr('cooling.curve')} footer={tr(s.profile === 'custom' ? 'cooling.curveHintCustom' : 'cooling.curveHint', { hyst: s.hyst })}>+ <View style={{ paddingVertical: spacing.m }}>+ <FanCurveChart curve={shown} floor={s.profile === 'custom' ? 0 : s.floor} hyst={s.hyst} step={s.force === 'off' ? s.step : -1}+ temp={s.temp} pct={fan ? fan.pct : null} height={190} onChange={s.profile === 'custom' && isAdmin ? editCurve : undefined} />+ </View>+ {s.profile === 'custom' && isAdmin && (+ <View style={{ flexDirection: 'row', gap: spacing.s, paddingBottom: spacing.s, justifyContent: 'flex-end' }}>+ <Button small label={tr('cooling.addPoint')} onClick={addPoint} disabled={custom.length >= 8} />+ <Button small label={tr('cooling.removePoint')} onClick={removePoint} disabled={custom.length <= 1} />+ <Button small label={tr('cooling.resetCurve')} onClick={() => editCurve(PRESET_CURVE)} />+ </View>+ )}+ </GroupBox>+ )}+ {controllable && (+ <GroupBox title={tr('cooling.boost')} footer={tr('cooling.boostHint')}>+ <SettingRow label={tr('cooling.force')} disabled={!isAdmin}>+ <PopUp value={forceValue} options={forceOpts} onChange={setForce} disabled={!isAdmin} />+ </SettingRow>+ </GroupBox>+ )}+ {s && s.board === 'pi5' && caseId != null && (+ <GroupBox title={tr('cooling.case')} footer={caseMsg ? caseMsg.text : tr('cooling.caseHint')}>+ <SettingRow label={tr('cooling.caseModel')} disabled={!isAdmin}>+ <PopUp value={caseId} width={210} disabled={!isAdmin}+ options={[['none', tr('cooling.caseNone')], ['argon-one-v5', tr('cooling.caseArgonV5')]]}+ onChange={(id) => admin.run('rpi-case', id).then(() => { fanCase.set(() => id); setCaseMsg({ ok: true, text: tr('cooling.caseRestart') }); },+ (e) => setCaseMsg({ ok: false, text: e.message }))} />+ </SettingRow>+ </GroupBox>+ )}+ {s && (+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>+ <Button small label={tr('cooling.refresh')} onClick={refreshFan} />+ </View>+ )}+ </Stack>+ );+}diff --git a/apps/settings/index.jsx b/apps/settings/index.jsxindex 5618831..764d812 100644--- a/apps/settings/index.jsx+++ b/apps/settings/index.jsx@@ -22,6 +22,7 @@ import { DockSettings } from './Dock.jsx';import { DisplaysSettings } from './Displays.jsx';import { BluetoothSettings } from './Bluetooth.jsx';import { PowerSettings } from './Power.jsx';+import { CoolingSettings } from './Cooling.jsx';import { NotificationsSettings } from './Notifications.jsx';import { DateTimeSettings } from './DateTime.jsx';import { DefaultAppsSettings } from './DefaultApps.jsx';@@ -119,6 +120,9 @@ function Appearance() {<SettingRow label={tr('settings.effects')} hint={tr('settings.effectsHint')}><Toggle small on={s.effects} onChange={(effects) => set({ effects })} /></SettingRow>+ <SettingRow label={tr('settings.reduceMotion')} hint={tr('settings.reduceMotionHint')}>+ <Toggle small on={!!s.reduceMotion} onChange={(reduceMotion) => set({ reduceMotion })} />+ </SettingRow></Section></Stack>);@@ -418,12 +422,26 @@ function BoltGlyph() {);}+// A fan: three rounded blades around a hub.+function FanGlyph() {+ return (+ <View style={{ width: 14, height: 14, direction: 'ltr' }}>+ {[0, 120, 240].map((r) => (+ <View key={r} style={{ position: 'absolute', left: 0, top: 0, width: 14, height: 14, transform: `rotate(${r}deg)` }}>+ <View style={{ position: 'absolute', left: 6, top: 0, width: 5, height: 7, borderTopRightRadius: 5, borderTopLeftRadius: 2, borderBottomRightRadius: 2, backgroundColor: '#fff' }} />+ </View>+ ))}+ <View style={{ position: 'absolute', left: 5, top: 5, width: 4, height: 4, borderRadius: 2, backgroundColor: '#fff' }} />+ </View>+ );+}+// Sidebar groups (as in TangoOS): [id, component, icon color, symbol (a glyph or a component)].const GROUPS = [[['general', General, '#8e8e93', 'i'], ['appearance', Appearance, '#3a3a3c', '◐'], ['wallpaper', Wallpapers, '#30b0c7', '▣'], ['dock', DockSettings, '#3a3a3c', '▁'], ['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, '#8e8e93', '⌨'], ['trackpad', TrackpadSettings, '#8e8e93', '▭'], ['defaultapps', DefaultAppsSettings, '#8e8e93', '◫']],- [['power', PowerSettings, '#30d158', BoltGlyph], ['privacy', PrivacySettings, '#0a84ff', LockGlyph], ['users', UsersSettings, '#0a84ff', '☺'], ['updates', Updates, '#8e8e93', '↻'], ['themes', Themes, '#ff9f0a', '◧'], ['session', Session, '#ff453a', '↪']],+ [['power', PowerSettings, '#30d158', BoltGlyph], ['cooling', CoolingSettings, '#32ade6', FanGlyph], ['privacy', PrivacySettings, '#0a84ff', LockGlyph], ['users', UsersSettings, '#0a84ff', '☺'], ['updates', Updates, '#8e8e93', '↻'], ['themes', Themes, '#ff9f0a', '◧'], ['session', Session, '#ff453a', '↪']],];const SECTIONS = GROUPS.flat();diff --git a/assets/locales/en/cooling.json b/assets/locales/en/cooling.jsonnew file mode 100644index 0000000..4008f8c--- /dev/null+++ b/assets/locales/en/cooling.json@@ -0,0 +1,74 @@+{+ "temp": "{v} °C",+ "leftM": "Full speed · {m} min left",+ "leftHM": "Full speed · {h} h {m} min left",+ "serviceOff": "The fan service is not running",+ "serviceOffHint": "The fan service (lord-fand) is not running. The kernel or the firmware keeps cooling the computer.",+ "firmwareManaged": "Fans managed by the firmware",+ "firmwareHint": "These fans report their speed, but the firmware controls them. LordOS leaves them alone.",+ "noFans": "No controllable fans",+ "noFansHint": "This computer has no fan LordOS can drive: it is cooled passively or by its firmware.",+ "forcedNow": "Full speed",+ "systemManaged": "Managed by the system",+ "belowFirst": "Off until {temp} °C",+ "stepOf": "Step {n} of {total}",+ "stepOff": "Off",+ "variant.argon": "Argon ONE V5 case",+ "variant.cooler": "Raspberry Pi 5 · fan header",+ "variant.pc": "Case and CPU fans",+ "variant.none": "Passive cooling",+ "fanPct": "Fan {v} %",+ "rpm": "{v} RPM",+ "pctRpm": "% · {v} RPM",+ "loading": "Looking for fans…",+ "fans": "Fans",+ "fanN": "Fan {n}",+ "firmwareFan": "Firmware fan {n}",+ "cooling": "Cooling",+ "passive": "Passive",+ "profile": "Profile",+ "profileHint.auto": "The kernel or the motherboard firmware decides the fan speed.",+ "profileHint.quiet": "Starts at 60 °C and stays low: the quietest choice.",+ "profileHint.balanced": "Starts at 55 °C with 30 %, 55 % from 60 °C and full speed from 65 °C.",+ "profileHint.performance": "Starts at 45 °C and reaches full speed at 60 °C.",+ "profileHint.always": "Never stops (40 %) and reaches full speed at 65 °C.",+ "profileHint.custom": "Your own steps: drag them on the curve below.",+ "needAdmin": "Only an administrator can change the fans.",+ "systemControl": "Let the system control the fans",+ "systemControlHint": "Off: LordOS drives them with the profile below.",+ "curveProfile": "Fan profile",+ "profiles.auto": "System",+ "profiles.quiet": "Quiet",+ "profiles.balanced": "Balanced",+ "profiles.performance": "Performance",+ "profiles.always": "Always on",+ "profiles.custom": "Custom",+ "curve": "Fan curve",+ "curveHint": "Each step starts at its temperature and ends {hyst} °C below it (orange band), so the fan does not keep switching on and off.",+ "curveHintCustom": "Drag a point to change its temperature and speed. Each step ends {hyst} °C below where it starts (orange band).",+ "addPoint": "Add step",+ "removePoint": "Remove step",+ "resetCurve": "Reset",+ "boost": "Heavy work",+ "boostHint": "Full speed for a while, for example while compiling. The profile comes back by itself.",+ "force": "Run the fans at full speed",+ "forceOff": "Off",+ "force30": "For 30 minutes",+ "force60": "For 1 hour",+ "force120": "For 2 hours",+ "forceOn": "Until I turn it off",+ "case": "Case",+ "caseHint": "Turns on what the case adds (its front USB ports and audio board). Takes effect after a restart.",+ "caseModel": "Case model",+ "caseNone": "None or another case",+ "caseArgonV5": "Argon ONE V5 case",+ "caseRestart": "Saved. Restart the computer to use the case's ports.",+ "refresh": "Refresh",+ "stopForce": "Back to the profile",+ "force100": "Full speed for 30 min",+ "customize": "Customize…",+ "history": "Temperature and fan",+ "temperature": "Temperature (°C)",+ "fanSpeed": "Fan (%)",+ "step": "Step"+}diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.jsonindex 31e45db..912f11f 100644--- a/assets/locales/en/errors.json+++ b/assets/locales/en/errors.json@@ -530,5 +530,12 @@"wifi.rejected": "The Wi-Fi service did not accept the network","wifi.saveFailed": "Could not save the network","wifi.selectFailed": "The Wi-Fi service could not select the network",- "wifi.startFailed": "Could not start Wi-Fi on {name}"+ "wifi.startFailed": "Could not start Wi-Fi on {name}",+ "fan.notAdmin": "Only an administrator can change the fans",+ "fan.badRequest": "The fan service refused the request",+ "fan.badCurve": "Invalid curve: temperatures from 30 to 90 °C going up, and speeds that never go down",+ "fan.saveFailed": "Could not save the fan settings",+ "fan.unavailable": "The fan service is not running",+ "hw.notRaspberryPi5": "This only works on a Raspberry Pi 5",+ "hw.caseFailed": "Could not save the case settings"}diff --git a/assets/locales/en/monitor.json b/assets/locales/en/monitor.jsonindex b572df4..3201e4f 100644--- a/assets/locales/en/monitor.json+++ b/assets/locales/en/monitor.json@@ -134,5 +134,6 @@"privacy.local": "Everything is computed on this computer, and only while Monitor is open. No IP address leaves the computer.","privacy.open": "Open Monitor","net.placeApps": "Apps",- "net.privacyShort": "IP-to-country from a local database (DB-IP Lite, CC BY 4.0, db-ip.com): no address leaves the computer."+ "net.privacyShort": "IP-to-country from a local database (DB-IP Lite, CC BY 4.0, db-ip.com): no address leaves the computer.",+ "tab.cooling": "Cooling"}diff --git a/assets/locales/en/settings.json b/assets/locales/en/settings.jsonindex 32c86f8..7e40082 100644--- a/assets/locales/en/settings.json+++ b/assets/locales/en/settings.json@@ -237,5 +237,9 @@"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"+ "keywords.defaultapps": "default apps browser mail music video images pdf text editor terminal open with mimeapps",+ "section.cooling": "Cooling",+ "keywords.cooling": "fan fans temperature cooling heat noise curve case full speed",+ "reduceMotion": "Reduce motion",+ "reduceMotionHint": "Stops decorative animations, like the spinning fan in Cooling."}diff --git a/assets/locales/en/status.json b/assets/locales/en/status.jsonindex bb9ae5a..d5673b6 100644--- a/assets/locales/en/status.json+++ b/assets/locales/en/status.json@@ -115,5 +115,6 @@},"wifi.connecting": "Connecting to {ssid}…","wifi.disconnected": "Disconnected",- "wifi.forgotten": "Network forgotten"+ "wifi.forgotten": "Network forgotten",+ "hw.caseSet": "Case: {case}"}diff --git a/assets/locales/es/cooling.json b/assets/locales/es/cooling.jsonnew file mode 100644index 0000000..c26cfd9--- /dev/null+++ b/assets/locales/es/cooling.json@@ -0,0 +1,74 @@+{+ "temp": "{v} °C",+ "leftM": "A tope · quedan {m} min",+ "leftHM": "A tope · quedan {h} h {m} min",+ "serviceOff": "El servicio de ventiladores no está en marcha",+ "serviceOffHint": "El servicio de ventiladores (lord-fand) no está en marcha. El kernel o el firmware siguen refrigerando el equipo.",+ "firmwareManaged": "Ventiladores controlados por el firmware",+ "firmwareHint": "Estos ventiladores informan su velocidad, pero los controla el firmware. LordOS no los toca.",+ "noFans": "No hay ventiladores controlables",+ "noFansHint": "Este equipo no tiene ningún ventilador que LordOS pueda manejar: se refrigera de forma pasiva o por su firmware.",+ "forcedNow": "A toda velocidad",+ "systemManaged": "Controlado por el sistema",+ "belowFirst": "Apagado hasta {temp} °C",+ "stepOf": "Escalón {n} de {total}",+ "stepOff": "Apagado",+ "variant.argon": "Caja Argon ONE V5",+ "variant.cooler": "Raspberry Pi 5 · conector de ventilador",+ "variant.pc": "Ventiladores de caja y CPU",+ "variant.none": "Refrigeración pasiva",+ "fanPct": "Ventilador {v} %",+ "rpm": "{v} RPM",+ "pctRpm": "% · {v} RPM",+ "loading": "Buscando ventiladores…",+ "fans": "Ventiladores",+ "fanN": "Ventilador {n}",+ "firmwareFan": "Ventilador del firmware {n}",+ "cooling": "Refrigeración",+ "passive": "Pasiva",+ "profile": "Perfil",+ "profileHint.auto": "El kernel o el firmware de la placa deciden la velocidad.",+ "profileHint.quiet": "Arranca a 60 °C y se mantiene bajo: lo más silencioso.",+ "profileHint.balanced": "Arranca a 55 °C con 30 %, 55 % desde 60 °C y a tope desde 65 °C.",+ "profileHint.performance": "Arranca a 45 °C y llega a tope a 60 °C.",+ "profileHint.always": "Nunca se detiene (40 %) y llega a tope a 65 °C.",+ "profileHint.custom": "Tus propios escalones: arrástralos en la curva de abajo.",+ "needAdmin": "Solo un administrador puede cambiar los ventiladores.",+ "systemControl": "Dejar que el sistema controle los ventiladores",+ "systemControlHint": "Desactivado: LordOS los maneja con el perfil de abajo.",+ "curveProfile": "Perfil de ventilación",+ "profiles.auto": "Sistema",+ "profiles.quiet": "Silencioso",+ "profiles.balanced": "Equilibrado",+ "profiles.performance": "Rendimiento",+ "profiles.always": "Siempre encendido",+ "profiles.custom": "Personalizado",+ "curve": "Curva del ventilador",+ "curveHint": "Cada escalón empieza en su temperatura y termina {hyst} °C por debajo (franja naranja), así el ventilador no se prende y apaga a cada rato.",+ "curveHintCustom": "Arrastra un punto para cambiar su temperatura y velocidad. Cada escalón termina {hyst} °C por debajo de donde empieza (franja naranja).",+ "addPoint": "Añadir escalón",+ "removePoint": "Quitar escalón",+ "resetCurve": "Restablecer",+ "boost": "Trabajo pesado",+ "boostHint": "A toda velocidad por un rato, por ejemplo al compilar. El perfil vuelve solo.",+ "force": "Ventiladores a toda velocidad",+ "forceOff": "No",+ "force30": "Durante 30 minutos",+ "force60": "Durante 1 hora",+ "force120": "Durante 2 horas",+ "forceOn": "Hasta que lo desactive",+ "case": "Caja",+ "caseHint": "Activa lo que agrega la caja (sus puertos USB frontales y la placa de audio). Se aplica al reiniciar.",+ "caseModel": "Modelo de caja",+ "caseNone": "Ninguna u otra caja",+ "caseArgonV5": "Caja Argon ONE V5",+ "caseRestart": "Guardado. Reinicia el equipo para usar los puertos de la caja.",+ "refresh": "Actualizar",+ "stopForce": "Volver al perfil",+ "force100": "A tope 30 min",+ "customize": "Personalizar…",+ "history": "Temperatura y ventilador",+ "temperature": "Temperatura (°C)",+ "fanSpeed": "Ventilador (%)",+ "step": "Escalón"+}diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.jsonindex a84f6e1..312d16d 100644--- a/assets/locales/es/errors.json+++ b/assets/locales/es/errors.json@@ -530,5 +530,12 @@"wifi.rejected": "El servicio de Wi-Fi no aceptó la red","wifi.saveFailed": "No se pudo guardar la red","wifi.selectFailed": "El servicio de Wi-Fi no pudo elegir la red",- "wifi.startFailed": "No se pudo iniciar el Wi-Fi en {name}"+ "wifi.startFailed": "No se pudo iniciar el Wi-Fi en {name}",+ "fan.notAdmin": "Solo un administrador puede cambiar los ventiladores",+ "fan.badRequest": "El servicio de ventiladores rechazó la solicitud",+ "fan.badCurve": "Curva no válida: temperaturas de 30 a 90 °C en subida y velocidades que nunca bajan",+ "fan.saveFailed": "No se pudo guardar la configuración de los ventiladores",+ "fan.unavailable": "El servicio de ventiladores no está en marcha",+ "hw.notRaspberryPi5": "Esto solo funciona en una Raspberry Pi 5",+ "hw.caseFailed": "No se pudo guardar la configuración de la caja"}diff --git a/assets/locales/es/monitor.json b/assets/locales/es/monitor.jsonindex 5969724..e7e47e5 100644--- a/assets/locales/es/monitor.json+++ b/assets/locales/es/monitor.json@@ -134,5 +134,6 @@"privacy.local": "Todo se calcula en este equipo y solo mientras el Monitor está abierto. Ninguna dirección IP sale del equipo.","privacy.open": "Abrir Monitor","net.placeApps": "Apps",- "net.privacyShort": "País por IP con una base local (DB-IP Lite, CC BY 4.0, db-ip.com): ninguna dirección sale del equipo."+ "net.privacyShort": "País por IP con una base local (DB-IP Lite, CC BY 4.0, db-ip.com): ninguna dirección sale del equipo.",+ "tab.cooling": "Refrigeración"}diff --git a/assets/locales/es/settings.json b/assets/locales/es/settings.jsonindex c824c50..beee647 100644--- a/assets/locales/es/settings.json+++ b/assets/locales/es/settings.json@@ -237,5 +237,9 @@"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"+ "keywords.defaultapps": "apps por defecto predeterminadas navegador correo música video imágenes pdf editor de texto terminal abrir con",+ "section.cooling": "Refrigeración",+ "keywords.cooling": "ventilador ventiladores temperatura refrigeración calor ruido curva caja a tope fan cooling",+ "reduceMotion": "Reducir movimiento",+ "reduceMotionHint": "Detiene las animaciones decorativas, como el ventilador que gira en Refrigeración."}diff --git a/assets/locales/es/status.json b/assets/locales/es/status.jsonindex dcaf673..fb0722d 100644--- a/assets/locales/es/status.json+++ b/assets/locales/es/status.json@@ -115,5 +115,6 @@},"wifi.connecting": "Conectando a {ssid}…","wifi.disconnected": "Desconectado",- "wifi.forgotten": "Red olvidada"+ "wifi.forgotten": "Red olvidada",+ "hw.caseSet": "Caja: {case}"}diff --git a/assets/locales/pt/cooling.json b/assets/locales/pt/cooling.jsonnew file mode 100644index 0000000..129de50--- /dev/null+++ b/assets/locales/pt/cooling.json@@ -0,0 +1,74 @@+{+ "temp": "{v} °C",+ "leftM": "Velocidade máxima · faltam {m} min",+ "leftHM": "Velocidade máxima · faltam {h} h {m} min",+ "serviceOff": "O serviço de ventoinhas não está em execução",+ "serviceOffHint": "O serviço de ventoinhas (lord-fand) não está em execução. O kernel ou o firmware continuam resfriando o computador.",+ "firmwareManaged": "Ventoinhas controladas pelo firmware",+ "firmwareHint": "Estas ventoinhas informam a velocidade, mas quem as controla é o firmware. O LordOS não mexe nelas.",+ "noFans": "Nenhuma ventoinha controlável",+ "noFansHint": "Este computador não tem ventoinha que o LordOS possa controlar: é resfriado de forma passiva ou pelo firmware.",+ "forcedNow": "Velocidade máxima",+ "systemManaged": "Controlado pelo sistema",+ "belowFirst": "Desligada até {temp} °C",+ "stepOf": "Degrau {n} de {total}",+ "stepOff": "Desligada",+ "variant.argon": "Gabinete Argon ONE V5",+ "variant.cooler": "Raspberry Pi 5 · conector de ventoinha",+ "variant.pc": "Ventoinhas do gabinete e da CPU",+ "variant.none": "Resfriamento passivo",+ "fanPct": "Ventoinha {v} %",+ "rpm": "{v} RPM",+ "pctRpm": "% · {v} RPM",+ "loading": "Procurando ventoinhas…",+ "fans": "Ventoinhas",+ "fanN": "Ventoinha {n}",+ "firmwareFan": "Ventoinha do firmware {n}",+ "cooling": "Resfriamento",+ "passive": "Passivo",+ "profile": "Perfil",+ "profileHint.auto": "O kernel ou o firmware da placa-mãe decidem a velocidade.",+ "profileHint.quiet": "Começa a 60 °C e fica baixa: a opção mais silenciosa.",+ "profileHint.balanced": "Começa a 55 °C com 30 %, 55 % a partir de 60 °C e máxima a partir de 65 °C.",+ "profileHint.performance": "Começa a 45 °C e chega à máxima a 60 °C.",+ "profileHint.always": "Nunca para (40 %) e chega à máxima a 65 °C.",+ "profileHint.custom": "Seus próprios degraus: arraste-os na curva abaixo.",+ "needAdmin": "Só um administrador pode mudar as ventoinhas.",+ "systemControl": "Deixar o sistema controlar as ventoinhas",+ "systemControlHint": "Desativado: o LordOS as controla com o perfil abaixo.",+ "curveProfile": "Perfil de ventilação",+ "profiles.auto": "Sistema",+ "profiles.quiet": "Silencioso",+ "profiles.balanced": "Equilibrado",+ "profiles.performance": "Desempenho",+ "profiles.always": "Sempre ligada",+ "profiles.custom": "Personalizado",+ "curve": "Curva da ventoinha",+ "curveHint": "Cada degrau começa na sua temperatura e termina {hyst} °C abaixo (faixa laranja), para a ventoinha não ficar ligando e desligando.",+ "curveHintCustom": "Arraste um ponto para mudar a temperatura e a velocidade. Cada degrau termina {hyst} °C abaixo de onde começa (faixa laranja).",+ "addPoint": "Adicionar degrau",+ "removePoint": "Remover degrau",+ "resetCurve": "Restaurar",+ "boost": "Trabalho pesado",+ "boostHint": "Velocidade máxima por um tempo, por exemplo ao compilar. O perfil volta sozinho.",+ "force": "Ventoinhas na velocidade máxima",+ "forceOff": "Não",+ "force30": "Por 30 minutos",+ "force60": "Por 1 hora",+ "force120": "Por 2 horas",+ "forceOn": "Até eu desativar",+ "case": "Gabinete",+ "caseHint": "Ativa o que o gabinete acrescenta (as portas USB frontais e a placa de áudio). Vale depois de reiniciar.",+ "caseModel": "Modelo do gabinete",+ "caseNone": "Nenhum ou outro gabinete",+ "caseArgonV5": "Gabinete Argon ONE V5",+ "caseRestart": "Salvo. Reinicie o computador para usar as portas do gabinete.",+ "refresh": "Atualizar",+ "stopForce": "Voltar ao perfil",+ "force100": "Máxima por 30 min",+ "customize": "Personalizar…",+ "history": "Temperatura e ventoinha",+ "temperature": "Temperatura (°C)",+ "fanSpeed": "Ventoinha (%)",+ "step": "Degrau"+}diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.jsonindex 174f100..3090946 100644--- a/assets/locales/pt/errors.json+++ b/assets/locales/pt/errors.json@@ -530,5 +530,12 @@"wifi.rejected": "O serviço de Wi-Fi não aceitou a rede","wifi.saveFailed": "Não foi possível salvar a rede","wifi.selectFailed": "O serviço de Wi-Fi não conseguiu escolher a rede",- "wifi.startFailed": "Não foi possível iniciar o Wi-Fi em {name}"+ "wifi.startFailed": "Não foi possível iniciar o Wi-Fi em {name}",+ "fan.notAdmin": "Só um administrador pode mudar as ventoinhas",+ "fan.badRequest": "O serviço de ventoinhas recusou o pedido",+ "fan.badCurve": "Curva inválida: temperaturas de 30 a 90 °C subindo e velocidades que nunca diminuem",+ "fan.saveFailed": "Não foi possível salvar as configurações das ventoinhas",+ "fan.unavailable": "O serviço de ventoinhas não está em execução",+ "hw.notRaspberryPi5": "Isto só funciona em um Raspberry Pi 5",+ "hw.caseFailed": "Não foi possível salvar as configurações do gabinete"}diff --git a/assets/locales/pt/monitor.json b/assets/locales/pt/monitor.jsonindex 855cc0e..5e32d8b 100644--- a/assets/locales/pt/monitor.json+++ b/assets/locales/pt/monitor.json@@ -134,5 +134,6 @@"privacy.local": "Tudo é calculado neste computador e só enquanto o Monitor está aberto. Nenhum endereço IP sai do computador.","privacy.open": "Abrir Monitor","net.placeApps": "Apps",- "net.privacyShort": "País por IP com uma base local (DB-IP Lite, CC BY 4.0, db-ip.com): nenhum endereço sai do computador."+ "net.privacyShort": "País por IP com uma base local (DB-IP Lite, CC BY 4.0, db-ip.com): nenhum endereço sai do computador.",+ "tab.cooling": "Resfriamento"}diff --git a/assets/locales/pt/settings.json b/assets/locales/pt/settings.jsonindex 205b393..7fa0e89 100644--- a/assets/locales/pt/settings.json+++ b/assets/locales/pt/settings.json@@ -237,5 +237,9 @@"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"+ "keywords.defaultapps": "apps padrão navegador e-mail música vídeo imagens pdf editor de texto terminal abrir com",+ "section.cooling": "Resfriamento",+ "keywords.cooling": "ventoinha ventoinhas temperatura resfriamento calor ruído curva gabinete máxima fan cooling",+ "reduceMotion": "Reduzir movimento",+ "reduceMotionHint": "Para as animações decorativas, como a ventoinha girando em Resfriamento."}diff --git a/assets/locales/pt/status.json b/assets/locales/pt/status.jsonindex 109810c..4d094cf 100644--- a/assets/locales/pt/status.json+++ b/assets/locales/pt/status.json@@ -115,5 +115,6 @@},"wifi.connecting": "Conectando a {ssid}…","wifi.disconnected": "Desconectado",- "wifi.forgotten": "Rede esquecida"+ "wifi.forgotten": "Rede esquecida",+ "hw.caseSet": "Gabinete: {case}"}diff --git a/docs/PRIVACY.md b/docs/PRIVACY.mdindex 5bdf995..72fe49a 100644--- a/docs/PRIVACY.md+++ b/docs/PRIVACY.md@@ -233,7 +233,8 @@ sandbox_apply_helper(&cfg); /* SANDBOX_HELPER_DIR_FDS says the f(glibc falls back to `clone`, which can be filtered by flags).- **TSYNC**: the filter also reaches threads that already existed (VA-API, drivers). If seccompcan't be applied, the helper exits (`_exit(70)`): it **fails closed**. If Landlock is missing- (some Raspberry Pi kernels), it goes on with seccomp and warns.+ (Raspberry Pi's own kernel; the LordOS Pi image ships its own build with Landlock, see+ `RASPBERRY.md`, "The LordOS kernel"), it goes on with seccomp and warns.- **Files**: nothing except `ro_paths` and the folders that arrive as fds (`rw_dir_fds`: write,create files, folders and links, and delete files, **without truncating**).- **ioctl by class** (`allow_ioctl_classes`): only types `'d'` (DRM/VA-API), `'V'` (V4L2, Pi 5)diff --git a/docs/RASPBERRY.md b/docs/RASPBERRY.mdindex 95a2989..92de3b2 100644--- a/docs/RASPBERRY.md+++ b/docs/RASPBERRY.md@@ -10,6 +10,12 @@ This document gathers what's needed to build the image, write it, develop on the> board"). **Not verified yet:** anything with a monitor on HDMI (KMS modeset, GPU composition on> screen, hardware cursor, FPS), the desktop session, remote-desktop screenshots, and booting the> image that `build-img.sh` produced.+>+> **Update (2026-10-18, later):** the image now ships **the LordOS build of the Raspberry Pi kernel**+> (`6.18.57-lordos-rpi-2712`, Raspberry Pi's source and `bcm2712_defconfig` plus Landlock; see "The+> LordOS kernel"), **switch files** on the boot partition (`ssh`, `remote-desktop`, Wi-Fi in+> `lordos-user.txt`; see "Switch files") and a post-flash check (`verify-board`, see "After+> flashing"). Built on the board; it is verified by booting the reflashed card.## Models@@ -42,11 +48,15 @@ SD card or an NVMe, and the same image boots on the Pi 5 and the Pi 4.- **Debian 13 (trixie) arm64**, minbase, with the same LordOS packages as the ISO: PipeWire,wpa_supplicant, OpenVPN, Noto, foot, FeatherPad.-- **Kernel and firmware from the Raspberry Pi archive** (`archive.raspberrypi.com/debian`, suite- trixie), only these packages (`/etc/apt/preferences.d/raspberrypi`):- - `linux-image-rpi-2712`: the Pi 5 one, with 16K pages;- - `linux-image-rpi-v8`: the Pi 4/400/CM4 one, with 4K pages. The Pi 5 can also use it, with- `kernel=kernel8.img` in `config.txt`;+- **The LordOS build of the Raspberry Pi kernel** (see "The LordOS kernel"), when+ `tools/rpi/build-kernel.sh` has built it; otherwise Raspberry Pi's archive kernel, with a loud+ warning (it has no Landlock):+ - `linux-image-<version>-lordos-rpi-2712`: the Pi 5 one, with 16K pages (archive:+ `linux-image-rpi-2712`);+ - `linux-image-<version>-lordos-rpi-v8`: the Pi 4/400/CM4 one, with 4K pages (archive:+ `linux-image-rpi-v8`). The Pi 5 can also use it, with `kernel=kernel8.img` in `config.txt`.+- **Firmware from the Raspberry Pi archive** (`archive.raspberrypi.com/debian`, suite trixie), only+ these packages (`/etc/apt/preferences.d/raspberrypi`):- `raspi-firmware`: the boot files, device trees and overlays in `/boot/firmware`;- `firmware-brcm80211`: Wi-Fi and Bluetooth (CYW43455);- `rpi-eeprom` and `raspi-utils` (`vcgencmd`, `pinctrl`), if available.@@ -83,8 +93,64 @@ Researched as of October 2026 (confirm on the board):Its hooks copy the kernel to `/boot/firmware` under the name the firmware looks for(`kernel_2712.img`). If they don't, `build-img.sh` copies it by hand. **Chosen.**-With the pinning, `apt upgrade` on the installed system keeps bringing the kernel and firmware from-Raspberry Pi, and everything else from Debian.+With the pinning, `apt upgrade` on the installed system keeps bringing the firmware from Raspberry+Pi, and everything else from Debian. The kernel is LordOS's own build of it (next section).++### The LordOS kernel++Raspberry Pi's kernel leaves Landlock out (`# CONFIG_SECURITY_LANDLOCK is not set`, `CONFIG_LSM=""`,+so `/sys/kernel/security/lsm` is just `capability`). LordOS confines apps (`.lpk`) and its helpers+(`lord-doc`, `lord-media`, `lord-maild`) with Landlock (`server/src/sec/sandbox.c`, see+`PRIVACY.md`); without it `doc_evil.sh` fails 5 of 25 and `sandbox-test` is skipped. The tests stay+as they are: the fix is the kernel.++`tools/rpi/build-kernel.sh` builds it from **Raspberry Pi's own source and defconfig**, changing only+what LordOS needs:++```sh+# on the Pi (arm64 Debian 13), ~70–90 min per flavour on a Pi 5 with 4 cores+sudo apt-get install -y --no-install-recommends build-essential bc bison flex libssl-dev libelf-dev \+ libdw-dev dwarves cpio kmod rsync dpkg-dev debhelper git+tools/rpi/build-kernel.sh /var/tmp/lordos-kernel all # 2712 (Pi 5), v8 (Pi 4), or all+# → /var/tmp/lordos-kernel/out/linux-image-6.18.57-lordos-rpi-2712_6.18.57-1+lordos_arm64.deb, …+```++- **Source:** `github.com/raspberrypi/linux`, branch `rpi-6.18.y` (`RPI_KERNEL_BRANCH`;+ `RPI_KERNEL_REF=<commit>` pins one). The first build (2026-10-18) used commit `234188315037`,+ kernel **6.18.57**; the archive shipped 6.18.50 at the time. `out/SOURCE` records it.+- **Config:** `bcm2712_defconfig` (Pi 5, 16K pages) or `bcm2711_defconfig` (Pi 4, 4K pages), then+ `scripts/config` and `olddefconfig`. The whole diff against the defconfig (`out/config-*.diff`):++ ```diff+ -CONFIG_LOCALVERSION="-v8-16k"+ +CONFIG_LOCALVERSION="-lordos-rpi-2712"+ -# CONFIG_SECURITY_LANDLOCK is not set+ +CONFIG_SECURITY_LANDLOCK=y+ -CONFIG_LSM=""+ +CONFIG_LSM="landlock,lockdown,yama,integrity,bpf"+ ```++ `CONFIG_LSM` uses the usual Debian order; the kernel skips the ones it doesn't build (lockdown,+ Yama, IMA/EVM and the BPF LSM stay off, as Raspberry Pi has them), so the active list is+ **`capability,landlock`**. The image's `cmdline.txt` has the same `lsm=` list.+- **Already in the defconfig, checked by the script** so a future defconfig can't drop them:+ `SECCOMP_FILTER` (sandbox.c), cgroup v2 with `MEMCG`, `CGROUP_PIDS` and `CGROUP_SCHED` (per-app+ limits; `cgroup_enable=memory` is in `cmdline.txt` because Raspberry Pi turns memcg off at boot),+ and `BPF_SYSCALL`, `BPF_JIT`, `CGROUP_BPF` (lord-netperm's cgroup hooks). LordOS doesn't need user+ namespaces (`USER_NS` stays as Raspberry Pi has it, on) or the BPF LSM.+- **Packages:** `make bindeb-pkg`, version `6.18.57-1+lordos`, release `6.18.57-lordos-rpi-2712`+ (`-lordos-rpi-v8` for the Pi 4). The `-rpi-<flavour>` suffix is what `raspi-firmware`'s hook keys+ on, so it installs exactly like Raspberry Pi's: `kernel_2712.img`, initramfs, device trees and+ overlays in `/boot/firmware`. The script checks the package carries the device trees and+ overlays. Headers are built too (`linux-headers-*`), not put in the image.+- **Not replaced by the archive.** `build-img.sh` installs the LordOS `.debs` from `KERNEL_DEBS`+ (default `/var/tmp/lordos-kernel/out`) instead of `linux-image-rpi-<flavour>`, and writes+ `/etc/apt/preferences.d/lordos-kernel` with priority -1 for Raspberry Pi's kernel packages of+ that flavour (`linux-image-rpi-2712`, `linux-image-*+rpt-rpi-2712` and the headers; checked with+ `apt-cache policy`: no candidate). Otherwise a newer `+rpt` kernel would win the hook's "newest+ `vmlinuz-*-rpi-2712`" and boot without Landlock. Kernel updates come as new LordOS packages.+- **Per flavour:** if only the 2712 kernel was built, the Pi 4 kernel comes from the archive (with+ a warning, and without the pin).### Packages to build it@@ -131,7 +197,8 @@ Variables:| Variable | What for ||---|---|-| `RPI_SSH=1` | adds `openssh-server` (for development) |+| `RPI_SSH=1` | SSH server on from the start (for development); without it `openssh-server` ships off and the `ssh` switch file turns it on |+| `KERNEL_DEBS` | folder with the LordOS kernel packages (`build-kernel.sh`), `/var/tmp/lordos-kernel/out` by default || `IMG_EXTRA_MB` | free space in the image, 512 by default || `MIRROR`, `RPI_MIRROR` | Debian and Raspberry Pi mirrors || `RPI_KEY_FPR`, `RPI_KEY_NOCHECK=1` | the Raspberry Pi key |@@ -154,9 +221,11 @@ Estimate: on x86-64 with qemu, 30–60 minutes the first time. Natively on the P- **Raspberry Pi Imager:** "Choose OS" → "Use custom" → the `.img.xz`, and then the card or theNVMe.- - Imager's OS customization (user, Wi-Fi, SSH) is designed for Raspberry Pi OS. If it leaves a- `userconf.txt` on the boot partition, LordOS uses it (see below).- - The rest (Wi-Fi, SSH, keyboard) isn't applied.+ - Skip Imager's OS customization (it's designed for Raspberry Pi OS; newer versions write+ cloud-init files that LordOS doesn't read). If it leaves a `userconf.txt` on the boot+ partition, LordOS uses it (see below).+ - Instead, add the switch files and `lordos-user.txt` to the `bootfs` partition (see "Switch+ files"); `out/FLASHING.txt` next to the image has the exact steps for macOS.- **dd** (Linux and other Unix-like systems):```shshasum -a 256 -c lordos-<version>-rpi5-arm64.img.xz.sha256@@ -201,9 +270,34 @@ two things.- In the meantime, **don't turn on remote desktop** and don't leave the board exposed on thenetwork.+3. **Switch files** (next section), on every boot.+Pending: a "create user" step of our own on the login screen, so setup mode isn't needed (seeROADMAP, M8).+### Switch files++Like Raspberry Pi OS's `ssh` file: files dropped on the `bootfs` partition (FAT, editable from any+computer) before booting. `firstboot` applies each one, logs it (`journalctl -u+lordos-rpi-firstboot`) and deletes it (overwritten with zeros first, since they can hold a password).+A name with `.txt` (as some editors save it) works the same.++| File | Contents | What it does |+|---|---|---|+| `ssh` | empty | Turns the SSH server on (`systemctl enable ssh`, started right away) and keeps it on. The image ships `openssh-server` off; each board creates its own host keys. Logging in needs an account with a password: root is locked and the setup user has none |+| `remote-desktop` | empty, or `port=5673` and/or `allow=all\|group` | Turns LordOS remote desktop on (`https://<board IP>:5673`, `REMOTE.md`), writing the same `/etc/lordos/remote/config` (`enabled=1`, `port=`, `allow=`) that Settings → Sharing's `remote-enable`/`remote-config` write; lord-sessiond reads it when `lordos.service` starts. It still asks for a user and password: while there's no account with a password (setup mode) the file is **kept** and applied on a later boot. `port` must be 1024–65535 (5673 by default); `allow=group` limits it to the `lordos-remote` group |+| `lordos-user.txt` | from `lordos-user.txt.example` | The first-boot user (above), read only on the first boot. Optional Wi-Fi: `wifi_ssid=`, `wifi_password=` (8–128 characters; empty for an open network) and `wifi_country=` (two letters) |+| `userconf.txt` | `user:hash` | Raspberry Pi OS / Imager's user file, first boot only |++**Wi-Fi at first boot.** The image's network stack is **lord-netd** (no NetworkManager, no+systemd-networkd): at boot it brings up every free physical interface with its own DHCP client, and+on Wi-Fi interfaces it starts `wpa_supplicant` and loads the saved networks. `firstboot` saves the+network from `lordos-user.txt` the same way Settings → Network does+(`/etc/lordos/net/wifi/<SSID in hex>.json`, and `.key` with mode 0600), before lord-netd starts, so+the board joins it on the first boot. `wifi_country` adds `cfg80211.ieee80211_regdom=<XX>` to+`cmdline.txt` (the 5 GHz channels of that country, from the second boot; until then the world+domain). lord-netd skips interfaces NetworkManager manages, which only matters on Raspberry Pi OS.+Options in `cmdline.txt` (a single line), as on the ISO:| Option | What it does |@@ -212,6 +306,32 @@ Options in `cmdline.txt` (a single line), as on the ISO:| `lordos.lang=es` / `pt` | first-boot language (English by default, like the ISO) || `video=HDMI-A-1:1920x1080@60` | pins the mode, for example on a 4K monitor (on the CPU, 4K is heavy: see below) |+### After flashing++`tools/rpi/verify-board.sh` (in the image as `/usr/lib/lordos/rpi/verify-board`) checks a freshly+booted board and prints a PASS/FAIL table. It only reads `/sys`, `/proc`, the kernel log and the+configs; it changes nothing.++```sh+sudo /usr/lib/lordos/rpi/verify-board # system checks+sudo /usr/lib/lordos/rpi/verify-board --repo ~/LordOS # plus make -C server test-full and doc_evil.sh+```++| Check | PASS when |+|---|---|+| kernel | `uname -r` is a `-lordos-rpi-*` kernel; page size 16K on the Pi 5 (4K with `-rpi-v8`) |+| Landlock | `/sys/kernel/security/lsm` lists `landlock`; the kernel log says `landlock: Up and running`; the kernel config has `SECURITY_LANDLOCK`, `SECCOMP_FILTER`, `CGROUP_BPF`, `BPF_SYSCALL`, `MEMCG` |+| seccomp, cgroups | seccomp available; the cgroup v2 `memory` controller is on (`cgroup_enable=memory`) |+| first boot | the root partition has grown; no switch file left on `bootfs` (WARN for a `remote-desktop` still waiting for an account); not in setup mode |+| display, GPU | a `connected` KMS output with its mode (WARN with no monitor); `eglinfo -p gbm` shows V3D; the session log shows `GPU composition` |+| fan, temperature | a fan hwmon (`pwmfan`, rpm and PWM; `lord-fand` active if it's installed); SoC < 75 °C; `throttled=0x0` |+| remote desktop | port 5673 (or the configured one) listens **only** when `/etc/lordos/remote/config` has `enabled=1` |+| services | `lordos.service` active; SSH shown as on or off |+| `--repo` | `make -C server test-full` passes; `doc_evil.sh` N/N (25/25 with the archive tools installed); the three `sandbox-test` runs ok |++`--repo` needs the tree and the build packages ("Developing on the board"); it builds as the tree's+owner.+## Display and GPU on the Pi 5### Two DRM devices@@ -349,7 +469,8 @@ There are two possible systems on the board:1. **SSH:**- with Raspberry Pi OS, enable it in Imager;- - with LordOS, build with `RPI_SSH=1` and use the account created at first boot;+ - with LordOS, put an empty `ssh` file on the boot partition (or build with `RPI_SSH=1`) and use+ the account created at first boot;- `ssh user@<ip>`; the IP shows up on the login screen or with `ip -4 addr`.2. **Packages for compiling** (the same as in `VM-SETUP.md` plus Mesa):```sh@@ -403,7 +524,7 @@ Each item, with a screenshot or the pasted output, in this document.| 11 | Temperature | `vcgencmd measure_temp`, `vcgencmd get_throttled`, LordOS Monitor (`cpu_thermal` and the fan) | <75 °C with the Active Cooler under load; `throttled=0x0` || 12 | NEON | `server/build/canvas-test` | "NEON matches C"; NEON faster than C || 13 | Headless tests | `make -C server test` and each `build/*-test` | all pass, as on x86 (WASM: the full wg-2.0 suite) |-| 14 | App isolation | open a `.lpk`; `sandbox[...]:` in the log; `cat /sys/kernel/security/lsm` | seccomp=1. **The Raspberry Pi kernel has no Landlock** (`# CONFIG_SECURITY_LANDLOCK is not set` in 6.18.50+rpt): seccomp only |+| 14 | App isolation | open a `.lpk`; `sandbox[...]:` in the log; `cat /sys/kernel/security/lsm`; `make -C server test-full` | `capability,landlock`; Landlock and seccomp=1; `doc_evil.sh` 25/25 and `sandbox-test` ok. Needs the LordOS kernel: Raspberry Pi's has no Landlock (`6.18.50+rpt`: seccomp only) || 15 | Remote desktop | Settings → Sharing, `https://<ip>:5673` from the development machine | visible and controllable; screenshots for this document || 16 | Network and sound | Wi-Fi (brcmfmac), Ethernet, HDMI audio via PipeWire | IP from our own DHCP; `wpctl status` shows HDMI || 17 | Pi 4 | the same image | boots with `kernel8.img`; note what fails |@@ -443,9 +564,9 @@ Notes for the image:- Raspberry Pi OS boots with `cgroup_disable=memory`; the image's `cmdline.txt` already has`cgroup_enable=memory` (per-app memory limits need it).-- `lsm=landlock,…` in the image's `cmdline.txt` does nothing on this kernel: Landlock isn't compiled- in. App and helper isolation on the Pi is seccomp + cgroups + no-new-privs only, until LordOS ships- a kernel with `CONFIG_SECURITY_LANDLOCK=y`.+- `lsm=landlock,…` in the image's `cmdline.txt` does nothing on Raspberry Pi's kernel: Landlock isn't+ compiled in, and isolation there is seccomp + cgroups + no-new-privs only. **Fixed:** the image now+ ships the LordOS kernel with `CONFIG_SECURITY_LANDLOCK=y` ("The LordOS kernel").- The image takes Mesa (25.0.7) and FFmpeg (7.1.5) from Debian. Debian's FFmpeg has no V4L2-requestdecoding, so the hardware HEVC seen above needs the Raspberry Pi FFmpeg pinned (option 1 in"Video").diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 101d523..a65f1f5 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -249,6 +249,10 @@ our own installer, and network, VPN, sound and clipboard with our own interface.- the partition grows by itself;- first boot with `lordos-user.txt`/`userconf.txt` (login screen) or setupmode.+ - [x] LordOS build of the Raspberry Pi kernel with Landlock (`tools/rpi/build-kernel.sh`,+ `6.18.57-lordos-rpi-2712`), pinned over the archive kernel.+ - [x] Switch files on the boot partition: `ssh`, `remote-desktop`, Wi-Fi in `lordos-user.txt`;+ `tools/rpi/verify-board.sh` after flashing.- [ ] Run `build-img.sh` and test on the 16 GB Pi 5 (test list in `RASPBERRY.md`,with screenshots through the remote desktop).- [ ] Hardware video on the Pi 5 (HEVC via V4L2 stateless; H.264 in software) indiff --git a/sdk/cooling.jsx b/sdk/cooling.jsxnew file mode 100644index 0000000..e36ab2f--- /dev/null+++ b/sdk/cooling.jsx@@ -0,0 +1,353 @@+// cooling.jsx — the session side of lord-fand (docs/FANS.md), shared by Settings → Cooling and+// Monitor → Cooling:+//+// useFan() status of lord-fand ({ temp, fans, profile, curve, step, … } or null), polled+// every 2 s only while something on screen uses it, plus a short history+// fanHistory store with the last FAN_HISTORY samples { t, temp, pct, rpm }+// coolingVariant(s) 'argon' | 'cooler' | 'pc' | 'none': which illustration fits the hardware+// CoolingArt our own drawing of that hardware; the fan spins with the real duty and the+// heatsink warms from blue to orange with the temperature+// FanCurveChart the profile's steps (°C → %), the hysteresis band, the live point; the steps+// can be dragged when `onChange` is given+//+// The illustrations are drawn here with views (no product photos or renders). The animation runs only+// while the fan turns and the window is visible, at 20 frames per second, and never with+// Appearance → Reduce motion.+import { createElement as h, useEffect, useRef, useState } from 'react';+import { View, Text, addListener } from '@lordos/runtime';+import { createStore, useStore } from './store.js';+import { settings } from './settings.js';+import { useTheme } from './theme.js';+import { t, formatNumber } from './i18n.js';+import { windows } from './windows.js';+import { useAppWindow } from './components.jsx';++const has = () => typeof lord !== 'undefined' && lord.fan && typeof lord.fan.status === 'function';+const call = (fn, fallback) => { try { return fn(); } catch (e) { return fallback; } };++export const FAN_HISTORY = 90; // 3 minutes at one sample every 2 s+export const fanStatus = createStore(undefined); // undefined: not asked yet; null: no service+export const fanHistory = createStore([]);+export const fanCase = createStore(undefined);++let users = 0;+let timer = null;+function poll() {+ const s = has() ? call(() => lord.fan.status(), null) : null;+ fanStatus.set(() => s);+ if (fanCase.get() === undefined) fanCase.set(() => (has() ? call(() => lord.fan.caseConfig(), null) : null));+ if (s && s.temp != null) {+ const f = (s.fans || [])[0];+ const sample = { t: Date.now(), temp: s.temp, pct: f && f.pct >= 0 ? f.pct : 0, rpm: f && f.rpm >= 0 ? f.rpm : -1 };+ fanHistory.set((l) => (l.length >= FAN_HISTORY ? [...l.slice(l.length - FAN_HISTORY + 1), sample] : [...l, sample]));+ }+ timer = users > 0 ? setTimeout(poll, 2000) : null;+}+// Ask again now (after a change from Settings).+export function refreshFan() { if (timer) clearTimeout(timer); poll(); }++export function useFan() {+ useEffect(() => {+ users++;+ if (!timer) poll();+ return () => { users--; };+ }, []);+ return useStore(fanStatus);+}++// ---- requests: '' when done, or an error code (errors.<code>) ----+const ask = (fn) => { const r = has() ? call(fn, 'fan.badRequest') : 'fan.unavailable'; refreshFan(); return r; };+export const fanControl = {+ setProfile: (p) => ask(() => lord.fan.setProfile(p)),+ setCurve: (pts) => ask(() => lord.fan.setCurve(pts)),+ force: (v) => ask(() => lord.fan.force(v)),+};++export function coolingVariant(s, caseId = fanCase.get()) {+ if (!s || !s.fans || !s.fans.length) return 'none';+ if (s.fans.some((f) => f.kind === 'board')) return caseId === 'argon-one-v5' ? 'argon' : 'cooler';+ return 'pc';+}++// ---- colors ----++const mix = (a, b, k) => a.map((x, i) => Math.round(x + (b[i] - x) * k));+// cool blue up to 40 °C, amber at 65 °C, orange-red from 80 °C+export function heatColor(temp, alpha = 1) {+ const c = temp == null ? [90, 160, 255]+ : temp <= 40 ? [90, 160, 255]+ : temp <= 65 ? mix([90, 160, 255], [255, 180, 64], (temp - 40) / 25)+ : mix([255, 180, 64], [255, 90, 54], Math.min(1, (temp - 65) / 15));+ return `rgba(${c[0]},${c[1]},${c[2]},${alpha})`;+}++// ---- the spinning fan ----++// Rotation that follows the duty: up to 1.5 turns per second at 100 %, eased; stops (no timer) at+// 0 %, while the window is minimized and with Reduce motion.+function useSpin(pct) {+ const { id } = useAppWindow() || {};+ const hidden = useStore(windows, (ws) => !!ws.find((w) => w.id === id)?.minimized);+ const effects = useStore(settings, (s) => !s.reduceMotion);+ const [angle, setAngle] = useState(0);+ const st = useRef({ v: 0, a: 0 });+ const target = effects && !hidden ? Math.max(0, Math.min(100, pct || 0)) / 100 * 1.5 : 0;+ useEffect(() => {+ const s = st.current;+ if (!effects || hidden || (target === 0 && s.v < 0.01)) { s.v = target; return undefined; }+ const FPS = 20;+ let tm = null;+ const step = () => {+ s.v += (target - s.v) * 0.12;+ if (target === 0 && s.v < 0.01) { s.v = 0; return; }+ s.a = (s.a + s.v * 360 / FPS) % 360;+ setAngle(s.a);+ tm = setTimeout(step, 1000 / FPS);+ };+ tm = setTimeout(step, 1000 / FPS);+ return () => clearTimeout(tm);+ }, [target, effects, hidden]);+ return angle;+}++function Fan({ size, pct, frame, blade, hub, angle }) {+ const b = Math.round(size * 0.42), bh = Math.round(size * 0.2);+ return h(View, { style: { width: size, height: size, borderRadius: size / 2, backgroundColor: frame, alignItems: 'center', justifyContent: 'center' } },+ h(View, { style: { position: 'absolute', left: 0, top: 0, width: size, height: size, transform: `rotate(${angle}deg)` } },+ [0, 1, 2, 3, 4].map((i) => h(View, { key: i, style: { position: 'absolute', left: 0, top: 0, width: size, height: size, transform: `rotate(${i * 72}deg)` } },+ h(View, { style: { position: 'absolute', left: size / 2 - 1, top: size / 2 - bh, width: b, height: bh, borderTopRightRadius: bh, borderBottomRightRadius: bh / 3,+ borderTopLeftRadius: 2, backgroundColor: blade } })))),+ h(View, { style: { width: size * 0.26, height: size * 0.26, borderRadius: size * 0.13, backgroundColor: hub, boxShadow: '0 1px 2px rgba(0,0,0,0.35)' } }));+}++// Fins: n thin bars spread over the box (len = their length, span = the box across them), tinted by+// the temperature glow.+function Fins({ n, w, len, span, color, glow, vertical }) {+ const gap = Math.max(1, (span - n * w) / Math.max(1, n - 1));+ return h(View, { style: { flexDirection: vertical ? 'row' : 'column', gap } },+ Array.from({ length: n }, (_, i) => h(View, { key: i, style: { width: vertical ? w : len, height: vertical ? len : w, borderRadius: 1.5,+ background: `linear-gradient(${vertical ? 180 : 90}deg, ${color}, ${glow})` } })));+}++// ---- illustrations (our own, stylized) ----++function palette(dark) {+ return dark+ ? { stage: 'linear-gradient(160deg, #23252c, #17181d)', alu: 'linear-gradient(170deg, #6b7079, #3b3f47)', aluEdge: '#2a2d33', fin: '#8b9099',+ slot: '#1b1d22', pcb: 'linear-gradient(160deg, #1f5a3d, #123826)', port: '#a7acb5', text: '#c9ccd2', shadow: 'rgba(0,0,0,0.5)', frame: '#2c2f36',+ blade: '#a9b0bb', hub: '#d9dde3', tower: 'linear-gradient(170deg, #34373e, #1f2126)', glass: 'rgba(120,140,170,0.10)' }+ : { stage: 'linear-gradient(160deg, #eef1f6, #dde2ea)', alu: 'linear-gradient(170deg, #e4e7ec, #aab0ba)', aluEdge: '#8d939d', fin: '#c3c8d0',+ slot: '#3a3d44', pcb: 'linear-gradient(160deg, #2f7a54, #1d5a3c)', port: '#7d838d', text: '#4a4f58', shadow: 'rgba(30,40,60,0.28)', frame: '#5b616b',+ blade: '#eef1f5', hub: '#ffffff', tower: 'linear-gradient(170deg, #50545c, #33363c)', glass: 'rgba(150,180,220,0.18)' };+}++function ArgonArt({ p, pct, temp, angle, W, H }) {+ const cw = Math.round(W * 0.78), ch = Math.round(H * 0.6), x = (W - cw) / 2, y = Math.round(H * 0.16);+ const glow = heatColor(temp, 0.55);+ return h(View, { style: { position: 'absolute', left: x, top: y, width: cw, height: ch } },+ // shadow and body: aluminium top over a darker base+ h(View, { style: { position: 'absolute', left: 6, right: 6, top: ch - 8, height: 16, borderRadius: 10, backgroundColor: p.shadow } }),+ h(View, { style: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, borderRadius: 14, background: p.alu, border: `1px solid ${p.aluEdge}`,+ boxShadow: `0 10px 24px ${p.shadow}`, overflow: 'hidden' } },+ // fins across the top, warming with the temperature+ h(View, { style: { position: 'absolute', left: 18, top: 16, width: cw * 0.52, height: ch * 0.62, justifyContent: 'space-between' } },+ h(Fins, { n: 7, w: 3, len: cw * 0.52, span: ch * 0.62, color: p.fin, glow, vertical: false })),+ // round blower window with the fan+ h(View, { style: { position: 'absolute', right: 22, top: (ch - ch * 0.62) / 2 - 4, width: ch * 0.62, height: ch * 0.62, borderRadius: ch * 0.31,+ backgroundColor: p.slot, alignItems: 'center', justifyContent: 'center', border: `2px solid ${p.aluEdge}` } },+ h(Fan, { size: ch * 0.54, pct, frame: p.slot, blade: p.blade, hub: p.hub, angle })),+ // front edge: two USB, the audio jacks and a light+ h(View, { style: { position: 'absolute', left: 18, bottom: 9, flexDirection: 'row', alignItems: 'center', gap: 7 } },+ h(View, { style: { width: 18, height: 7, borderRadius: 1.5, backgroundColor: p.slot, border: `1px solid ${p.port}` } }),+ h(View, { style: { width: 18, height: 7, borderRadius: 1.5, backgroundColor: p.slot, border: `1px solid ${p.port}` } }),+ h(View, { style: { width: 7, height: 7, borderRadius: 3.5, backgroundColor: p.slot, border: `1px solid ${p.port}` } }),+ h(View, { style: { width: 7, height: 7, borderRadius: 3.5, backgroundColor: p.slot, border: `1px solid ${p.port}` } }),+ h(View, { style: { width: 4, height: 4, borderRadius: 2, marginLeft: 6, backgroundColor: pct > 0 ? '#30d158' : p.port } }))));+}++function CoolerArt({ p, pct, temp, angle, W, H }) {+ const bw = Math.round(W * 0.66), bh = Math.round(H * 0.68), x = (W - bw) / 2, y = Math.round(H * 0.14);+ const glow = heatColor(temp, 0.6);+ const hs = Math.round(bh * 0.66);+ return h(View, { style: { position: 'absolute', left: x, top: y, width: bw, height: bh } },+ h(View, { style: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, borderRadius: 10, background: p.pcb, boxShadow: `0 10px 22px ${p.shadow}` } },+ // header pins along the top edge+ h(View, { style: { position: 'absolute', left: 14, top: 7, flexDirection: 'row', gap: 3 } },+ Array.from({ length: 16 }, (_, i) => h(View, { key: i, style: { width: 4, height: 9, borderRadius: 1, backgroundColor: '#d6c27a', opacity: 0.85 } }))),+ // ports on the right edge+ h(View, { style: { position: 'absolute', right: -6, top: 18, gap: 6 } },+ [0, 1, 2].map((i) => h(View, { key: i, style: { width: 20, height: i === 2 ? 22 : 16, borderRadius: 2, background: 'linear-gradient(90deg, #c9cdd3, #8e939b)' } }))),+ // mounting holes+ ...[[8, bh - 16], [bw - 30, bh - 16]].map(([l, t2], i) => h(View, { key: `h${i}`, style: { position: 'absolute', left: l, top: t2, width: 8, height: 8, borderRadius: 4, backgroundColor: 'rgba(0,0,0,0.35)' } })),+ // heatsink with the fan on top+ h(View, { style: { position: 'absolute', left: Math.round(bw * 0.2), top: Math.round((bh - hs) / 2) + 4, width: Math.round(hs * 1.25), height: hs, borderRadius: 8,+ background: p.alu, border: `1px solid ${p.aluEdge}`, boxShadow: `0 6px 14px ${p.shadow}`, alignItems: 'center', justifyContent: 'center' } },+ h(View, { style: { position: 'absolute', left: 6, right: 6, top: 6, bottom: 6, flexDirection: 'row', justifyContent: 'space-between' } },+ h(Fins, { n: 9, w: 3, len: hs - 12, span: hs * 1.25 - 12, color: p.fin, glow, vertical: true })),+ h(View, { style: { width: hs * 0.8, height: hs * 0.8, borderRadius: hs * 0.4, backgroundColor: p.frame, alignItems: 'center', justifyContent: 'center', border: `2px solid ${p.aluEdge}` } },+ h(Fan, { size: hs * 0.72, pct, frame: p.frame, blade: p.blade, hub: p.hub, angle })))));+}++function PcArt({ p, pct, temp, angle, W, H }) {+ const tw = Math.round(H * 0.82), th = Math.round(H * 0.82), x = (W - tw) / 2, y = Math.round(H * 0.08);+ const glow = heatColor(temp, 0.6);+ return h(View, { style: { position: 'absolute', left: x, top: y, width: tw, height: th } },+ h(View, { style: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, borderRadius: 12, background: p.tower, boxShadow: `0 10px 24px ${p.shadow}`, border: `1px solid ${p.aluEdge}` } },+ // glass side panel with the board inside+ h(View, { style: { position: 'absolute', left: 10, right: 10, top: 10, bottom: 10, borderRadius: 8, backgroundColor: p.glass, border: `1px solid rgba(255,255,255,0.12)` } },+ h(View, { style: { position: 'absolute', left: 14, top: 12, width: tw * 0.52, height: th * 0.62, borderRadius: 4, background: 'linear-gradient(160deg, #2b3340, #1b2029)' } },+ // CPU tower cooler+ h(View, { style: { position: 'absolute', left: tw * 0.08, top: th * 0.08, width: tw * 0.3, height: th * 0.3, borderRadius: 4, background: p.alu, alignItems: 'center', justifyContent: 'center' } },+ h(View, { style: { position: 'absolute', left: 4, right: 4, top: 4, bottom: 4, flexDirection: 'row', justifyContent: 'space-between' } },+ h(Fins, { n: 7, w: 2, len: th * 0.3 - 8, span: tw * 0.3 - 8, color: p.fin, glow, vertical: true })),+ h(Fan, { size: tw * 0.24, pct, frame: p.frame, blade: p.blade, hub: p.hub, angle })),+ // memory and a card+ h(View, { style: { position: 'absolute', left: tw * 0.41, top: th * 0.08, width: 5, height: th * 0.3, borderRadius: 1, backgroundColor: '#5e6878' } }),+ h(View, { style: { position: 'absolute', left: tw * 0.43, top: th * 0.08, width: 5, height: th * 0.3, borderRadius: 1, backgroundColor: '#5e6878' } }),+ h(View, { style: { position: 'absolute', left: tw * 0.06, top: th * 0.46, width: tw * 0.4, height: 9, borderRadius: 2, backgroundColor: '#3c4554' } })),+ // rear and front case fans+ h(View, { style: { position: 'absolute', right: 10, top: 14, width: tw * 0.24, height: tw * 0.24, borderRadius: 4, backgroundColor: p.frame, alignItems: 'center', justifyContent: 'center' } },+ h(Fan, { size: tw * 0.22, pct, frame: p.frame, blade: p.blade, hub: p.hub, angle: -angle })),+ h(View, { style: { position: 'absolute', right: 10, bottom: 14, width: tw * 0.24, height: tw * 0.24, borderRadius: 4, backgroundColor: p.frame, alignItems: 'center', justifyContent: 'center' } },+ h(Fan, { size: tw * 0.22, pct, frame: p.frame, blade: p.blade, hub: p.hub, angle: angle * 0.9 })))));+}++function PassiveArt({ p, temp, W, H }) {+ const cw = Math.round(W * 0.34), x = (W - cw) / 2, y = Math.round(H * 0.3);+ const glow = heatColor(temp, 0.45);+ return h(View, { style: { position: 'absolute', left: 0, top: 0, width: W, height: H } },+ // calm air lines+ ...[0, 1, 2].map((i) => h(View, { key: `a${i}`, style: { position: 'absolute', left: x - 30 + i * 18, top: y - 34 - i * 6, width: cw * 0.7, height: 3, borderRadius: 2,+ backgroundColor: p.fin, opacity: 0.35 - i * 0.08 } })),+ h(View, { style: { position: 'absolute', left: x, top: y, width: cw, height: H * 0.42, borderRadius: 8, background: p.alu, border: `1px solid ${p.aluEdge}`,+ boxShadow: `0 10px 22px ${p.shadow}`, paddingHorizontal: 8, paddingVertical: 8, flexDirection: 'row', justifyContent: 'space-between' } },+ h(Fins, { n: 8, w: 3, len: H * 0.42 - 16, span: cw - 16, color: p.fin, glow, vertical: true })),+ h(View, { style: { position: 'absolute', left: x - 12, top: y + H * 0.42 - 2, width: cw + 24, height: 10, borderRadius: 3, background: p.pcb } }));+}++// The illustration in a stage of the given size. variant: coolingVariant(status).+export function CoolingArt({ variant, pct = 0, temp = null, width = 320, height = 168 }) {+ const th = useTheme();+ const p = palette(th.mode === 'dark');+ const angle = useSpin(variant === 'none' ? 0 : pct);+ const W = width, H = height;+ const props = { p, pct, temp, angle, W, H };+ const Art = variant === 'argon' ? ArgonArt : variant === 'cooler' ? CoolerArt : variant === 'pc' ? PcArt : PassiveArt;+ return h(View, { style: { width: W, height: H, borderRadius: 14, background: p.stage, overflow: 'hidden', direction: 'ltr' } },+ h(View, { style: { position: 'absolute', left: W * 0.15, right: W * 0.15, top: H * 0.1, bottom: H * 0.1, borderRadius: H, backgroundColor: heatColor(temp, th.mode === 'dark' ? 0.08 : 0.1) } }),+ h(Art, props));+}++// ---- the curve chart ----++const TMIN = 30, TMAX = 90;++function useBoxWidth(ref, fallback) {+ const [w, setW] = useState(fallback);+ useEffect(() => {+ const m = () => {+ const n = ref.current;+ if (!n) return;+ const x = Math.round(lord.getLayout(n.id)[2]);+ if (x > 0) setW((o) => (Math.abs(x - o) > 1 ? x : o));+ };+ m();+ const id = setTimeout(m, 60);+ return () => clearTimeout(id);+ });+ return w;+}++// curve: [[°C, %], …]; floor: % below the first step; step: active step (-1 below the first);+// temp/pct: the live point; onChange(points) makes the steps draggable (custom profile).+export function FanCurveChart({ curve = [], floor = 0, hyst = 3, step = -1, temp = null, pct = null, height = 180, onChange }) {+ const th = useTheme();+ const dark = th.mode === 'dark';+ const box = useRef(null);+ const W = useBoxWidth(box, 480);+ const L = 34, R = 10, T = 10, B = 22;+ const pw = Math.max(40, W - L - R), ph = height - T - B;+ const X = (c) => L + ((Math.max(TMIN, Math.min(TMAX, c)) - TMIN) / (TMAX - TMIN)) * pw;+ const Y = (v) => T + (1 - Math.max(0, Math.min(100, v)) / 100) * ph;+ const [drag, setDrag] = useState(null); // { i, pts } while dragging+ const st = useRef(null);+ const pts = drag ? drag.pts : curve;+ useEffect(() => {+ if (!onChange) return undefined;+ const offMove = addListener('pointermove', (e) => {+ const d = st.current;+ if (!d) return;+ const n = d.start.map((q) => [...q]);+ const i = d.i;+ const lo = i > 0 ? n[i - 1][0] + 1 : TMIN, hi = i < n.length - 1 ? n[i + 1][0] - 1 : TMAX;+ const plo = i > 0 ? n[i - 1][1] : 0, phi = i < n.length - 1 ? n[i + 1][1] : 100;+ n[i][0] = Math.max(lo, Math.min(hi, Math.round(d.start[i][0] + (e.x - d.x) * (TMAX - TMIN) / pw)));+ n[i][1] = Math.max(plo, Math.min(phi, Math.round((d.start[i][1] - (e.y - d.y) * 100 / ph) / 5) * 5));+ d.pts = n;+ setDrag({ i, pts: n });+ });+ const offUp = addListener('pointerup', () => {+ const d = st.current;+ st.current = null;+ if (!d) return;+ setDrag(null);+ if (d.pts && JSON.stringify(d.pts) !== JSON.stringify(d.start)) onChange(d.pts);+ });+ return () => { offMove(); offUp(); };+ }, [onChange, pw, ph]);++ const accent = th.accent;+ const grid = th.separator;+ const kids = [];+ // grid and labels+ for (const v of [0, 25, 50, 75, 100]) {+ kids.push(h(View, { key: `gy${v}`, style: { position: 'absolute', left: L, width: pw, top: Y(v), height: 1, backgroundColor: grid, opacity: v === 0 ? 1 : 0.6 } }));+ kids.push(h(Text, { key: `ly${v}`, style: { position: 'absolute', left: 0, width: L - 6, top: Y(v) - 7, fontSize: 10, color: th.textDim, textAlign: 'right' } }, `${v}%`));+ }+ for (let c = 30; c <= 90; c += 10) {+ kids.push(h(View, { key: `gx${c}`, style: { position: 'absolute', top: T, height: ph, left: X(c), width: 1, backgroundColor: grid, opacity: 0.45 } }));+ kids.push(h(Text, { key: `lx${c}`, style: { position: 'absolute', top: T + ph + 5, left: X(c) - 16, width: 32, fontSize: 10, color: th.textDim, textAlign: 'center' } }, `${c}°`));+ }+ // the steps: filled area and the line+ const segs = [];+ if (pts.length) segs.push([TMIN, pts[0][0], floor, -1]);+ pts.forEach((q, i) => segs.push([q[0], i + 1 < pts.length ? pts[i + 1][0] : TMAX, q[1], i]));+ segs.forEach(([a, b, v, i]) => {+ const on = i === step;+ kids.push(h(View, { key: `f${i}`, style: { position: 'absolute', left: X(a), width: Math.max(0, X(b) - X(a)), top: Y(v), height: Math.max(0, Y(0) - Y(v)),+ backgroundColor: accent, opacity: on ? 0.22 : 0.1 } }));+ kids.push(h(View, { key: `s${i}`, style: { position: 'absolute', left: X(a), width: Math.max(2, X(b) - X(a)), top: Y(v) - 1, height: 2.5, borderRadius: 1, backgroundColor: accent } }));+ });+ for (let i = 0; i < segs.length - 1; i++) {+ const v0 = segs[i][2], v1 = segs[i + 1][2], x = X(segs[i + 1][0]);+ kids.push(h(View, { key: `v${i}`, style: { position: 'absolute', left: x - 1, width: 2.5, top: Y(Math.max(v0, v1)), height: Math.abs(Y(v0) - Y(v1)) + 1, backgroundColor: accent } }));+ }+ // hysteresis bands: a step is left only hyst °C below it+ pts.forEach((q, i) => {+ kids.push(h(View, { key: `hy${i}`, style: { position: 'absolute', left: X(q[0] - hyst), width: X(q[0]) - X(q[0] - hyst), top: T, height: ph,+ backgroundColor: '#ff9f0a', opacity: i === step ? 0.16 : 0.06 } }));+ });+ // step handles+ pts.forEach((q, i) => {+ const r = onChange ? 7 : 5;+ kids.push(h(View, { key: `p${i}`,+ onMouseDown: onChange ? (e) => { st.current = { i, x: e.x, y: e.y, start: pts.map((z) => [...z]), pts: null }; } : undefined,+ style: { position: 'absolute', left: X(q[0]) - r, top: Y(q[1]) - r, width: r * 2, height: r * 2, borderRadius: r, cursor: onChange ? 'grab' : 'default',+ backgroundColor: i === step ? accent : (dark ? '#1c1d22' : '#ffffff'), border: `2px solid ${accent}` } }));+ if (drag && drag.i === i) {+ kids.push(h(Text, { key: `dl${i}`, style: { position: 'absolute', left: X(q[0]) - 40, width: 80, top: Y(q[1]) - 24, fontSize: 11, fontWeight: 600, color: th.text, textAlign: 'center' } },+ `${q[0]} °C · ${q[1]} %`));+ }+ });+ // the live point+ if (temp != null && pct != null && pct >= 0) {+ const c = heatColor(temp);+ kids.push(h(View, { key: 'halo', style: { position: 'absolute', left: X(temp) - 11, top: Y(pct) - 11, width: 22, height: 22, borderRadius: 11, backgroundColor: c, opacity: 0.25 } }));+ kids.push(h(View, { key: 'live', style: { position: 'absolute', left: X(temp) - 5, top: Y(pct) - 5, width: 10, height: 10, borderRadius: 5, backgroundColor: c, border: '2px solid #ffffff' } }));+ kids.push(h(View, { key: 'livex', style: { position: 'absolute', left: X(temp), top: Y(pct) + 6, width: 1, height: Math.max(0, Y(0) - Y(pct) - 6), backgroundColor: c, opacity: 0.6 } }));+ }+ return h(View, { ref: box, style: { height, direction: 'ltr' } }, kids);+}++// "52 °C" / "—"+export const formatTemp = (v) => (v == null ? '—' : t('cooling.temp', { v: formatNumber(Math.round(v), 0) }));diff --git a/sdk/index.js b/sdk/index.jsindex 43f342d..419e50a 100644--- a/sdk/index.js+++ b/sdk/index.js@@ -95,6 +95,8 @@ export {CLOCK_DEFAULTS, applyIdle,} from './hardware.jsx';import { DisplayConfirm, BluetoothPrompt, startHardware } from './hardware.jsx';+// Fans and cooling (lord-fand, docs/FANS.md): Settings → Cooling and Monitor → Cooling+export { useFan, fanStatus, fanHistory, fanCase, fanControl, refreshFan, coolingVariant, heatColor, CoolingArt, FanCurveChart, formatTemp, FAN_HISTORY } from './cooling.jsx';export { DEFAULT_CATEGORIES, defaultFor, setDefaultFor, candidatesFor, defaultOpenerId, nativeOf } from './defaults.js';export { notifyPrefs, appNotifyPrefs, setAppNotifyPrefs, dndActive, NOTIFY_DEFAULTS } from './notify.js';diff --git a/sdk/settings.js b/sdk/settings.jsindex d439d37..f7782e6 100644--- a/sdk/settings.js+++ b/sdk/settings.js@@ -5,6 +5,7 @@ const DEFAULTS = {mode: 'dark', // 'dark' | 'light'accent: 'azul',effects: true, // transparency with blur+ reduceMotion: false, // decorative animations off (Settings → Appearance)wallpaper: 'aurora',keyboard: 'latam', // before M5; now keyboards (see keyboard.js)keyboards: null, // [{ layout, variant }] from xkb-datadiff --git a/server/Makefile b/server/Makefileindex eae895f..90f8100 100644--- a/server/Makefile+++ b/server/Makefile@@ -153,6 +153,18 @@ build/npcompile-test: tests/npcompile_test.c src/netperm/npcompile.c src/netperm@mkdir -p build$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/npcompile_test.c src/netperm/npcompile.c src/netperm/npdns.c src/fw/rules.c src/fw/dnsmap.c src/fw/fwmap.c src/sec/json.c./$@ || { rm -f $@; exit 1; }+# lord-fand (src/fan, docs/FANS.md): the root service that drives the fans by temperature. libc+# only; it executes nothing and has no network. tests/fan_test.c: curves, fan.json, requests and a+# fake sysfs (run by tests/run_suites.sh).+FAN_SRC := src/fan/fancurve.c src/fan/fanhw.c src/sec/json.c+ALL += build/lord-fand+build/lord-fand: src/fan/fand.c $(FAN_SRC) $(wildcard src/fan/*.h) src/sec/json.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ src/fan/fand.c $(FAN_SRC)+test: build/fan-test+build/fan-test: tests/fan_test.c $(FAN_SRC) $(wildcard src/fan/*.h) src/sec/json.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/fan_test.c $(FAN_SRC)all: $(ALL)# Headless tests: terminal emulator (tests/vt_dump.c), OpenType shaping againstdiff --git a/server/mk/settings.mk b/server/mk/settings.mkindex 76672c8..7076245 100644--- a/server/mk/settings.mk+++ b/server/mk/settings.mk@@ -2,8 +2,9 @@# 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+ 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 \+ src/ui/js_fan.c src/fan/fancurve.c+HW_HDR := $(wildcard src/hw/*.h) $(wildcard src/fan/*.h) src/ui/js_hw.h src/ui/js_fan.h src/kms.h src/vault/dbus.hHW_OBJ := $(HW_SRC:src/%.c=build/obj/%.o)$(HW_OBJ): $(HW_HDR)build/lord-server: $(HW_OBJ)diff --git a/server/src/fan/fancurve.c b/server/src/fan/fancurve.cnew file mode 100644index 0000000..d862903--- /dev/null+++ b/server/src/fan/fancurve.c@@ -0,0 +1,195 @@+/* fancurve.c — profiles, curve evaluation, fan.json and the socket requests (see fancurve.h). */+#include "fan/fancurve.h"+#include "sec/json.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static const char *const NAMES[FP__COUNT] = { "auto", "quiet", "balanced", "performance", "always", "custom" };++/* Presets. Balanced is the curve most cases ship with: 55 °C → 30 %, 60 °C → 55 %, 65 °C → 100 %. */+static const FanCurve PRESET[FP__COUNT] = {+ [FP_QUIET] = { 3, { { 60, 30 }, { 67, 60 }, { 72, 100 } }, 0 },+ [FP_BALANCED] = { 3, { { 55, 30 }, { 60, 55 }, { 65, 100 } }, 0 },+ [FP_PERFORMANCE] = { 3, { { 45, 40 }, { 55, 70 }, { 60, 100 } }, 0 },+ [FP_ALWAYS] = { 2, { { 55, 60 }, { 65, 100 } }, 40 },+};++const char *fan_profile_name(FanProfile p) { return (unsigned)p < FP__COUNT ? NAMES[p] : "auto"; }++int fan_profile_parse(const char *s, FanProfile *out) {+ for (int i = 0; i < FP__COUNT; i++)+ if (!strcmp(s, NAMES[i])) { *out = (FanProfile)i; return 0; }+ return -1;+}++void fan_profile_curve(const FanConfig *cfg, FanCurve *out) {+ memset(out, 0, sizeof *out);+ if (cfg->profile == FP_CUSTOM) *out = cfg->custom;+ else if (cfg->profile != FP_AUTO && (unsigned)cfg->profile < FP__COUNT) *out = PRESET[cfg->profile];+}++int fan_curve_valid(const FanCurve *c) {+ if (c->n < 1 || c->n > FAN_MAX_POINTS) return -1;+ if (c->floor_pct < 0 || c->floor_pct > 100) return -1;+ for (int i = 0; i < c->n; i++) {+ const FanPoint *p = &c->p[i];+ if (p->temp < FAN_TEMP_MIN || p->temp > FAN_TEMP_MAX || p->pct < 0 || p->pct > 100) return -1;+ if (i && (p->temp <= c->p[i - 1].temp || p->pct < c->p[i - 1].pct)) return -1;+ }+ return 0;+}++int fan_curve_step(const FanCurve *c, int hyst, int prev, int temp_mc) {+ if (c->n <= 0) return -1;+ int s = prev < -1 ? -1 : prev >= c->n ? c->n - 1 : prev;+ /* leave a step only hyst °C below it ... */+ while (s >= 0 && temp_mc < (c->p[s].temp - hyst) * 1000) s--;+ /* ... and enter every step the temperature has reached */+ while (s + 1 < c->n && temp_mc >= c->p[s + 1].temp * 1000) s++;+ return s;+}++int fan_curve_pct(const FanCurve *c, int step) {+ int f = c->floor_pct > 0 ? c->floor_pct : 0;+ if (step < 0 || step >= c->n) return f;+ return c->p[step].pct > f ? c->p[step].pct : f;+}++int fan_output_pct(int pct) {+ if (pct <= 0) return 0;+ if (pct >= 100) return 100;+ return pct < FAN_MIN_PCT ? FAN_MIN_PCT : pct;+}++void fan_config_default(FanConfig *cfg, int has_board_fan) {+ memset(cfg, 0, sizeof *cfg);+ /* a board fan (Raspberry Pi fan header) gets our curve from the first boot; a PC's+ * motherboard fans stay with the firmware until the user picks a profile */+ cfg->profile = has_board_fan ? FP_BALANCED : FP_AUTO;+ cfg->custom = PRESET[FP_BALANCED];+ cfg->hyst = FAN_HYST_DEFAULT;+ cfg->force = FF_OFF;+}++static void seterr(char *err, size_t n, const char *m) { if (err && n) snprintf(err, n, "%s", m); }++static int is_int(double v, int lo, int hi) { return v >= lo && v <= hi && v == (double)(int)v; }++int fan_config_parse(const char *text, size_t len, FanConfig *cfg, char *err, size_t errlen) {+ /* the caller fills cfg with fan_config_default(); missing keys keep those values */+ FanConfig c = *cfg, fallback = *cfg;+ JDoc d;+ if (json_parse(text, len, &d, err, errlen)) { *cfg = fallback; return -1; }+ const JVal *o = d.root;+ int bad = 0;+ if (!o || o->type != J_OBJ) { seterr(err, errlen, "not an object"); bad = 1; }+ for (const JVal *k = o && !bad ? o->kid : NULL; k && !bad; k = k->next) {+ if (!strcmp(k->key, "version")) {+ if (k->type != J_NUM || k->num != 1) { seterr(err, errlen, "version"); bad = 1; }+ } else if (!strcmp(k->key, "profile")) {+ if (k->type != J_STR || fan_profile_parse(k->str, &c.profile)) { seterr(err, errlen, "profile"); bad = 1; }+ } else if (!strcmp(k->key, "hyst")) {+ if (k->type != J_NUM || !is_int(k->num, FAN_HYST_MIN, FAN_HYST_MAX)) { seterr(err, errlen, "hyst"); bad = 1; }+ else c.hyst = (int)k->num;+ } else if (!strcmp(k->key, "custom")) {+ if (k->type != J_ARR || k->len < 1 || k->len > FAN_MAX_POINTS) { seterr(err, errlen, "custom"); bad = 1; break; }+ FanCurve cu = { 0 };+ for (const JVal *pt = k->kid; pt; pt = pt->next) {+ const JVal *a = pt->kid, *b = a ? a->next : NULL;+ if (pt->type != J_ARR || pt->len != 2 || a->type != J_NUM || b->type != J_NUM ||+ !is_int(a->num, FAN_TEMP_MIN, FAN_TEMP_MAX) || !is_int(b->num, 0, 100)) { bad = 1; break; }+ cu.p[cu.n].temp = (int)a->num;+ cu.p[cu.n].pct = (int)b->num;+ cu.n++;+ }+ if (bad || fan_curve_valid(&cu)) { seterr(err, errlen, "custom"); bad = 1; }+ else c.custom = cu;+ } else if (!strcmp(k->key, "force")) {+ if (k->type != J_STR) { seterr(err, errlen, "force"); bad = 1; }+ else if (!strcmp(k->str, "off")) c.force = FF_OFF;+ else if (!strcmp(k->str, "on")) c.force = FF_ON;+ else if (!strcmp(k->str, "timed")) c.force = FF_TIMED;+ else { seterr(err, errlen, "force"); bad = 1; }+ } else if (!strcmp(k->key, "forceUntil")) {+ if (k->type != J_NUM || k->num < 0 || k->num > 4102444800.0 || k->num != (double)(long long)k->num) { seterr(err, errlen, "forceUntil"); bad = 1; }+ else c.force_until = (long long)k->num;+ } else { seterr(err, errlen, "unknown key"); bad = 1; }+ }+ json_free(&d);+ if (!bad && c.force == FF_TIMED && c.force_until <= 0) { seterr(err, errlen, "forceUntil"); bad = 1; }+ if (bad) { *cfg = fallback; return -1; }+ if (c.force != FF_TIMED) c.force_until = 0;+ *cfg = c;+ return 0;+}++size_t fan_config_write(const FanConfig *cfg, char *out, size_t n) {+ char pts[FAN_MAX_POINTS * 12 + 4];+ size_t k = 0;+ pts[0] = 0;+ for (int i = 0; i < cfg->custom.n && k < sizeof pts; i++)+ k += (size_t)snprintf(pts + k, sizeof pts - k, "%s[%d,%d]", i ? "," : "", cfg->custom.p[i].temp, cfg->custom.p[i].pct);+ int r = snprintf(out, n, "{\"version\":1,\"profile\":\"%s\",\"hyst\":%d,\"custom\":[%s],\"force\":\"%s\",\"forceUntil\":%lld}\n",+ fan_profile_name(cfg->profile), cfg->hyst, pts,+ cfg->force == FF_ON ? "on" : cfg->force == FF_TIMED ? "timed" : "off",+ cfg->force == FF_TIMED ? cfg->force_until : 0LL);+ return r < 0 ? 0 : (size_t)r;+}++/* A decimal integer of 1..3 digits at *s; advances *s. */+static int take_int(const char **s, int *out) {+ const char *p = *s;+ int v = 0, d = 0;+ while (*p >= '0' && *p <= '9') { if (++d > 4) return -1; v = v * 10 + (*p++ - '0'); }+ if (!d) return -1;+ *s = p;+ *out = v;+ return 0;+}++int fan_curve_parse_text(const char *s, FanCurve *c) {+ FanCurve cu = { 0 };+ for (;;) {+ if (cu.n >= FAN_MAX_POINTS) return -1;+ int t, p;+ if (take_int(&s, &t) || *s++ != ':' || take_int(&s, &p)) return -1;+ cu.p[cu.n].temp = t;+ cu.p[cu.n].pct = p;+ cu.n++;+ if (!*s) break;+ if (*s++ != ',') return -1;+ }+ if (fan_curve_valid(&cu)) return -1;+ *c = cu;+ return 0;+}++int fan_req_parse(const char *line, size_t len, FanReq *r) {+ if (len == 0 || len >= FAN_REQ_MAX || strlen(line) != len) return -1;+ for (size_t i = 0; i < len; i++)+ if ((unsigned char)line[i] < 0x20 || (unsigned char)line[i] > 0x7e) return -1;+ memset(r, 0, sizeof *r);+ if (!strcmp(line, "STATUS")) { r->type = FR_STATUS; return 0; }+ if (!strncmp(line, "PROFILE ", 8)) {+ r->type = FR_PROFILE;+ return fan_profile_parse(line + 8, &r->profile);+ }+ if (!strncmp(line, "CURVE ", 6)) {+ r->type = FR_CURVE;+ return fan_curve_parse_text(line + 6, &r->curve);+ }+ if (!strncmp(line, "FORCE ", 6)) {+ const char *a = line + 6;+ r->type = FR_FORCE;+ if (!strcmp(a, "off")) { r->force = FF_OFF; return 0; }+ if (!strcmp(a, "on")) { r->force = FF_ON; return 0; }+ int m;+ if (take_int(&a, &m) || *a || m < 1 || m > FAN_FORCE_MAX_MIN) return -1;+ r->force = FF_TIMED;+ r->minutes = m;+ return 0;+ }+ return -1;+}diff --git a/server/src/fan/fancurve.h b/server/src/fan/fancurve.hnew file mode 100644index 0000000..e9a2e5e--- /dev/null+++ b/server/src/fan/fancurve.h@@ -0,0 +1,88 @@+/* fancurve.h — fan profiles, curve evaluation with hysteresis, the configuration file and the+ * socket requests of lord-fand (docs/FANS.md). Pure code: no I/O, so it is tested by+ * tests/fan_test.c.+ *+ * A curve is a list of steps "from T °C, P %", sorted by temperature. Below the first step the fan+ * is off (or at the profile's floor). A step is entered when the temperature reaches it and left+ * only when it falls `hyst` °C below it, so the fan does not flap around a threshold. */+#ifndef LORD_FAN_CURVE_H+#define LORD_FAN_CURVE_H++#include <stddef.h>++#define FAN_MAX_POINTS 8+#define FAN_TEMP_MIN 30 /* custom curve limits, °C */+#define FAN_TEMP_MAX 90+#define FAN_HYST_DEFAULT 3 /* °C */+#define FAN_HYST_MIN 1+#define FAN_HYST_MAX 10+#define FAN_MIN_PCT 25 /* below this most small fans stall: a non-zero duty is raised to it */+#define FAN_KICK_BELOW 50 /* starting from 0 % to less than this: one tick at 100 % first */+#define FAN_REQ_MAX 256 /* longest request line accepted on the socket */+#define FAN_FORCE_MAX_MIN (24 * 60)++typedef enum { FP_AUTO, FP_QUIET, FP_BALANCED, FP_PERFORMANCE, FP_ALWAYS, FP_CUSTOM, FP__COUNT } FanProfile;++typedef struct { int temp; int pct; } FanPoint; /* °C, % */++typedef struct {+ int n;+ FanPoint p[FAN_MAX_POINTS];+ int floor_pct; /* duty below the first step (Always on) */+} FanCurve;++typedef enum { FF_OFF, FF_TIMED, FF_ON } FanForceMode;++typedef struct {+ FanProfile profile;+ FanCurve custom; /* the user's curve (kept even while another profile is active) */+ int hyst; /* °C */+ FanForceMode force;+ long long force_until; /* FF_TIMED: CLOCK_REALTIME seconds */+} FanConfig;++const char *fan_profile_name(FanProfile p);+int fan_profile_parse(const char *s, FanProfile *out); /* 0 ok, -1 unknown */++/* The curve a profile runs (custom → cfg->custom). FP_AUTO has no curve (n = 0, floor -1):+ * the fans are left to the kernel or the firmware. */+void fan_profile_curve(const FanConfig *cfg, FanCurve *out);++/* 0 if a user curve is acceptable: 1..FAN_MAX_POINTS points, temperatures FAN_TEMP_MIN..FAN_TEMP_MAX+ * strictly increasing, percentages 0..100 never decreasing. */+int fan_curve_valid(const FanCurve *c);++/* Next step (-1 = below the first) for temperature temp_mc (milli-°C), given the previous step. */+int fan_curve_step(const FanCurve *c, int hyst, int prev, int temp_mc);+/* Duty (%) of a step: the step's %, never below the floor. */+int fan_curve_pct(const FanCurve *c, int step);+/* What reaches the hardware: 0, or at least FAN_MIN_PCT, at most 100. */+int fan_output_pct(int pct);++void fan_config_default(FanConfig *cfg, int has_board_fan);++/* /etc/lordos/fan.json. The caller fills cfg with fan_config_default() first. Parse: 0 ok; -1 on any+ * error (cfg is left unchanged). Strict: unknown+ * keys, bad types or an invalid curve are refused. */+int fan_config_parse(const char *text, size_t len, FanConfig *cfg, char *err, size_t errlen);+size_t fan_config_write(const FanConfig *cfg, char *out, size_t n);++/* "55:30,60:55,65:100" → curve; 0 ok. */+int fan_curve_parse_text(const char *s, FanCurve *c);++/* Socket requests (one line, no trailing newline):+ * STATUS+ * PROFILE auto|quiet|balanced|performance|always|custom+ * CURVE <t:p,...> sets the custom curve and selects it+ * FORCE off|on|<minutes> minutes 1..FAN_FORCE_MAX_MIN */+typedef enum { FR_STATUS, FR_PROFILE, FR_CURVE, FR_FORCE } FanReqType;+typedef struct {+ FanReqType type;+ FanProfile profile;+ FanCurve curve;+ FanForceMode force;+ int minutes;+} FanReq;+int fan_req_parse(const char *line, size_t len, FanReq *r); /* 0 ok, -1 refused */++#endifdiff --git a/server/src/fan/fand.c b/server/src/fan/fand.cnew file mode 100644index 0000000..36da431--- /dev/null+++ b/server/src/fan/fand.c@@ -0,0 +1,341 @@+/* fand.c — lord-fand: the root service that drives the fans by temperature (docs/FANS.md).+ * Closed and minimal, like lord-netperm:+ *+ * - executes nothing and opens no network sockets (the unit forbids every family but AF_UNIX);+ * - reads the CPU temperature every FAND_TICK_MS and writes each fan's duty (fan/fanhw.c);+ * - its configuration is /etc/lordos/fan.json, written only here, after validating;+ * - talks to sessions over /run/lordos/fand.sock (0666) with one line per connection:+ * STATUS anyone: a JSON line with temperature, fans, profile and step+ * PROFILE <name> / CURVE <t:p,...> / FORCE off|on|<minutes>+ * administrators only (SO_PEERCRED: root, or a member of+ * sudo, admin or wheel): "OK" or "ERR <code>"+ * Clients never name paths or devices: the daemon drives every fan it found.+ * - on SIGTERM/SIGINT, and in `lord-fand --restore` (the unit's ExecStopPost, which also runs+ * after a crash), the fans go back to the kernel or the firmware.+ *+ * Other modes, for diagnosis: `lord-fand --detect` prints what it found and exits.+ * For tests only (never in the unit): --root DIR (sysfs root), --config FILE, --run DIR. */+#include "fan/fancurve.h"+#include "fan/fanhw.h"++#include <errno.h>+#include <fcntl.h>+#include <grp.h>+#include <poll.h>+#include <pwd.h>+#include <signal.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/un.h>+#include <time.h>+#include <unistd.h>++#define FAND_TICK_MS 2000+#define FAND_CLIENTS 8+#define FAND_CLIENT_MS 1000+#define FAND_STATUS_MAX 4096++typedef struct {+ int fd;+ long long deadline;+ size_t len;+ char buf[FAN_REQ_MAX + 2];+} Client;++static struct {+ const char *root, *config, *run;+ char sock[256], state[256];+ FanHw hw;+ FanConfig cfg;+ FanCurve curve;+ int step;+ int temp;+ int out_pct; /* what the fans were asked for */+ int controlling; /* 1 while we drive the fans (profile != auto or forced) */+ Client cl[FAND_CLIENTS];+} S = { .root = "", .config = "/etc/lordos/fan.json", .run = "/run/lordos", .step = -1 };++static volatile sig_atomic_t quit;+static void on_signal(int s) { (void)s; quit = 1; }++static long long now_ms(void) {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;+}+static long long wall_s(void) { return (long long)time(NULL); }++/* ---- configuration ---- */++static void load_config(void) {+ fan_config_default(&S.cfg, S.hw.n > 0 && S.hw.t[0].kind == FK_BOARD);+ int fd = open(S.config, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);+ if (fd < 0) return;+ struct stat st;+ char buf[4096];+ ssize_t r = -1;+ /* only a root-owned regular file that nobody else can write */+ if (!fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 022) && st.st_size < (off_t)sizeof buf)+ r = read(fd, buf, sizeof buf - 1);+ close(fd);+ char err[96] = "";+ if (r < 0 || fan_config_parse(buf, (size_t)r, &S.cfg, err, sizeof err))+ fprintf(stderr, "lord-fand: %s ignored (%s), using defaults\n", S.config, r < 0 ? "not a root-owned file" : err);+}++static int save_config(void) {+ char buf[1024], tmp[300];+ size_t n = fan_config_write(&S.cfg, buf, sizeof buf);+ snprintf(tmp, sizeof tmp, "%s.tmp", S.config);+ int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0644);+ if (fd < 0) return -1;+ int ok = n > 0 && write(fd, buf, n) == (ssize_t)n && fsync(fd) == 0;+ close(fd);+ if (!ok || rename(tmp, S.config)) { unlink(tmp); return -1; }+ return 0;+}++/* ---- control ---- */++static int forced(void) {+ if (S.cfg.force == FF_ON) return 1;+ if (S.cfg.force == FF_TIMED) {+ if (wall_s() < S.cfg.force_until) return 1;+ S.cfg.force = FF_OFF;+ S.cfg.force_until = 0;+ save_config();+ }+ return 0;+}++static void apply_profile(void) {+ fan_profile_curve(&S.cfg, &S.curve);+ S.step = -1;+}++static void tick(void) {+ S.temp = fanhw_temp(&S.hw);+ int want_control = S.hw.n > 0 && (S.cfg.profile != FP_AUTO || forced());+ if (!want_control) {+ if (S.controlling) { fanhw_release(&S.hw); unlink(S.state); S.controlling = 0; }+ S.out_pct = -1;+ S.step = -1;+ return;+ }+ if (!S.controlling) { fanhw_take(&S.hw, S.state); S.controlling = 1; }+ int pct;+ if (forced()) pct = 100;+ else if (S.temp <= -1000000) pct = 100; /* no temperature: be safe */+ else {+ S.step = fan_curve_step(&S.curve, S.cfg.hyst, S.step, S.temp);+ pct = fan_curve_pct(&S.curve, S.step);+ }+ S.out_pct = fan_output_pct(pct);+ for (int i = 0; i < S.hw.n; i++) fanhw_set(&S.hw, i, S.out_pct);+}++/* ---- status ---- */++static size_t status_json(char *o, size_t n) {+ size_t k = 0;+#define PUT(...) do { if (k < n) { int r_ = snprintf(o + k, n - k, __VA_ARGS__); if (r_ > 0) k += (size_t)r_; } } while (0)+ PUT("{\"ok\":true,\"board\":\"%s\",\"tempSource\":\"%s\",", S.hw.board ? "pi5" : "", S.hw.temp_src);+ if (S.temp > -1000000) PUT("\"temp\":%d.%d,", S.temp / 1000, (S.temp < 0 ? -S.temp : S.temp) % 1000 / 100);+ else PUT("\"temp\":null,");+ PUT("\"profile\":\"%s\",\"hyst\":%d,\"controlling\":%s,\"step\":%d,\"target\":%d,",+ fan_profile_name(S.cfg.profile), S.cfg.hyst, S.controlling ? "true" : "false", S.step, S.out_pct);+ FanCurve cur;+ fan_profile_curve(&S.cfg, &cur);+ PUT("\"floor\":%d,\"curve\":[", cur.floor_pct);+ for (int i = 0; i < cur.n; i++) PUT("%s[%d,%d]", i ? "," : "", cur.p[i].temp, cur.p[i].pct);+ PUT("],\"custom\":[");+ for (int i = 0; i < S.cfg.custom.n; i++) PUT("%s[%d,%d]", i ? "," : "", S.cfg.custom.p[i].temp, S.cfg.custom.p[i].pct);+ long long left = S.cfg.force == FF_TIMED ? S.cfg.force_until - wall_s() : 0;+ PUT("],\"force\":\"%s\",\"forceLeft\":%lld,\"fans\":[", S.cfg.force == FF_ON ? "on" : S.cfg.force == FF_TIMED ? "timed" : "off", left > 0 ? left : 0);+ for (int i = 0; i < S.hw.n; i++)+ PUT("%s{\"id\":%d,\"kind\":\"%s\",\"chip\":\"%s\",\"ch\":%d,\"pct\":%d,\"rpm\":%d}", i ? "," : "", i,+ fanhw_kind_name(S.hw.t[i].kind), S.hw.t[i].chip, S.hw.t[i].ch, fanhw_pct(&S.hw, i), fanhw_rpm(&S.hw, i));+ PUT("],\"firmwareFans\":[");+ for (int i = 0; i < S.hw.nro; i++) PUT("%s{\"chip\":\"%s\",\"rpm\":%d}", i ? "," : "", S.hw.ro[i].chip, fanhw_ro_rpm(&S.hw, i));+ PUT("]}\n");+#undef PUT+ return k < n ? k : 0;+}++/* ---- socket ---- */++static int peer_is_admin(int fd) {+ struct ucred uc;+ socklen_t l = sizeof uc;+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &uc, &l)) return 0;+ if (uc.uid == 0) return 1;+ struct passwd pw, *pp = NULL;+ char pbuf[2048];+ if (getpwuid_r(uc.uid, &pw, pbuf, sizeof pbuf, &pp) || !pp) return 0;+ gid_t groups[64];+ int n = 64;+ if (getgrouplist(pp->pw_name, pp->pw_gid, groups, &n) < 0) return 0;+ for (int i = 0; i < n; i++) {+ struct group gr, *gp = NULL;+ char gbuf[4096];+ if (getgrgid_r(groups[i], &gr, gbuf, sizeof gbuf, &gp) || !gp) continue;+ if (!strcmp(gp->gr_name, "sudo") || !strcmp(gp->gr_name, "admin") || !strcmp(gp->gr_name, "wheel")) return 1;+ }+ return 0;+}++static void reply(int fd, const char *s, size_t n) {+ while (n) {+ ssize_t w = send(fd, s, n, MSG_NOSIGNAL | MSG_DONTWAIT);+ if (w <= 0) return;+ s += w;+ n -= (size_t)w;+ }+}++static void handle(Client *c) {+ char *nl = memchr(c->buf, '\n', c->len);+ if (!nl) { reply(c->fd, "ERR fan.badRequest\n", 19); return; }+ *nl = 0;+ FanReq r;+ if (fan_req_parse(c->buf, (size_t)(nl - c->buf), &r)) { reply(c->fd, "ERR fan.badRequest\n", 19); return; }+ if (r.type == FR_STATUS) {+ char o[FAND_STATUS_MAX];+ size_t n = status_json(o, sizeof o);+ reply(c->fd, o, n);+ return;+ }+ if (!peer_is_admin(c->fd)) { reply(c->fd, "ERR fan.notAdmin\n", 17); return; }+ FanConfig old = S.cfg;+ if (r.type == FR_PROFILE) S.cfg.profile = r.profile;+ else if (r.type == FR_CURVE) { S.cfg.custom = r.curve; S.cfg.profile = FP_CUSTOM; }+ else if (r.type == FR_FORCE) {+ S.cfg.force = r.force;+ S.cfg.force_until = r.force == FF_TIMED ? wall_s() + (long long)r.minutes * 60 : 0;+ }+ if (save_config()) { S.cfg = old; reply(c->fd, "ERR fan.saveFailed\n", 19); return; }+ fprintf(stderr, "lord-fand: %s\n", c->buf);+ apply_profile();+ tick();+ reply(c->fd, "OK\n", 3);+}++static void drop(Client *c) { close(c->fd); c->fd = -1; c->len = 0; }++static int listen_sock(void) {+ mkdir(S.run, 0755);+ int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);+ if (fd < 0) return -1;+ struct sockaddr_un a = { .sun_family = AF_UNIX };+ if (strlen(S.sock) >= sizeof a.sun_path) { close(fd); return -1; }+ memcpy(a.sun_path, S.sock, strlen(S.sock) + 1);+ unlink(S.sock);+ if (bind(fd, (struct sockaddr *)&a, sizeof a) || chmod(S.sock, 0666) || listen(fd, 8)) { close(fd); return -1; }+ return fd;+}++/* ---- modes ---- */++static int detect(void) {+ FanHw *h = &S.hw;+ printf("board: %s\ntemperature: %s (%s)", h->board ? "Raspberry Pi 5" : "other", h->temp_src[0] ? h->temp_src : "none", h->temp_path);+ int t = fanhw_temp(h);+ if (t > -1000000) printf(" %d.%d C", t / 1000, (t < 0 ? -t : t) % 1000 / 100);+ printf("\n");+ for (int i = 0; i < h->n; i++)+ printf("fan %d: %s %s pwm%d at %d %%, %d rpm (%s)\n", i, fanhw_kind_name(h->t[i].kind), h->t[i].chip, h->t[i].ch,+ fanhw_pct(h, i), fanhw_rpm(h, i), h->t[i].dir);+ for (int i = 0; i < h->ntrips; i++) printf("kernel trip %d: %d mC (%s)\n", h->trip[i], h->trip_orig[i], h->zone);+ for (int i = 0; i < h->nro; i++) printf("firmware fan: %s %d rpm\n", h->ro[i].chip, fanhw_ro_rpm(h, i));+ if (!h->n) printf("no controllable fans\n");+ return 0;+}++int main(int argc, char **argv) {+ int mode_detect = 0, mode_restore = 0;+ for (int i = 1; i < argc; i++) {+ if (!strcmp(argv[i], "--detect")) mode_detect = 1;+ else if (!strcmp(argv[i], "--restore")) mode_restore = 1;+ else if (!strcmp(argv[i], "--root") && i + 1 < argc) S.root = argv[++i];+ else if (!strcmp(argv[i], "--config") && i + 1 < argc) S.config = argv[++i];+ else if (!strcmp(argv[i], "--run") && i + 1 < argc) S.run = argv[++i];+ else { fprintf(stderr, "usage: lord-fand [--detect | --restore]\n"); return 2; }+ }+ if (strlen(S.run) > 100 || strlen(S.config) > 200) return 2;+ snprintf(S.sock, sizeof S.sock, "%s/fand.sock", S.run);+ snprintf(S.state, sizeof S.state, "%s/fand.restore", S.run);+ umask(022);++ if (mode_restore) {+ if (access(S.state, F_OK)) return 0; /* nothing taken */+ int r = fanhw_restore_file(S.root, S.state);+ fprintf(stderr, "lord-fand: fans given back to the kernel/firmware%s\n", r ? " (partially)" : "");+ return 0;+ }+ /* a previous run that died without cleaning up: undo it before reading the "original" values */+ if (!mode_detect && !access(S.state, F_OK)) fanhw_restore_file(S.root, S.state);+ fanhw_scan(&S.hw, S.root);+ if (mode_detect) return detect();++ load_config();+ apply_profile();+ fprintf(stderr, "lord-fand: %d fan(s), %d firmware fan(s), temperature from %s, profile %s\n",+ S.hw.n, S.hw.nro, S.hw.temp_src[0] ? S.hw.temp_src : "nothing", fan_profile_name(S.cfg.profile));++ struct sigaction sa = { .sa_handler = on_signal };+ sigaction(SIGTERM, &sa, NULL);+ sigaction(SIGINT, &sa, NULL);+ signal(SIGPIPE, SIG_IGN);++ int lfd = listen_sock();+ if (lfd < 0) fprintf(stderr, "lord-fand: %s: %s (fans still controlled, no settings)\n", S.sock, strerror(errno));+ for (int i = 0; i < FAND_CLIENTS; i++) S.cl[i].fd = -1;++ long long next = now_ms();+ while (!quit) {+ long long now = now_ms();+ if (now >= next) { tick(); next = now + FAND_TICK_MS; }+ struct pollfd p[1 + FAND_CLIENTS];+ int np = 0;+ if (lfd >= 0) p[np++] = (struct pollfd){ .fd = lfd, .events = POLLIN };+ long long wake = next;+ for (int i = 0; i < FAND_CLIENTS; i++)+ if (S.cl[i].fd >= 0) {+ p[np++] = (struct pollfd){ .fd = S.cl[i].fd, .events = POLLIN };+ if (S.cl[i].deadline < wake) wake = S.cl[i].deadline;+ }+ int to = (int)(wake - now_ms());+ int r = poll(p, (nfds_t)np, to < 0 ? 0 : to);+ if (r < 0 && errno != EINTR) break;+ now = now_ms();+ for (int k = 0; r > 0 && k < np; k++) {+ if (!p[k].revents) continue;+ if (p[k].fd == lfd) {+ int fd = accept4(lfd, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);+ if (fd < 0) continue;+ int slot = -1;+ for (int i = 0; i < FAND_CLIENTS && slot < 0; i++) if (S.cl[i].fd < 0) slot = i;+ if (slot < 0) { close(fd); continue; }+ S.cl[slot] = (Client){ .fd = fd, .deadline = now + FAND_CLIENT_MS };+ continue;+ }+ for (int i = 0; i < FAND_CLIENTS; i++) {+ Client *c = &S.cl[i];+ if (c->fd != p[k].fd) continue;+ ssize_t n = recv(c->fd, c->buf + c->len, sizeof c->buf - 1 - c->len, 0);+ if (n <= 0) { drop(c); break; }+ c->len += (size_t)n;+ if (memchr(c->buf, '\n', c->len) || c->len >= sizeof c->buf - 1) { handle(c); drop(c); }+ break;+ }+ }+ for (int i = 0; i < FAND_CLIENTS; i++) if (S.cl[i].fd >= 0 && now >= S.cl[i].deadline) drop(&S.cl[i]);+ }+ if (S.controlling) { fanhw_release(&S.hw); unlink(S.state); }+ if (lfd >= 0) { close(lfd); unlink(S.sock); }+ fprintf(stderr, "lord-fand: stopped, fans given back to the kernel/firmware\n");+ return 0;+}diff --git a/server/src/fan/fanhw.c b/server/src/fan/fanhw.cnew file mode 100644index 0000000..a9de0f3--- /dev/null+++ b/server/src/fan/fanhw.c@@ -0,0 +1,410 @@+/* fanhw.c — temperature and fan discovery, duty writes and giving control back (see fanhw.h). */+#include "fan/fanhw.h"+#include "fan/fancurve.h"++#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>++#define TEMP_NONE (-1000000)++/* ---- small sysfs helpers ---- */++static int read_str(const char *path, char *out, size_t n) {+ int fd = open(path, 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 - 1] == 0)) out[--r] = 0;+ return 0;+}++static int read_int(const char *path, int *v) {+ char b[32], *e;+ if (read_str(path, b, sizeof b) || !b[0]) return -1;+ errno = 0;+ long x = strtol(b, &e, 10);+ if (errno || *e || x < INT_MIN || x > INT_MAX) return -1;+ *v = (int)x;+ return 0;+}++static int write_int(const char *path, int v) {+ int fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC | O_NOFOLLOW); /* O_TRUNC: no-op on sysfs, needed for the test tree */+ if (fd < 0) return -1;+ char b[16];+ int n = snprintf(b, sizeof b, "%d", v);+ ssize_t w = write(fd, b, (size_t)n);+ close(fd);+ return w == n ? 0 : -1;+}++/* sysfs names end up in JSON: keep only [A-Za-z0-9_.-] */+static void clean(char *s) {+ for (; *s; s++)+ if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9') || *s == '_' || *s == '-' || *s == '.')) *s = '_';+}++static int exists(const char *p) { return access(p, F_OK) == 0; }++static void pathf(char *out, size_t n, const char *fmt, ...) __attribute__((format(printf, 3, 4)));+static void pathf(char *out, size_t n, const char *fmt, ...) {+ va_list ap;+ va_start(ap, fmt);+ int r = vsnprintf(out, n, fmt, ap);+ va_end(ap);+ if (r < 0 || (size_t)r >= n) out[0] = 0; /* a truncated path is never used */+}++/* hwmonN, thermal_zoneN, cooling_deviceN: the prefix followed only by digits */+static int numbered(const char *name, const char *prefix) {+ size_t l = strlen(prefix);+ if (strncmp(name, prefix, l) || !name[l]) return 0;+ for (const char *p = name + l; *p; p++) if (*p < '0' || *p > '9') return 0;+ return 1;+}++/* Super I/O and fan controller drivers whose pwmN_enable=1 means "manual" and whose fans are case+ * or CPU fans. GPU drivers and laptop embedded controllers are not here: their fans stay with+ * the firmware. */+static int chip_allowed(const char *chip) {+ static const char *const pre[] = { "nct6", "nct7", "it8", "f71", "f8000", "w83", "sch5", "emc2", "adt7", "amc6821", "max6650", "max31790", NULL };+ for (int i = 0; pre[i]; i++) if (!strncmp(chip, pre[i], strlen(pre[i]))) return 1;+ return 0;+}++const char *fanhw_kind_name(FanKind k) { return k == FK_BOARD ? "board" : "hwmon"; }++/* ---- scan ---- */++static void find_temp(FanHw *h) {+ char base[FANHW_PATH], p[FANHW_PATH], type[32];+ h->temp_path[0] = 0;+ /* 1. thermal zones of the CPU package */+ pathf(base, sizeof base, "%s/sys/class/thermal", h->root);+ DIR *d = opendir(base);+ struct dirent *e;+ char zone0[FANHW_PATH] = "";+ while (d && (e = readdir(d))) {+ if (!numbered(e->d_name, "thermal_zone")) continue;+ pathf(p, sizeof p, "%s/%s/type", base, e->d_name);+ if (read_str(p, type, sizeof type)) continue;+ clean(type);+ if (!strcmp(e->d_name, "thermal_zone0")) pathf(zone0, sizeof zone0, "%s/%s/temp", base, e->d_name);+ if (!strcmp(type, "cpu-thermal") || !strcmp(type, "x86_pkg_temp") || !strcmp(type, "cpu_thermal")) {+ pathf(h->temp_path, sizeof h->temp_path, "%s/%s/temp", base, e->d_name);+ snprintf(h->temp_src, sizeof h->temp_src, "%s", type);+ break;+ }+ }+ if (d) closedir(d);+ if (h->temp_path[0]) return;+ /* 2. CPU sensors in hwmon */+ pathf(base, sizeof base, "%s/sys/class/hwmon", h->root);+ d = opendir(base);+ while (d && (e = readdir(d))) {+ if (!numbered(e->d_name, "hwmon")) continue;+ pathf(p, sizeof p, "%s/%s/name", base, e->d_name);+ if (read_str(p, type, sizeof type)) continue;+ if (!strcmp(type, "k10temp") || !strcmp(type, "coretemp") || !strcmp(type, "zenpower") || !strcmp(type, "cpu_thermal")) {+ pathf(h->temp_path, sizeof h->temp_path, "%s/%s/temp1_input", base, e->d_name);+ snprintf(h->temp_src, sizeof h->temp_src, "%s", type);+ break;+ }+ }+ if (d) closedir(d);+ if (h->temp_path[0]) return;+ /* 3. whatever thermal_zone0 is */+ if (zone0[0]) { snprintf(h->temp_path, sizeof h->temp_path, "%s", zone0); snprintf(h->temp_src, sizeof h->temp_src, "thermal_zone0"); }+}++/* The cooling device of type "pwm-fan" and the active trips of the zone bound to it. */+static void find_board_trips(FanHw *h) {+ char base[FANHW_PATH], p[FANHW_PATH], s[64], link[FANHW_PATH];+ pathf(base, sizeof base, "%s/sys/class/thermal", h->root);+ DIR *d = opendir(base);+ struct dirent *e;+ char cdev_name[256] = "";+ while (d && (e = readdir(d))) {+ if (!numbered(e->d_name, "cooling_device")) continue;+ pathf(p, sizeof p, "%s/%s/type", base, e->d_name);+ if (!read_str(p, s, sizeof s) && !strcmp(s, "pwm-fan")) {+ snprintf(cdev_name, sizeof cdev_name, "%s", e->d_name);+ pathf(h->cdev, sizeof h->cdev, "%s/%s", base, e->d_name);+ break;+ }+ }+ if (d) closedir(d);+ if (!cdev_name[0]) return;+ d = opendir(base);+ while (d && (e = readdir(d)) && !h->ntrips) {+ if (!numbered(e->d_name, "thermal_zone")) continue;+ char zdir[FANHW_PATH];+ pathf(zdir, sizeof zdir, "%s/%s", base, e->d_name);+ DIR *z = opendir(zdir);+ struct dirent *f;+ while (z && (f = readdir(z))) {+ if (!numbered(f->d_name, "cdev")) continue;+ pathf(p, sizeof p, "%s/%s", zdir, f->d_name);+ ssize_t l = readlink(p, link, sizeof link - 1);+ if (l <= 0) continue;+ link[l] = 0;+ const char *b = strrchr(link, '/');+ b = b ? b + 1 : link;+ if (strcmp(b, cdev_name)) continue;+ int trip, v;+ pathf(p, sizeof p, "%s/%s_trip_point", zdir, f->d_name);+ if (read_int(p, &trip) || trip < 0 || trip > 63) continue;+ pathf(p, sizeof p, "%s/trip_point_%d_type", zdir, trip);+ if (read_str(p, s, sizeof s) || strcmp(s, "active")) continue;+ pathf(p, sizeof p, "%s/trip_point_%d_temp", zdir, trip);+ if (read_int(p, &v)) continue;+ int dup = 0;+ for (int i = 0; i < h->ntrips; i++) dup |= h->trip[i] == trip;+ if (dup || h->ntrips >= FANHW_MAX_TRIPS) continue;+ h->trip[h->ntrips] = trip;+ h->trip_orig[h->ntrips] = v;+ h->ntrips++;+ }+ if (z) closedir(z);+ if (h->ntrips) snprintf(h->zone, sizeof h->zone, "%s", zdir);+ }+ if (d) closedir(d);+ /* sort by original temperature (the backstop keeps their order) */+ for (int i = 1; i < h->ntrips; i++)+ for (int j = i; j > 0 && h->trip_orig[j] < h->trip_orig[j - 1]; j--) {+ int a = h->trip[j], b = h->trip_orig[j];+ h->trip[j] = h->trip[j - 1]; h->trip_orig[j] = h->trip_orig[j - 1];+ h->trip[j - 1] = a; h->trip_orig[j - 1] = b;+ }+}++int fanhw_scan(FanHw *h, const char *root) {+ memset(h, 0, sizeof *h);+ snprintf(h->root, sizeof h->root, "%s", root ? root : "");+ char base[FANHW_PATH], p[FANHW_PATH], chip[32], model[128];+ pathf(p, sizeof p, "%s/proc/device-tree/model", h->root);+ if (!read_str(p, model, sizeof model) && strstr(model, "Raspberry Pi 5")) h->board = 1;+ find_temp(h);+ pathf(base, sizeof base, "%s/sys/class/hwmon", h->root);+ DIR *d = opendir(base);+ struct dirent *e;+ /* readdir order is not stable: collect the names and sort them */+ char names[32][24];+ int nn = 0;+ while (d && (e = readdir(d)) && nn < 32)+ if (numbered(e->d_name, "hwmon") && strlen(e->d_name) < sizeof names[0]) snprintf(names[nn++], sizeof names[0], "%s", e->d_name);+ if (d) closedir(d);+ for (int i = 1; i < nn; i++)+ for (int j = i; j > 0 && atoi(names[j] + 5) < atoi(names[j - 1] + 5); j--) {+ char t[24];+ memcpy(t, names[j], sizeof t); memcpy(names[j], names[j - 1], sizeof t); memcpy(names[j - 1], t, sizeof t);+ }+ for (int k = 0; k < nn; k++) {+ char dir[FANHW_PATH];+ pathf(dir, sizeof dir, "%s/%s", base, names[k]);+ pathf(p, sizeof p, "%s/name", dir);+ if (read_str(p, chip, sizeof chip)) continue;+ clean(chip);+ int board = !strcmp(chip, "pwmfan");+ int allowed = board || chip_allowed(chip);+ for (int ch = 1; ch <= 8; ch++) {+ char pwm[FANHW_PATH], en[FANHW_PATH], rpm[FANHW_PATH];+ pathf(pwm, sizeof pwm, "%s/pwm%d", dir, ch);+ pathf(en, sizeof en, "%s/pwm%d_enable", dir, ch);+ pathf(rpm, sizeof rpm, "%s/fan%d_input", dir, ch);+ int has_pwm = exists(pwm) && exists(en);+ if (allowed && has_pwm && h->n < FANHW_MAX) {+ FanTarget *t = &h->t[h->n++];+ t->kind = board ? FK_BOARD : FK_HWMON;+ snprintf(t->chip, sizeof t->chip, "%s", chip);+ snprintf(t->dir, sizeof t->dir, "%s", dir);+ pathf(p, sizeof p, "%s/device", dir);+ if (!realpath(p, t->dev)) snprintf(t->dev, sizeof t->dev, "%s", dir);+ t->ch = ch;+ t->has_rpm = exists(rpm);+ t->orig_enable = -1;+ t->last_pct = -1;+ if (board) find_board_trips(h);+ } else if (exists(rpm) && h->nro < FANHW_MAX_RO) {+ FanRo *r = &h->ro[h->nro++];+ snprintf(r->chip, sizeof r->chip, "%s", chip);+ snprintf(r->path, sizeof r->path, "%s", rpm);+ }+ }+ }+ return h->n;+}++int fanhw_temp(const FanHw *h) {+ int v;+ if (!h->temp_path[0] || read_int(h->temp_path, &v) || v < -50000 || v > 200000) return TEMP_NONE;+ return v;+}++/* ---- control ---- */++static int to_pwm(int pct) { return pct <= 0 ? 0 : pct >= 100 ? 255 : (pct * 255 + 50) / 100; }+static int to_pct(int pwm) { return pwm <= 0 ? 0 : pwm >= 255 ? 100 : (pwm * 100 + 127) / 255; }++static void tpath(const FanTarget *t, const char *what, char *out, size_t n) {+ pathf(out, n, "%s/pwm%d%s", t->dir, t->ch, what);+}++int fanhw_take(FanHw *h, const char *state_path) {+ /* 1. the restore notes first, so a crash right after leaves enough to undo it */+ if (state_path) {+ char tmp[FANHW_PATH];+ pathf(tmp, sizeof tmp, "%s.tmp", state_path);+ FILE *f = tmp[0] ? fopen(tmp, "we") : NULL;+ if (f) {+ fprintf(f, "lord-fand 1\n");+ for (int i = 0; i < h->n; i++) {+ FanTarget *t = &h->t[i];+ char p[FANHW_PATH];+ tpath(t, "_enable", p, sizeof p);+ int v;+ if (t->kind == FK_HWMON && !read_int(p, &v)) t->orig_enable = v;+ if (t->kind == FK_HWMON && t->orig_enable >= 0 && !strchr(t->dev, ' ') && !strchr(t->dev, '\n'))+ fprintf(f, "enable %d %d %s\n", t->ch, t->orig_enable, t->dev);+ }+ for (int i = 0; i < h->ntrips; i++) fprintf(f, "trip %d %d\n", h->trip[i], h->trip_orig[i]);+ if (fclose(f) == 0) rename(tmp, state_path);+ else unlink(tmp);+ }+ }+ int ok = 0;+ for (int i = 0; i < h->n; i++) {+ FanTarget *t = &h->t[i];+ char p[FANHW_PATH];+ if (t->kind == FK_HWMON) {+ tpath(t, "_enable", p, sizeof p);+ int v;+ if (t->orig_enable < 0 && !read_int(p, &v)) t->orig_enable = v;+ if (write_int(p, 1)) { fprintf(stderr, "lord-fand: %s: manual mode refused\n", p); continue; }+ }+ t->taken = 1;+ ok++;+ }+ /* the board fan: move the kernel's trips up to the backstop, so it does not fight our writes+ * but still spins the fan up by itself if we ever stop answering above it */+ for (int i = 0; i < h->ntrips; i++) {+ char p[FANHW_PATH];+ pathf(p, sizeof p, "%s/trip_point_%d_temp", h->zone, h->trip[i]);+ int want = (FANHW_BACKSTOP_C + 2 * i) * 1000;+ if (h->trip_orig[i] < want && write_int(p, want) == 0) h->trips_raised = 1;+ }+ return ok;+}++int fanhw_pct(const FanHw *h, int i) {+ char p[FANHW_PATH];+ int v;+ if (i < 0 || i >= h->n) return -1;+ tpath(&h->t[i], "", p, sizeof p);+ return read_int(p, &v) ? -1 : to_pct(v);+}++int fanhw_set(FanHw *h, int i, int pct) {+ if (i < 0 || i >= h->n || !h->t[i].taken) return -1;+ FanTarget *t = &h->t[i];+ char p[FANHW_PATH];+ tpath(t, "", p, sizeof p);+ int cur;+ if (read_int(p, &cur)) return -1;+ int want = to_pwm(pct);+ /* a stopped fan given a low duty may not start: one tick at full speed first */+ if (cur == 0 && pct > 0 && pct < FAN_KICK_BELOW) { want = 255; t->kicking = 1; }+ else t->kicking = 0;+ t->last_pct = pct;+ if (cur == want) return 0;+ return write_int(p, want);+}++int fanhw_rpm(const FanHw *h, int i) {+ char p[FANHW_PATH];+ int v;+ if (i < 0 || i >= h->n || !h->t[i].has_rpm) return -1;+ pathf(p, sizeof p, "%s/fan%d_input", h->t[i].dir, h->t[i].ch);+ return read_int(p, &v) || v < 0 ? -1 : v;+}++int fanhw_ro_rpm(const FanHw *h, int i) {+ int v;+ if (i < 0 || i >= h->nro || read_int(h->ro[i].path, &v) || v < 0) return -1;+ return v;+}++/* The board fan's cooling state for temp under the original trips, written to the cooling device+ * (which sets the duty from the device tree's cooling levels). */+static void board_state_now(FanHw *h) {+ if (!h->cdev[0]) return;+ int temp = fanhw_temp(h), max = 0, st = 0;+ char p[FANHW_PATH];+ pathf(p, sizeof p, "%s/max_state", h->cdev);+ if (read_int(p, &max) || max < 0) return;+ for (int i = 0; i < h->ntrips; i++) if (temp != TEMP_NONE && temp >= h->trip_orig[i]) st++;+ if (st > max) st = max;+ pathf(p, sizeof p, "%s/cur_state", h->cdev);+ write_int(p, st);+}++void fanhw_release(FanHw *h) {+ for (int i = 0; i < h->ntrips; i++) {+ char p[FANHW_PATH];+ pathf(p, sizeof p, "%s/trip_point_%d_temp", h->zone, h->trip[i]);+ write_int(p, h->trip_orig[i]);+ }+ h->trips_raised = 0;+ board_state_now(h);+ for (int i = 0; i < h->n; i++) {+ FanTarget *t = &h->t[i];+ if (t->kind == FK_HWMON && t->taken && t->orig_enable >= 0) {+ char p[FANHW_PATH];+ tpath(t, "_enable", p, sizeof p);+ write_int(p, t->orig_enable);+ }+ t->taken = 0;+ }+}++int fanhw_restore_file(const char *root, const char *state_path) {+ FanHw h;+ fanhw_scan(&h, root);+ FILE *f = fopen(state_path, "re");+ int rc = 0;+ if (f) {+ char line[FANHW_PATH + 64];+ if (!fgets(line, sizeof line, f) || strcmp(line, "lord-fand 1\n")) rc = -1;+ while (rc == 0 && fgets(line, sizeof line, f)) {+ int a, b, n = 0;+ char dev[FANHW_PATH];+ if (sscanf(line, "trip %d %d%n", &a, &b, &n) == 2 && line[n] == '\n') {+ if (b < 0 || b > 200000) continue;+ for (int i = 0; i < h.ntrips; i++) if (h.trip[i] == a) h.trip_orig[i] = b;+ } else if (sscanf(line, "enable %d %d %319s%n", &a, &b, dev, &n) == 3 && line[n] == '\n') {+ if (b < 0 || b > 5) continue;+ for (int i = 0; i < h.n; i++)+ if (h.t[i].kind == FK_HWMON && h.t[i].ch == a && !strcmp(h.t[i].dev, dev)) { h.t[i].orig_enable = b; h.t[i].taken = 1; }+ }+ }+ fclose(f);+ }+ /* the trips go back even without notes: never leave them at the backstop */+ if (h.ntrips) {+ int raised = 1;+ for (int i = 0; i < h.ntrips; i++) raised &= h.trip_orig[i] >= FANHW_BACKSTOP_C * 1000;+ if (raised && !f) rc = -1; /* no notes and trips look raised: the original values are unknown */+ }+ if (f || !h.ntrips) fanhw_release(&h);+ unlink(state_path);+ return rc;+}diff --git a/server/src/fan/fanhw.h b/server/src/fan/fanhw.hnew file mode 100644index 0000000..3d84a48--- /dev/null+++ b/server/src/fan/fanhw.h@@ -0,0 +1,85 @@+/* fanhw.h — lord-fand's hardware side: finds the CPU temperature and the fans it may drive, and+ * writes their duty (docs/FANS.md). Everything is found under a sysfs root (normally "", so the+ * real /sys; tests/fan_test.c builds a fake tree). Paths never come from a client: a client only+ * picks a profile, and the daemon drives every fan it found.+ *+ * Kinds of fan:+ * FK_BOARD the Raspberry Pi 5 fan header (hwmon "pwmfan", cooling device "pwm-fan"): the official+ * Active Cooler and case fans plugged there (the Argon ONE V5 case's blower too).+ * pwm1 is written directly; the kernel's active trip points for this fan are raised+ * to a backstop (FANHW_BACKSTOP_C) while we drive it, and put back when we stop.+ * FK_HWMON a motherboard Super I/O or fan controller with pwmN + pwmN_enable (allow-listed+ * drivers). pwmN_enable is set to 1 (manual) while we drive it and put back after.+ * Fans that only report fanN_input (laptops, GPUs, unknown drivers) are listed as "managed by+ * firmware" and never written. */+#ifndef LORD_FAN_HW_H+#define LORD_FAN_HW_H++#define FANHW_MAX 8+#define FANHW_MAX_RO 8+#define FANHW_MAX_TRIPS 8+#define FANHW_PATH 320+#define FANHW_BACKSTOP_C 78 /* kernel trips while we drive the board fan: 78, 80, 82, 84 °C */++typedef enum { FK_BOARD, FK_HWMON } FanKind;++typedef struct {+ FanKind kind;+ char chip[32]; /* hwmon name */+ char dir[FANHW_PATH]; /* .../hwmonN */+ char dev[FANHW_PATH]; /* realpath of hwmonN/device (identity across restarts) */+ int ch; /* pwmN */+ int has_rpm;+ int orig_enable; /* FK_HWMON: pwmN_enable before we took it (-1 unknown) */+ int taken;+ int last_pct; /* last duty written, -1 none */+ int kicking; /* one tick at 100 % before a low duty */+} FanTarget;++typedef struct {+ char chip[32];+ char path[FANHW_PATH]; /* fanN_input */+} FanRo;++typedef struct {+ char root[128];+ FanTarget t[FANHW_MAX];+ int n;+ FanRo ro[FANHW_MAX_RO];+ int nro;+ char temp_path[FANHW_PATH];+ char temp_src[32];+ /* FK_BOARD: the kernel trips bound to its cooling device */+ char zone[FANHW_PATH]; /* .../thermal_zoneN */+ char cdev[FANHW_PATH]; /* .../cooling_deviceM (type pwm-fan) */+ int ntrips;+ int trip[FANHW_MAX_TRIPS]; /* trip index */+ int trip_orig[FANHW_MAX_TRIPS];+ int trips_raised;+ int board; /* 1: Raspberry Pi 5 (device-tree model) */+} FanHw;++/* Finds the temperature source and the fans. root: "" for the real system. Returns the number+ * of drivable fans. */+int fanhw_scan(FanHw *h, const char *root);+/* CPU temperature in milli-°C, or -1000000 if unreadable. */+int fanhw_temp(const FanHw *h);+/* Takes manual control of every fan (hwmon: pwmN_enable=1; board: raise the trips). Writes what it+ * changed to state_path first (if not NULL) so `lord-fand --restore` can undo it after a crash. */+int fanhw_take(FanHw *h, const char *state_path);+/* Duty 0..100 to fan i (already through fan_output_pct). Rewrites only when the value read back+ * differs, so a kernel step in between is corrected on the next tick. */+int fanhw_set(FanHw *h, int i, int pct);+int fanhw_pct(const FanHw *h, int i); /* duty read back, -1 unknown */+int fanhw_rpm(const FanHw *h, int i); /* -1 if the fan has no tachometer */+int fanhw_ro_rpm(const FanHw *h, int i);+/* Gives every fan back to the kernel or firmware: original pwmN_enable and trip points, and the+ * board fan's cooling state for the current temperature. */+void fanhw_release(FanHw *h);+/* After a crash: rescan and restore what state_path says (validated: only values, matched to the+ * fans found by the scan). Then removes the file. 0 ok. */+int fanhw_restore_file(const char *root, const char *state_path);++const char *fanhw_kind_name(FanKind k);++#endifdiff --git a/server/src/hw/hw_admin.c b/server/src/hw/hw_admin.cindex c720f38..8dc5e26 100644--- a/server/src/hw/hw_admin.c+++ b/server/src/hw/hw_admin.c@@ -217,3 +217,44 @@ void hw_act_bt_unblock(const AdminReq *r, const char *arg, size_t len) {if (w != RFKILL_EVENT_SIZE_V1) admin_err("hw.rfkillFailed", "errno", lerr_errno(errno), NULL);else admin_ok("hw.unblocked", NULL);}++/* ---- Raspberry Pi 5 case accessories (docs/FANS.md, "Argon ONE V5 case") ---- */++/* The cases LordOS knows. The text is fixed here; the file is included from config.txt+ * ("include lordos-case.txt", tools/rpi). Never user text. */+const char *hw_rpi_case_text(const char *id) {+ if (!strcmp(id, "none"))+ return "# lordos-case.txt: written by LordOS (Settings, Cooling). No case accessories.\n";+ if (!strcmp(id, "argon-one-v5"))+ return "# lordos-case.txt: written by LordOS (Settings, Cooling). Do not edit by hand.\n"+ "# Argon ONE V5 case: its board puts the two front USB 2.0 ports and the audio chip\n"+ "# (USB) on the USB-C controller, which has to work as a host. Its fan is on the fan\n"+ "# header and is driven by lord-fand: nothing to set for it.\n"+ "[pi5]\n"+ "dtoverlay=dwc2,dr_mode=host\n"+ "[all]\n";+ return NULL;+}++void hw_act_rpi_case(const AdminReq *r, const char *arg, size_t len) {+ (void)r;+ char id[24], model[96] = "";+ const char *text;+ if (arg_copy(arg, len, id, sizeof id) || !(text = hw_rpi_case_text(id))) { admin_err("admin.invalidArgument", NULL); return; }+ int fd = open("/proc/device-tree/model", O_RDONLY | O_CLOEXEC);+ if (fd >= 0) { ssize_t n = read(fd, model, sizeof model - 1); if (n > 0) model[n] = 0; close(fd); }+ struct stat st;+ if (!strstr(model, "Raspberry Pi 5") || stat("/boot/firmware/config.txt", &st) || !S_ISREG(st.st_mode)) {+ admin_err("hw.notRaspberryPi5", NULL);+ return;+ }+ /* written next to config.txt: temporary file, then rename (the FAT partition has no links) */+ const char *tmp = "/boot/firmware/lordos-case.tmp", *dst = "/boot/firmware/lordos-case.txt";+ fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0644);+ if (fd < 0) { admin_err("hw.caseFailed", "errno", lerr_errno(errno), NULL); return; }+ size_t l = strlen(text);+ int ok = write(fd, text, l) == (ssize_t)l && fsync(fd) == 0;+ close(fd);+ if (!ok || rename(tmp, dst)) { unlink(tmp); admin_err("hw.caseFailed", "errno", lerr_errno(errno), NULL); return; }+ admin_ok("hw.caseSet", "case", id, NULL);+}diff --git a/server/src/hw/hw_admin.h b/server/src/hw/hw_admin.hindex 2e7074e..e4b4476 100644--- a/server/src/hw/hw_admin.h+++ b/server/src/hw/hw_admin.h@@ -10,6 +10,9 @@* 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+ * rpi-case none|argon-one-v5 Raspberry Pi 5 only: writes /boot/firmware/lordos-case.txt+ * (fixed text, included from config.txt; takes effect+ * after a restart) admin*/#ifndef LORD_HW_ADMIN_H#define LORD_HW_ADMIN_H@@ -23,6 +26,8 @@ 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);+void hw_act_rpi_case(const AdminReq *r, const char *arg, size_t len);+const char *hw_rpi_case_text(const char *id); /* fixed file text of a known case, NULL otherwise *//* Validators, exposed for tests. */int hw_button_action_valid(const char *a, int lid);@@ -36,6 +41,7 @@ int hw_backlight_name_valid(const char *n);{ "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 },+ { "bt-unblock", hw_act_bt_unblock, A_ANYONE }, \+ { "rpi-case", hw_act_rpi_case, 0 },#endifdiff --git a/server/src/ui/js_fan.c b/server/src/ui/js_fan.cnew file mode 100644index 0000000..088757e--- /dev/null+++ b/server/src/ui/js_fan.c@@ -0,0 +1,177 @@+/* js_fan.c — lord.fan: Settings → Cooling and Monitor talk to lord-fand (docs/FANS.md).+ *+ * lord.fan.status() the daemon's status object, or null if it is not running+ * lord.fan.setProfile(name) auto|quiet|balanced|performance|always|custom → '' or an error code+ * lord.fan.setCurve(points) [[°C, %], ...] (1..8 points, 30..90 °C rising, 0..100 % never falling)+ * lord.fan.force(v) 'on' | 'off' | minutes (1..1440)+ * lord.fan.caseConfig() 'argon-one-v5' | 'none' | null (not a LordOS Raspberry Pi image)+ *+ * Everything is validated here and again in lord-fand (which also checks that the user is an+ * administrator). The requests are one short line over /run/lordos/fand.sock; the daemon answers+ * at once, and a call never waits more than FAN_WAIT_MS. LORD_FAND_SOCK and LORD_FAN_CASE_FILE+ * point elsewhere for tests and screenshots (they only change what this user's session reads). */+#include "js_fan.h"+#include "js_err.h"+#include "../fan/fancurve.h"++#include <errno.h>+#include <fcntl.h>+#include <poll.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/socket.h>+#include <sys/un.h>+#include <time.h>+#include <unistd.h>++#define FAN_SOCK "/run/lordos/fand.sock"+#define FAN_CASE_FILE "/boot/firmware/lordos-case.txt"+#define FAN_WAIT_MS 300+#define FAN_REPLY_MAX 8192++static long long ms_now(void) {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;+}++/* Sends one request line and reads the whole answer. Returns its length, -1 if the daemon is not+ * there or too slow. */+static int fan_ask(const char *req, char *out, size_t n) {+ const char *path = getenv("LORD_FAND_SOCK");+ if (!path || !*path) path = FAN_SOCK;+ struct sockaddr_un a = { .sun_family = AF_UNIX };+ 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 | SOCK_NONBLOCK, 0);+ if (fd < 0) return -1;+ if (connect(fd, (struct sockaddr *)&a, sizeof a)) { close(fd); return -1; }+ char line[FAN_REQ_MAX + 2];+ int l = snprintf(line, sizeof line, "%s\n", req);+ if (l <= 0 || (size_t)l >= sizeof line || send(fd, line, (size_t)l, MSG_NOSIGNAL) != l) { close(fd); return -1; }+ size_t got = 0;+ long long end = ms_now() + FAN_WAIT_MS;+ for (;;) {+ int left = (int)(end - ms_now());+ if (left <= 0) { close(fd); return -1; }+ struct pollfd p = { .fd = fd, .events = POLLIN };+ if (poll(&p, 1, left) <= 0) { if (errno == EINTR) continue; close(fd); return -1; }+ ssize_t r = recv(fd, out + got, n - 1 - got, 0);+ if (r < 0 && (errno == EAGAIN || errno == EINTR)) continue;+ if (r <= 0) break;+ got += (size_t)r;+ if (got >= n - 1) break;+ }+ close(fd);+ out[got] = 0;+ return (int)got;+}++/* OK → '', ERR <code> → '<code>', no daemon → 'fan.unavailable' */+static JSValue fan_command(JSContext *c, const char *req) {+ char out[128];+ if (fan_ask(req, out, sizeof out) < 0) return JS_NewString(c, "fan.unavailable");+ out[strcspn(out, "\n")] = 0;+ if (!strcmp(out, "OK")) return JS_NewString(c, "");+ if (!strncmp(out, "ERR fan.", 8) && strlen(out) < 40) return JS_NewString(c, out + 4);+ return JS_NewString(c, "fan.badRequest");+}++static JSValue f_status(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t; (void)argc; (void)argv;+ char *out = malloc(FAN_REPLY_MAX);+ if (!out) return JS_NULL;+ int n = fan_ask("STATUS", out, FAN_REPLY_MAX);+ JSValue v = n > 0 && out[0] == '{' ? JS_ParseJSON(c, out, (size_t)n, "<fan>") : JS_NULL;+ free(out);+ if (JS_IsException(v)) { JS_FreeValue(c, JS_GetException(c)); return JS_NULL; }+ return v;+}++static JSValue f_set_profile(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ if (argc < 1 || !JS_IsString(argv[0])) return js_throw_code(c, "fan.badRequest", NULL);+ const char *s = JS_ToCString(c, argv[0]);+ if (!s) return JS_EXCEPTION;+ FanProfile p;+ char req[48];+ int ok = strlen(s) < 20 && fan_profile_parse(s, &p) == 0;+ if (ok) snprintf(req, sizeof req, "PROFILE %s", fan_profile_name(p));+ JS_FreeCString(c, s);+ if (!ok) return js_throw_code(c, "fan.badRequest", NULL);+ return fan_command(c, req);+}++static JSValue f_set_curve(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ if (argc < 1 || !JS_IsArray(c, argv[0])) return js_throw_code(c, "fan.badRequest", NULL);+ JSValue lv = JS_GetPropertyStr(c, argv[0], "length");+ int32_t n = -1;+ if (JS_ToInt32(c, &n, lv)) n = -1;+ JS_FreeValue(c, lv);+ if (n < 1 || n > FAN_MAX_POINTS) return js_throw_code(c, "fan.badRequest", NULL);+ FanCurve cu = { 0 };+ for (int i = 0; i < n; i++) {+ JSValue pt = JS_GetPropertyUint32(c, argv[0], (uint32_t)i);+ JSValue a = JS_GetPropertyUint32(c, pt, 0), b = JS_GetPropertyUint32(c, pt, 1);+ double x = -1, y = -1;+ int bad = !JS_IsNumber(a) || !JS_IsNumber(b) || JS_ToFloat64(c, &x, a) || JS_ToFloat64(c, &y, b);+ JS_FreeValue(c, a); JS_FreeValue(c, b); JS_FreeValue(c, pt);+ if (bad || x != (int)x || y != (int)y) return js_throw_code(c, "fan.badRequest", NULL);+ cu.p[i].temp = (int)x;+ cu.p[i].pct = (int)y;+ cu.n++;+ }+ if (fan_curve_valid(&cu)) return js_throw_code(c, "fan.badCurve", NULL);+ char req[FAN_REQ_MAX];+ size_t k = (size_t)snprintf(req, sizeof req, "CURVE ");+ for (int i = 0; i < cu.n; i++) k += (size_t)snprintf(req + k, sizeof req - k, "%s%d:%d", i ? "," : "", cu.p[i].temp, cu.p[i].pct);+ return fan_command(c, req);+}++static JSValue f_force(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ char req[32];+ if (argc >= 1 && JS_IsString(argv[0])) {+ const char *s = JS_ToCString(c, argv[0]);+ if (!s) return JS_EXCEPTION;+ int ok = !strcmp(s, "on") || !strcmp(s, "off");+ if (ok) snprintf(req, sizeof req, "FORCE %s", s);+ JS_FreeCString(c, s);+ if (!ok) return js_throw_code(c, "fan.badRequest", NULL);+ } else if (argc >= 1 && JS_IsNumber(argv[0])) {+ double m;+ if (JS_ToFloat64(c, &m, argv[0]) || m != (int)m || m < 1 || m > FAN_FORCE_MAX_MIN) return js_throw_code(c, "fan.badRequest", NULL);+ snprintf(req, sizeof req, "FORCE %d", (int)m);+ } else return js_throw_code(c, "fan.badRequest", NULL);+ return fan_command(c, req);+}++static JSValue f_case(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t; (void)argc; (void)argv;+ const char *path = getenv("LORD_FAN_CASE_FILE");+ if (!path || !*path) path = FAN_CASE_FILE;+ int fd = open(path, O_RDONLY | O_CLOEXEC);+ if (fd < 0) return JS_NULL;+ char b[1024];+ ssize_t r = read(fd, b, sizeof b - 1);+ close(fd);+ if (r < 0) return JS_NULL;+ b[r] = 0;+ return JS_NewString(c, strstr(b, "\n[pi5]\ndtoverlay=dwc2,dr_mode=host\n") && strstr(b, "Argon ONE V5 case") ? "argon-one-v5" : "none");+}++static const JSCFunctionListEntry fan_funcs[] = {+ JS_CFUNC_DEF("status", 0, f_status),+ JS_CFUNC_DEF("setProfile", 1, f_set_profile),+ JS_CFUNC_DEF("setCurve", 1, f_set_curve),+ JS_CFUNC_DEF("force", 1, f_force),+ JS_CFUNC_DEF("caseConfig", 0, f_case),+};++void js_fan_register(JSContext *c, JSValue lord) {+ JSValue o = JS_NewObject(c);+ JS_SetPropertyFunctionList(c, o, fan_funcs, sizeof fan_funcs / sizeof fan_funcs[0]);+ JS_SetPropertyStr(c, lord, "fan", o);+}diff --git a/server/src/ui/js_fan.h b/server/src/ui/js_fan.hnew file mode 100644index 0000000..b215d20--- /dev/null+++ b/server/src/ui/js_fan.h@@ -0,0 +1,9 @@+/* js_fan.h — lord.fan, the session side of lord-fand (see js_fan.c, docs/FANS.md). */+#ifndef LORD_JS_FAN_H+#define LORD_JS_FAN_H++#include "quickjs.h"++void js_fan_register(JSContext *c, JSValue lord);++#endifdiff --git a/server/src/ui/js_hw.c b/server/src/ui/js_hw.cindex 1da7356..b891cde 100644--- a/server/src/ui/js_hw.c+++ b/server/src/ui/js_hw.c@@ -18,8 +18,10 @@* 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+ * lord.fan.status() / setProfile(p) / setCurve(pts) / force(v) / caseConfig() (js_fan.c, lord-fand)*/#include "js_hw.h"+#include "js_fan.h"#include "../hw/bt.h"#include "../hw/defaults.h"#include "../hw/display.h"@@ -347,4 +349,5 @@ void js_hw_register(JSContext *c, JSValue lord) {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]);+ js_fan_register(c, lord); /* lord.fan: Settings → Cooling and Monitor (js_fan.c) */}diff --git a/server/tests/fan_test.c b/server/tests/fan_test.cnew file mode 100644index 0000000..b9714c7--- /dev/null+++ b/server/tests/fan_test.c@@ -0,0 +1,369 @@+/* fan_test.c — lord-fand without hardware (docs/FANS.md):+ * - curve evaluation and hysteresis, presets, output clamping;+ * - fan.json parser: valid files, round trip, and many broken ones (fuzz-ish);+ * - socket request parser;+ * - the sysfs driver against a fake tree: a Raspberry Pi 5 fan header with kernel trips and a PC+ * Super I/O chip, take/set/release and the crash restore file.+ * Usage: build/fan-test runs everything+ * build/fan-test mkfake DIR VARIANT builds a fake tree (pi5 | pc | none) for manual runs */+#include "fan/fancurve.h"+#include "fan/fanhw.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: CHECK(%s) failed\n", __FILE__, __LINE__, #c); } } while (0)++/* ---- curve ---- */++static void test_curve(void) {+ FanConfig cfg;+ fan_config_default(&cfg, 1);+ CHECK(cfg.profile == FP_BALANCED);+ FanCurve c;+ fan_profile_curve(&cfg, &c);+ CHECK(c.n == 3 && c.p[0].temp == 55 && c.p[0].pct == 30 && c.p[2].pct == 100);+ CHECK(fan_curve_valid(&c) == 0);+ /* going up */+ int s = -1;+ s = fan_curve_step(&c, 3, s, 40000); CHECK(s == -1); CHECK(fan_curve_pct(&c, s) == 0);+ s = fan_curve_step(&c, 3, s, 54999); CHECK(s == -1);+ s = fan_curve_step(&c, 3, s, 55000); CHECK(s == 0); CHECK(fan_curve_pct(&c, s) == 30);+ s = fan_curve_step(&c, 3, s, 61000); CHECK(s == 1); CHECK(fan_curve_pct(&c, s) == 55);+ s = fan_curve_step(&c, 3, s, 70000); CHECK(s == 2); CHECK(fan_curve_pct(&c, s) == 100);+ /* jump straight from off to the top */+ CHECK(fan_curve_step(&c, 3, -1, 80000) == 2);+ /* hysteresis on the way down: 65 → stays until below 62 */+ s = fan_curve_step(&c, 3, 2, 64000); CHECK(s == 2);+ s = fan_curve_step(&c, 3, s, 62000); CHECK(s == 2);+ s = fan_curve_step(&c, 3, s, 61999); CHECK(s == 1);+ s = fan_curve_step(&c, 3, s, 57500); CHECK(s == 1);+ s = fan_curve_step(&c, 3, s, 56999); CHECK(s == 0);+ s = fan_curve_step(&c, 3, s, 52000); CHECK(s == 0);+ s = fan_curve_step(&c, 3, s, 51999); CHECK(s == -1);+ /* big drop leaves several steps at once */+ CHECK(fan_curve_step(&c, 3, 2, 30000) == -1);+ /* oscillating around a threshold does not flap */+ s = 0;+ for (int i = 0; i < 20; i++) { s = fan_curve_step(&c, 3, s, i & 1 ? 54500 : 55500); CHECK(s == 0); }+ /* bad previous steps are clamped */+ CHECK(fan_curve_step(&c, 3, 99, 70000) == 2);+ CHECK(fan_curve_step(&c, 3, -7, 20000) == -1);+ /* auto has no curve */+ cfg.profile = FP_AUTO;+ fan_profile_curve(&cfg, &c);+ CHECK(c.n == 0 && fan_curve_step(&c, 3, 1, 90000) == -1);+ /* always on: floor */+ cfg.profile = FP_ALWAYS;+ fan_profile_curve(&cfg, &c);+ CHECK(fan_curve_pct(&c, -1) == 40);+ CHECK(fan_curve_pct(&c, fan_curve_step(&c, 3, -1, 66000)) == 100);+ /* output clamp */+ CHECK(fan_output_pct(0) == 0 && fan_output_pct(-5) == 0 && fan_output_pct(1) == FAN_MIN_PCT);+ CHECK(fan_output_pct(60) == 60 && fan_output_pct(150) == 100);+ /* every preset is valid */+ for (int p = FP_QUIET; p <= FP_ALWAYS; p++) { cfg.profile = (FanProfile)p; fan_profile_curve(&cfg, &c); CHECK(fan_curve_valid(&c) == 0); }+ /* validity rules */+ FanCurve v = { 2, { { 50, 40 }, { 60, 30 } }, 0 };+ CHECK(fan_curve_valid(&v) != 0); /* % going down */+ v = (FanCurve){ 2, { { 60, 40 }, { 60, 50 } }, 0 };+ CHECK(fan_curve_valid(&v) != 0); /* same temperature */+ v = (FanCurve){ 1, { { 29, 40 } }, 0 };+ CHECK(fan_curve_valid(&v) != 0);+ v = (FanCurve){ 1, { { 91, 40 } }, 0 };+ CHECK(fan_curve_valid(&v) != 0);+ v = (FanCurve){ 1, { { 90, 101 } }, 0 };+ CHECK(fan_curve_valid(&v) != 0);+ v = (FanCurve){ 0, { { 0, 0 } }, 0 };+ CHECK(fan_curve_valid(&v) != 0);+ v = (FanCurve){ 9, { { 0, 0 } }, 0 };+ CHECK(fan_curve_valid(&v) != 0);+ v = (FanCurve){ 2, { { 30, 0 }, { 90, 100 } }, 0 };+ CHECK(fan_curve_valid(&v) == 0);+}++/* ---- fan.json ---- */++static int parse(const char *s, FanConfig *c) {+ fan_config_default(c, 1);+ char err[96];+ return fan_config_parse(s, strlen(s), c, err, sizeof err);+}++static void test_config(void) {+ FanConfig c;+ CHECK(parse("{}", &c) == 0 && c.profile == FP_BALANCED && c.hyst == 3);+ CHECK(parse("{\"version\":1,\"profile\":\"quiet\",\"hyst\":5}", &c) == 0 && c.profile == FP_QUIET && c.hyst == 5);+ CHECK(parse("{\"profile\":\"custom\",\"custom\":[[40,20],[50,50],[70,100]]}", &c) == 0 && c.profile == FP_CUSTOM && c.custom.n == 3 && c.custom.p[1].pct == 50);+ CHECK(parse("{\"force\":\"timed\",\"forceUntil\":1900000000}", &c) == 0 && c.force == FF_TIMED && c.force_until == 1900000000LL);+ CHECK(parse("{\"force\":\"on\",\"forceUntil\":5}", &c) == 0 && c.force == FF_ON && c.force_until == 0);+ /* round trip */+ FanConfig a;+ fan_config_default(&a, 0);+ a.profile = FP_CUSTOM; a.hyst = 4; a.force = FF_TIMED; a.force_until = 1800000000LL;+ a.custom = (FanCurve){ 4, { { 35, 0 }, { 45, 25 }, { 60, 60 }, { 85, 100 } }, 0 };+ char buf[1024];+ size_t n = fan_config_write(&a, buf, sizeof buf);+ CHECK(n > 0);+ FanConfig b;+ fan_config_default(&b, 0);+ CHECK(fan_config_parse(buf, n, &b, NULL, 0) == 0);+ CHECK(b.profile == a.profile && b.hyst == a.hyst && b.force == a.force && b.force_until == a.force_until);+ CHECK(b.custom.n == 4 && b.custom.p[3].temp == 85 && b.custom.p[2].pct == 60);+ /* broken files: each must fail and leave the defaults */+ static const char *const bad[] = {+ "", " ", "null", "[]", "1", "\"x\"", "{", "{}}", "{\"profile\":\"turbo\"}", "{\"profile\":1}",+ "{\"profile\":\"quiet\",\"profile\":\"quiet\"}", "{\"hyst\":0}", "{\"hyst\":11}", "{\"hyst\":2.5}", "{\"hyst\":\"3\"}",+ "{\"version\":2}", "{\"extra\":1}", "{\"custom\":[]}", "{\"custom\":[[50]]}", "{\"custom\":[[50,30,1]]}",+ "{\"custom\":[[50,30],[45,40]]}", "{\"custom\":[[50,30],[60,20]]}", "{\"custom\":[[20,30]]}", "{\"custom\":[[95,30]]}",+ "{\"custom\":[[50,-1]]}", "{\"custom\":[[50,101]]}", "{\"custom\":[[50.5,30]]}", "{\"custom\":[[\"50\",30]]}",+ "{\"custom\":[[30,1],[31,2],[32,3],[33,4],[34,5],[35,6],[36,7],[37,8],[38,9]]}", "{\"custom\":{}}",+ "{\"force\":\"maybe\"}", "{\"force\":\"timed\"}", "{\"force\":\"timed\",\"forceUntil\":-1}", "{\"forceUntil\":1e30}",+ "{\"forceUntil\":1.5}", "{\"profile\":\"quiet\"} x", "{\"profile\":\"qu\\u0000iet\"}",+ };+ for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {+ int r = parse(bad[i], &c);+ if (r == 0) fprintf(stderr, "accepted: %s\n", bad[i]);+ CHECK(r != 0 && c.profile == FP_BALANCED && c.custom.n == 3);+ }+ /* random bytes and truncations of a valid file never crash and never half-apply */+ unsigned seed = 12345;+ for (int i = 0; i < 4000; i++) {+ char s[160];+ size_t l = strlen(buf);+ memcpy(s, buf, l < sizeof s ? l : sizeof s - 1);+ l = l < sizeof s ? l : sizeof s - 1;+ seed = seed * 1103515245u + 12345u;+ size_t cut = (seed >> 8) % (l + 1);+ seed = seed * 1103515245u + 12345u;+ if (cut < l) s[(seed >> 8) % (cut + 1 > l ? l : cut + 1)] = (char)(seed >> 20);+ fan_config_default(&c, 1);+ if (fan_config_parse(s, cut, &c, NULL, 0) == 0) {+ FanCurve cv;+ fan_profile_curve(&c, &cv);+ CHECK(c.hyst >= FAN_HYST_MIN && c.hyst <= FAN_HYST_MAX && fan_curve_valid(&c.custom) == 0);+ } else CHECK(c.profile == FP_BALANCED);+ }+}++/* ---- requests ---- */++static int req(const char *s, FanReq *r) { return fan_req_parse(s, strlen(s), r); }++static void test_requests(void) {+ FanReq r;+ CHECK(req("STATUS", &r) == 0 && r.type == FR_STATUS);+ CHECK(req("PROFILE quiet", &r) == 0 && r.type == FR_PROFILE && r.profile == FP_QUIET);+ CHECK(req("PROFILE auto", &r) == 0 && r.profile == FP_AUTO);+ CHECK(req("CURVE 55:30,60:55,65:100", &r) == 0 && r.type == FR_CURVE && r.curve.n == 3 && r.curve.p[2].pct == 100);+ CHECK(req("FORCE on", &r) == 0 && r.force == FF_ON);+ CHECK(req("FORCE off", &r) == 0 && r.force == FF_OFF);+ CHECK(req("FORCE 30", &r) == 0 && r.force == FF_TIMED && r.minutes == 30);+ CHECK(req("FORCE 1440", &r) == 0);+ static const char *const bad[] = {+ "", "status", "STATUS ", " STATUS", "PROFILE", "PROFILE ", "PROFILE turbo", "PROFILE quiet x", "CURVE", "CURVE ",+ "CURVE 55:30,", "CURVE 55:30,,60:50", "CURVE 55-30", "CURVE 55:30,50:40", "CURVE 55:30,60:20", "CURVE 10:30",+ "CURVE 55:300", "CURVE 00055:30", "CURVE 55:30\n", "FORCE", "FORCE 0", "FORCE 1441", "FORCE -1", "FORCE 30m",+ "FORCE on ", "SET /sys/class/hwmon/hwmon0/pwm1 255", "PROFILE quiet\tx",+ "CURVE 30:1,31:2,32:3,33:4,34:5,35:6,36:7,37:8,38:9",+ };+ for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {+ int rr = req(bad[i], &r);+ if (rr == 0) fprintf(stderr, "accepted request: %s\n", bad[i]);+ CHECK(rr != 0);+ }+ char longline[FAN_REQ_MAX + 8];+ memset(longline, 'A', sizeof longline - 1);+ longline[sizeof longline - 1] = 0;+ CHECK(fan_req_parse(longline, strlen(longline), &r) != 0);+ CHECK(fan_req_parse("STATUS\0x", 8, &r) != 0);+}++/* ---- fake sysfs ---- */++static void put(const char *root, const char *rel, const char *val) {+ char p[512], d[512];+ snprintf(p, sizeof p, "%s/%s", root, rel);+ /* mkdir -p of the parent */+ snprintf(d, sizeof d, "%s", p);+ for (char *s = d + strlen(root) + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(d, 0755); *s = '/'; }+ FILE *f = fopen(p, "w");+ if (f) { fputs(val, f); fputc('\n', f); fclose(f); }+}++static void link_rel(const char *root, const char *rel, const char *target) {+ char p[512];+ snprintf(p, sizeof p, "%s/%s", root, rel);+ unlink(p);+ if (symlink(target, p)) perror(p);+}++static int get(const char *root, const char *rel) {+ char p[512], b[32] = "";+ snprintf(p, sizeof p, "%s/%s", root, rel);+ FILE *f = fopen(p, "r");+ if (!f) return -99999;+ if (!fgets(b, sizeof b, f)) b[0] = 0;+ fclose(f);+ return atoi(b);+}++/* A Raspberry Pi 5 with the fan header: cpu-thermal zone, pwm-fan cooling device bound to four+ * active trips, hwmon pwmfan with tachometer; plus an unrelated hwmon. */+static void make_pi5(const char *r, int temp_mc) {+ char t[16];+ put(r, "proc/device-tree/model", "Raspberry Pi 5 Model B Rev 1.1");+ snprintf(t, sizeof t, "%d", temp_mc);+ put(r, "sys/class/thermal/thermal_zone0/type", "cpu-thermal");+ put(r, "sys/class/thermal/thermal_zone0/temp", t);+ put(r, "sys/class/thermal/thermal_zone0/trip_point_0_type", "critical");+ put(r, "sys/class/thermal/thermal_zone0/trip_point_0_temp", "110000");+ static const int trips[] = { 50000, 60000, 67500, 75000 };+ for (int i = 0; i < 4; i++) {+ char rel[96], v[16];+ snprintf(rel, sizeof rel, "sys/class/thermal/thermal_zone0/trip_point_%d_type", i + 1);+ put(r, rel, "active");+ snprintf(rel, sizeof rel, "sys/class/thermal/thermal_zone0/trip_point_%d_temp", i + 1);+ snprintf(v, sizeof v, "%d", trips[i]);+ put(r, rel, v);+ snprintf(rel, sizeof rel, "sys/class/thermal/thermal_zone0/cdev%d_trip_point", i + 1);+ snprintf(v, sizeof v, "%d", i + 1);+ put(r, rel, v);+ snprintf(rel, sizeof rel, "sys/class/thermal/thermal_zone0/cdev%d", i + 1);+ link_rel(r, rel, "../cooling_device0");+ }+ put(r, "sys/class/thermal/cooling_device0/type", "pwm-fan");+ put(r, "sys/class/thermal/cooling_device0/max_state", "4");+ put(r, "sys/class/thermal/cooling_device0/cur_state", "0");+ put(r, "sys/class/hwmon/hwmon0/name", "cpu_thermal");+ put(r, "sys/class/hwmon/hwmon0/temp1_input", t);+ put(r, "sys/class/hwmon/hwmon2/name", "pwmfan");+ put(r, "sys/class/hwmon/hwmon2/pwm1", "0");+ put(r, "sys/class/hwmon/hwmon2/pwm1_enable", "1");+ put(r, "sys/class/hwmon/hwmon2/fan1_input", "0");+}++/* A desktop PC: k10temp, a Super I/O with two PWM headers (one with tachometer), and a GPU whose+ * fan must never be touched. */+static void make_pc(const char *r) {+ put(r, "sys/class/hwmon/hwmon0/name", "k10temp");+ put(r, "sys/class/hwmon/hwmon0/temp1_input", "48250");+ put(r, "sys/class/hwmon/hwmon1/name", "nct6798");+ put(r, "sys/class/hwmon/hwmon1/pwm1", "100");+ put(r, "sys/class/hwmon/hwmon1/pwm1_enable", "5");+ put(r, "sys/class/hwmon/hwmon1/fan1_input", "820");+ put(r, "sys/class/hwmon/hwmon1/pwm2", "80");+ put(r, "sys/class/hwmon/hwmon1/pwm2_enable", "2");+ put(r, "sys/class/hwmon/hwmon3/name", "amdgpu");+ put(r, "sys/class/hwmon/hwmon3/pwm1", "60");+ put(r, "sys/class/hwmon/hwmon3/pwm1_enable", "2");+ put(r, "sys/class/hwmon/hwmon3/fan1_input", "1100");+}++static void make_none(const char *r) {+ put(r, "sys/class/thermal/thermal_zone0/type", "acpitz");+ put(r, "sys/class/thermal/thermal_zone0/temp", "41000");+}++static void test_sysfs(void) {+ char tmpl[] = "/tmp/fan-test.XXXXXX";+ char *r = mkdtemp(tmpl);+ CHECK(r != NULL);+ if (!r) return;+ char root[64], state[96];++ /* Raspberry Pi 5 */+ snprintf(root, sizeof root, "%s/pi5", r);+ mkdir(root, 0755);+ make_pi5(root, 63000);+ snprintf(state, sizeof state, "%s/fand.restore", r);+ FanHw h;+ CHECK(fanhw_scan(&h, root) == 1);+ CHECK(h.board == 1 && h.t[0].kind == FK_BOARD && h.t[0].has_rpm && !strcmp(h.temp_src, "cpu-thermal"));+ CHECK(fanhw_temp(&h) == 63000);+ CHECK(h.ntrips == 4 && h.trip[0] == 1 && h.trip_orig[0] == 50000 && h.trip_orig[3] == 75000);+ CHECK(h.nro == 0);+ CHECK(fanhw_take(&h, state) == 1);+ CHECK(access(state, F_OK) == 0);+ CHECK(get(root, "sys/class/thermal/thermal_zone0/trip_point_1_temp") == 78000);+ CHECK(get(root, "sys/class/thermal/thermal_zone0/trip_point_4_temp") == 84000);+ CHECK(get(root, "sys/class/thermal/thermal_zone0/trip_point_0_temp") == 110000); /* critical untouched */+ /* starting a stopped fan at 30 %: kick at full speed first, then 30 % */+ CHECK(fanhw_set(&h, 0, 30) == 0 && get(root, "sys/class/hwmon/hwmon2/pwm1") == 255);+ CHECK(fanhw_set(&h, 0, 30) == 0 && get(root, "sys/class/hwmon/hwmon2/pwm1") == 77);+ CHECK(fanhw_pct(&h, 0) == 30);+ CHECK(fanhw_set(&h, 0, 100) == 0 && get(root, "sys/class/hwmon/hwmon2/pwm1") == 255);+ CHECK(fanhw_set(&h, 0, 0) == 0 && get(root, "sys/class/hwmon/hwmon2/pwm1") == 0);+ CHECK(fanhw_set(&h, 0, 60) == 0 && get(root, "sys/class/hwmon/hwmon2/pwm1") == 153); /* ≥ 50 %: no kick */+ put(root, "sys/class/hwmon/hwmon2/pwm1", "125"); /* the kernel stepped in */+ CHECK(fanhw_set(&h, 0, 60) == 0 && get(root, "sys/class/hwmon/hwmon2/pwm1") == 153);+ put(root, "sys/class/hwmon/hwmon2/fan1_input", "4120");+ CHECK(fanhw_rpm(&h, 0) == 4120);+ CHECK(fanhw_set(&h, 5, 50) == -1);+ fanhw_release(&h);+ CHECK(get(root, "sys/class/thermal/thermal_zone0/trip_point_1_temp") == 50000);+ CHECK(get(root, "sys/class/thermal/thermal_zone0/trip_point_3_temp") == 67500);+ CHECK(get(root, "sys/class/thermal/cooling_device0/cur_state") == 2); /* 63 °C: trips 50 and 60 */+ CHECK(fanhw_set(&h, 0, 50) == -1); /* not ours any more */+ /* crash: take, then restore from the notes with a fresh process */+ FanHw h2;+ fanhw_scan(&h2, root);+ fanhw_take(&h2, state);+ CHECK(get(root, "sys/class/thermal/thermal_zone0/trip_point_2_temp") == 80000);+ CHECK(fanhw_restore_file(root, state) == 0);+ CHECK(get(root, "sys/class/thermal/thermal_zone0/trip_point_2_temp") == 60000);+ CHECK(access(state, F_OK) != 0);++ /* PC */+ snprintf(root, sizeof root, "%s/pc", r);+ mkdir(root, 0755);+ make_pc(root);+ CHECK(fanhw_scan(&h, root) == 2);+ CHECK(h.board == 0 && !strcmp(h.temp_src, "k10temp") && fanhw_temp(&h) == 48250);+ CHECK(h.t[0].kind == FK_HWMON && h.t[0].ch == 1 && h.t[0].has_rpm && h.t[1].ch == 2 && !h.t[1].has_rpm);+ CHECK(h.nro == 1 && !strcmp(h.ro[0].chip, "amdgpu") && fanhw_ro_rpm(&h, 0) == 1100);+ CHECK(fanhw_take(&h, state) == 2);+ CHECK(get(root, "sys/class/hwmon/hwmon1/pwm1_enable") == 1 && get(root, "sys/class/hwmon/hwmon1/pwm2_enable") == 1);+ CHECK(get(root, "sys/class/hwmon/hwmon3/pwm1_enable") == 2); /* GPU untouched */+ fanhw_set(&h, 0, 70);+ CHECK(get(root, "sys/class/hwmon/hwmon1/pwm1") == 179);+ fanhw_release(&h);+ CHECK(get(root, "sys/class/hwmon/hwmon1/pwm1_enable") == 5 && get(root, "sys/class/hwmon/hwmon1/pwm2_enable") == 2);+ /* crash restore with notes; a tampered line is ignored */+ fanhw_scan(&h, root);+ fanhw_take(&h, state);+ FILE *f = fopen(state, "a");+ if (f) { fputs("enable 1 9 /etc\nexec /bin/sh\n", f); fclose(f); }+ fanhw_restore_file(root, state);+ CHECK(get(root, "sys/class/hwmon/hwmon1/pwm1_enable") == 5 && get(root, "sys/class/hwmon/hwmon1/pwm2_enable") == 2);++ /* nothing to drive */+ snprintf(root, sizeof root, "%s/none", r);+ mkdir(root, 0755);+ make_none(root);+ CHECK(fanhw_scan(&h, root) == 0 && h.nro == 0 && fanhw_temp(&h) == 41000 && !strcmp(h.temp_src, "thermal_zone0"));++ char cmd[128];+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", r);+ if (system(cmd)) fprintf(stderr, "cleanup failed\n");+}++int main(int argc, char **argv) {+ if (argc == 4 && !strcmp(argv[1], "mkfake")) {+ mkdir(argv[2], 0755);+ if (!strcmp(argv[3], "pi5")) make_pi5(argv[2], 58000);+ else if (!strcmp(argv[3], "pc")) make_pc(argv[2]);+ else make_none(argv[2]);+ return 0;+ }+ test_curve();+ test_config();+ test_requests();+ test_sysfs();+ printf("fan-test: %d checks, %d failed\n", checks, fails);+ return fails ? 1 : 0;+}diff --git a/server/tests/run_suites.sh b/server/tests/run_suites.shindex 0452d78..f02e608 100644--- a/server/tests/run_suites.sh+++ b/server/tests/run_suites.sh@@ -146,6 +146,7 @@ EOFrun "arcpath-test" build/arcpath-testrun "ipp-test" build/ipp-testrun "tp-test" build/tp-test+ run "fan-test" build/fan-test}full() {diff --git a/tools/rpi/build-img.sh b/tools/rpi/build-img.shindex c46ac3b..1e03e08 100755--- a/tools/rpi/build-img.sh+++ b/tools/rpi/build-img.sh@@ -13,8 +13,13 @@# emulated, and lord-server is built in a separate arm64 chroot (slow: ~15–30 min the first time).## Variables: MIRROR (Debian), RPI_MIRROR (Raspberry Pi archive), IMG_EXTRA_MB (free space in the-# image before it grows on boot, 512), RPI_SSH=1 (adds openssh-server, for development),-# RPI_KEY_NOCHECK=1 (do not verify the Raspberry Pi archive key fingerprint; not recommended).+# image before it grows on boot, 512), RPI_SSH=1 (SSH server on from the start, for development;+# otherwise it ships off and the `ssh` switch file turns it on), RPI_KEY_NOCHECK=1 (do not verify+# the Raspberry Pi archive key fingerprint; not recommended), KERNEL_DEBS (folder with the LordOS+# kernel packages from tools/rpi/build-kernel.sh, default /var/tmp/lordos-kernel/out).+#+# Kernel: the LordOS build of the Raspberry Pi kernel (with Landlock) when its .debs are in+# $KERNEL_DEBS; otherwise Raspberry Pi's archive kernel, which has no Landlock (a loud warning).set -eu[ "$(id -u)" = 0 ] || { echo "build-img.sh: run as root (sudo)" >&2; exit 1; }@@ -42,6 +47,7 @@ NAME="lordos-$VERSION-rpi5-arm64"IMG="$OUT/$NAME.img"DEB="$OUT/lordos_${VERSION}_arm64.deb"RPI="$ROOT/tools/rpi/rootfs"+KERNEL_DEBS=${KERNEL_DEBS:-/var/tmp/lordos-kernel/out}T0=$(date +%s)for t in debootstrap dpkg-deb sfdisk losetup mkfs.vfat mkfs.ext4 xz curl gpg partx; do@@ -61,20 +67,39 @@ PKGS_BASE="initramfs-tools systemd-sysv udev kmod dbus dbus-user-session sudo loPKGS_LORDOS="libwayland-server0 libxkbcommon0 xkb-data pipewire pipewire-pulse pipewire-alsa wireplumber rtkitalsa-ucm-conf wpasupplicant openvpn fonts-noto-core fonts-noto-cjk fonts-noto-color-emoji libthai-dataskkdic rime-data-pinyin-simp fonts-dejavu-core"-# Raspberry Pi: Pi 5 kernel (2712: 16K pages) and Pi 4/400/CM4 kernel (v8: 4K), boot firmware-# (start*.elf are not used on the Pi 5: its firmware lives in the EEPROM) and Wi-Fi/BT (CYW43455)-PKGS_RPI="raspi-firmware linux-image-rpi-2712 linux-image-rpi-v8 firmware-brcm80211"+# Raspberry Pi: boot firmware (start*.elf are not used on the Pi 5: its firmware lives in the+# EEPROM) and Wi-Fi/BT (CYW43455); kernels below+PKGS_RPI="raspi-firmware firmware-brcm80211 rsync"PKGS_RPI_EXTRA="rpi-eeprom raspi-utils"+# Kernels: Pi 5 (2712: 16K pages) and Pi 4/400/CM4 (v8: 4K pages). Ours (Landlock) if built,+# per flavour; otherwise Raspberry Pi's.+OWN_KDEBS=""; ARCHIVE_K=""; OWN_FLAVOURS=""+for fl in 2712 v8; do+ d=$(ls "$KERNEL_DEBS"/linux-image-*-lordos-rpi-${fl}_*_arm64.deb 2>/dev/null | sort -V | tail -1 || true)+ if [ -n "$d" ]; then OWN_KDEBS="$OWN_KDEBS $d"; OWN_FLAVOURS="$OWN_FLAVOURS $fl"+ else ARCHIVE_K="$ARCHIVE_K linux-image-rpi-$fl"; fi+done# Debian 13 Mesa: v3d (OpenGL ES 3.1 on the Pi 5), v3dv (Vulkan 1.2/1.3) and kmsro (vc4 + v3d)PKGS_GPU="libgl1-mesa-dri libegl1 libgles2 libgbm1 mesa-vulkan-drivers mesa-utils vulkan-tools glmark2-es2-wayland"PKGS_APPS="foot featherpad qt6-wayland"-PKGS_DEV=""-[ "${RPI_SSH:-0}" = 1 ] && PKGS_DEV="openssh-server"+# the SSH server ships off; the `ssh` switch file on the boot partition (rpi/firstboot) or RPI_SSH=1 turns it on+PKGS_SSH="openssh-server"# to build lord-server (only in the build chroot, not in the image)PKGS_BUILD="build-essential pkg-config libxkbcommon-dev libwayland-dev wayland-protocols libgbm-dev libegl-dev libgles-devlibssl-dev libcrypt-dev dpkg-dev file"echo "== LordOS $VERSION: Raspberry Pi image in $WORK (host $(uname -m))"+kernel_warning() {+ echo "##########################################################################################" >&2+ echo "## WARNING: no LordOS kernel for rpi-$1 in $KERNEL_DEBS: using Raspberry Pi's archive kernel." >&2+ echo "## It has NO Landlock: app and helper isolation will be seccomp-only on that board and" >&2+ echo "## doc_evil.sh / sandbox-test fail. Build it first: tools/rpi/build-kernel.sh (docs/RASPBERRY.md)." >&2+ echo "##########################################################################################" >&2+}+for fl in 2712 v8; do+ case " $OWN_FLAVOURS " in *" $fl "*) echo " kernel rpi-$fl: LordOS build ($(basename "$(ls "$KERNEL_DEBS"/linux-image-*-lordos-rpi-${fl}_*_arm64.deb | sort -V | tail -1)"))" ;;+ *) kernel_warning "$fl" ;; esac+doneumount_tree() {for d in "$CH" "$BR"; dofor m in dev/pts dev proc sys run; do mountpoint -q "$d/$m" 2>/dev/null && umount -l "$d/$m" || true; done@@ -201,8 +226,29 @@ mount_ch "$CH"echo "== paquetes"in_root "$CH" apt-get update -q > "$WORK/apt.log" 2>&1 || { tail -30 "$WORK/apt.log"; exit 1; }# shellcheck disable=SC2086-in_root "$CH" apt-get install -y -q --no-install-recommends $PKGS_BASE $PKGS_LORDOS $PKGS_RPI $PKGS_GPU $PKGS_APPS $PKGS_DEV \+in_root "$CH" apt-get install -y -q --no-install-recommends $PKGS_BASE $PKGS_LORDOS $PKGS_RPI $ARCHIVE_K $PKGS_GPU $PKGS_APPS $PKGS_SSH \>> "$WORK/apt.log" 2>&1 || { tail -30 "$WORK/apt.log"; exit 1; }+# the LordOS kernels (same hooks as Raspberry Pi's: initramfs, raspi-firmware copies kernel_2712.img,+# device trees and overlays), and an apt pin so the archive kernel of that flavour never replaces them+if [ -n "$OWN_KDEBS" ]; then+ mkdir -p "$CH/tmp/kernel"+ # shellcheck disable=SC2086+ cp $OWN_KDEBS "$CH/tmp/kernel/"+ in_root "$CH" sh -c 'apt-get install -y -q --no-install-recommends /tmp/kernel/*.deb' >> "$WORK/apt.log" 2>&1 || {+ tail -30 "$WORK/apt.log"; exit 1; }+ rm -rf "$CH/tmp/kernel"+ {+ echo "# LordOS on Raspberry Pi: the kernel is LordOS's build of the Raspberry Pi kernel (with Landlock,"+ echo "# tools/rpi/build-kernel.sh, docs/RASPBERRY.md). Raspberry Pi's kernel packages for the same"+ echo "# board are never installed over it; LordOS updates ship as new linux-image-*-lordos-rpi-* packages."+ for fl in $OWN_FLAVOURS; do+ echo+ echo "Package: linux-image-rpi-$fl linux-image-*+rpt-rpi-$fl linux-headers-rpi-$fl linux-headers-*+rpt-rpi-$fl"+ echo "Pin: version *"+ echo "Pin-Priority: -1"+ done+ } > "$CH/etc/apt/preferences.d/lordos-kernel"+fi# shellcheck disable=SC2086in_root "$CH" apt-get install -y -q --no-install-recommends $PKGS_RPI_EXTRA >> "$WORK/apt.log" 2>&1 ||echo " warning: $PKGS_RPI_EXTRA were not installed (see $WORK/apt.log)"@@ -240,6 +286,8 @@ in_root "$CH" systemctl --global enable pipewire.socket pipewire-pulse.socket wi# first boot and wait for vc4install -d "$CH/usr/lib/lordos/rpi" "$CH/etc/systemd/system/lordos.service.d"install -m 755 "$RPI/usr/lib/lordos/rpi/firstboot" "$RPI/usr/lib/lordos/rpi/wait-kms" "$CH/usr/lib/lordos/rpi/"+# the post-flash check (docs/RASPBERRY.md, "After flashing"): sudo /usr/lib/lordos/rpi/verify-board+install -m 755 "$ROOT/tools/rpi/verify-board.sh" "$CH/usr/lib/lordos/rpi/verify-board"install -m 644 "$RPI/etc/systemd/system/lordos-rpi-firstboot.service" "$CH/etc/systemd/system/"install -m 644 "$RPI/etc/systemd/system/lordos.service.d/rpi.conf" "$CH/etc/systemd/system/lordos.service.d/"mkdir -p "$CH/var/lib/lordos/rpi"@@ -255,6 +303,10 @@ in_root "$CH" usermod -p '*' rootKV2712=$(ls "$CH/boot" | sed -n 's/^vmlinuz-\(.*-rpi-2712\)$/\1/p' | sort -V | tail -1)KV8=$(ls "$CH/boot" | sed -n 's/^vmlinuz-\(.*-rpi-v8\)$/\1/p' | sort -V | tail -1)[ -n "$KV2712" ] || { echo "build-img.sh: the rpi-2712 kernel was not installed" >&2; exit 1; }+for kv in $KV2712 $KV8; do+ if grep -q '^CONFIG_SECURITY_LANDLOCK=y' "$CH/boot/config-$kv" 2>/dev/null; then echo " kernel $kv: Landlock built in"+ else echo " WARNING: kernel $kv has NO Landlock (seccomp-only isolation on that board)" >&2; fi+donein_root "$CH" update-initramfs -u -k all > /dev/null 2>&1 || trueplace_kernel() { # version, kernel name on the FAT, initramfs name[ -n "$1" ] || return 0@@ -273,8 +325,10 @@ install -m 644 "$RPI/boot/firmware/lordos-user.txt.example" "$CH/boot/firmware/lrm -f "$CH/usr/sbin/policy-rc.d" "$CH/usr/bin/qemu-aarch64-static"in_root "$CH" apt-get cleanrm -rf "$CH/var/lib/apt/lists/"* "$CH/var/cache/apt/"*.bin "$CH/tmp/"* "$CH/var/log/"*.log-rm -f "$CH/etc/ssh/ssh_host_"* # generated on first boot (if openssh-server is present)-[ "${RPI_SSH:-0}" = 1 ] && in_root "$CH" systemctl enable ssh > /dev/null 2>&1 || true+rm -f "$CH/etc/ssh/ssh_host_"* # each board creates its own on first boot (rpi/firstboot)+# SSH off unless asked for: the `ssh` switch file turns it on at boot (rpi/firstboot)+in_root "$CH" systemctl disable ssh.service ssh.socket > /dev/null 2>&1 || true+if [ "${RPI_SSH:-0}" = 1 ]; then in_root "$CH" systemctl enable ssh.service > /dev/null 2>&1 || true; fi: > "$CH/etc/resolv.conf": > "$CH/etc/machine-id"umount_ch "$CH"@@ -311,8 +365,9 @@ PARTUUID=$PARTUUID_ROOT / ext4 defaults,noatime 0 1PARTUUID=$PARTUUID_BOOT /boot/firmware vfat defaults,umask=0077 0 2EOF# lordos.gpu=0 (safe mode, everything on the CPU) and lordos.lang=en|pt can be added here, as on the ISO.-# lsm=: Landlock for app isolation (server/src/sec); those the kernel lacks are ignored.-printf 'console=serial0,115200 console=tty3 root=PARTUUID=%s rootfstype=ext4 fsck.repair=yes rootwait quiet loglevel=3 cgroup_enable=memory lsm=landlock,lockdown,yama,integrity,apparmor,bpf lordos.lang=en\n' \+# lsm=: the same list as the LordOS kernel's CONFIG_LSM (Landlock for app isolation, server/src/sec);+# those the kernel lacks are ignored, so the active list is "capability,landlock".+printf 'console=serial0,115200 console=tty3 root=PARTUUID=%s rootfstype=ext4 fsck.repair=yes rootwait quiet loglevel=3 cgroup_enable=memory lsm=landlock,lockdown,yama,integrity,bpf lordos.lang=en\n' \"$PARTUUID_ROOT" > "$WORK/mnt/boot/firmware/cmdline.txt"syncumount "$WORK/mnt/boot/firmware"diff --git a/tools/rpi/build-kernel.sh b/tools/rpi/build-kernel.shnew file mode 100644index 0000000..db0fe84--- /dev/null+++ b/tools/rpi/build-kernel.sh@@ -0,0 +1,135 @@+#!/bin/sh+# build-kernel.sh — the LordOS Raspberry Pi kernel: Raspberry Pi's own kernel source and defconfig,+# plus what LordOS needs that it lacks (Landlock). See docs/RASPBERRY.md, "The LordOS kernel".+#+# Usage (on an arm64 Debian 13, ideally the Pi itself; ~70–90 min per flavour on a Pi 5):+# tools/rpi/build-kernel.sh [work folder] [2712|v8|all] # default /var/tmp/lordos-kernel 2712+#+# Result: <work>/out/linux-image-<release>_<version>_arm64.deb (+ linux-headers-…), where+# <release> = <upstream version>-lordos-rpi-2712 (Pi 5: bcm2712_defconfig, 16K pages)+# <upstream version>-lordos-rpi-v8 (Pi 4/400/CM4: bcm2711_defconfig, 4K pages)+# The "-rpi-<flavour>" suffix is what raspi-firmware's kernel hook keys on (it copies the newest+# vmlinuz-*-rpi-2712 to kernel_2712.img and the device trees to /boot/firmware), so the package+# installs exactly like Raspberry Pi's own. tools/rpi/build-img.sh picks these .debs up from+# $KERNEL_DEBS (default /var/tmp/lordos-kernel/out).+#+# Variables: RPI_KERNEL_REPO (default the Raspberry Pi GitHub tree), RPI_KERNEL_BRANCH (rpi-6.18.y),+# RPI_KERNEL_REF (a commit to pin; default the branch head), LORDOS_KREV (package revision, 1),+# JOBS (default nproc). Building packages needs: build-essential bc bison flex libssl-dev+# libelf-dev libdw-dev dwarves cpio kmod rsync dpkg-dev debhelper git.+set -eu++WORK=${1:-/var/tmp/lordos-kernel}+FLAVOURS=${2:-2712}+REPO=${RPI_KERNEL_REPO:-https://github.com/raspberrypi/linux.git}+BRANCH=${RPI_KERNEL_BRANCH:-rpi-6.18.y}+REF=${RPI_KERNEL_REF:-}+KREV=${LORDOS_KREV:-1}+JOBS=${JOBS:-$(nproc)}+SRC="$WORK/linux"+OUT="$WORK/out"+[ "$FLAVOURS" = all ] && FLAVOURS="2712 v8"++case "$(uname -m)" in+ aarch64|arm64) CROSS="" ;;+ *) command -v aarch64-linux-gnu-gcc >/dev/null || {+ echo "build-kernel.sh: not arm64 and no aarch64-linux-gnu-gcc (gcc-aarch64-linux-gnu)" >&2; exit 1; }+ CROSS="CROSS_COMPILE=aarch64-linux-gnu-" ;;+esac+for t in git make gcc bc bison flex dpkg-deb dpkg-buildpackage dh rsync cpio; do+ command -v "$t" >/dev/null || { echo "build-kernel.sh: missing $t" >&2; exit 1; }+done++# raspi-firmware's kernel hook copies overlays/README along with the overlays and fails without it;+# Raspberry Pi's own packages ship it, `make dtbs_install` doesn't: added to the package here.+add_overlay_readme() { # .deb, kernel release+ dpkg-deb -c "$1" | grep -q "usr/lib/linux-image-$2/overlays/README\$" && return 0+ R="$WORK/repack"+ rm -rf "$R"; dpkg-deb -R "$1" "$R"+ install -m 644 "$SRC/arch/arm/boot/dts/overlays/README" "$R/usr/lib/linux-image-$2/overlays/README"+ [ -f "$R/DEBIAN/md5sums" ] && (cd "$R" && md5sum "usr/lib/linux-image-$2/overlays/README" >> DEBIAN/md5sums)+ dpkg-deb --root-owner-group -Zxz -b "$R" "$1" > /dev/null+ rm -rf "$R"+ echo " added overlays/README to $(basename "$1")"+}++mkdir -p "$WORK" "$OUT"+if [ ! -f "$SRC/Makefile" ]; then+ echo "== cloning $REPO ($BRANCH)"+ git clone --depth 1 -b "$BRANCH" "$REPO" "$SRC"+fi+if [ -n "$REF" ]; then+ git -C "$SRC" fetch --depth 1 origin "$REF"+ git -C "$SRC" checkout -q FETCH_HEAD+fi+COMMIT=$(git -C "$SRC" rev-parse HEAD)+KV=$(make -s -C "$SRC" kernelversion)+echo "== Raspberry Pi kernel $KV ($BRANCH @ ${COMMIT%"${COMMIT#????????????}"})"++for FL in $FLAVOURS; do+ case "$FL" in+ 2712) DEFCONFIG=bcm2712_defconfig ;;+ v8) DEFCONFIG=bcm2711_defconfig ;;+ *) echo "build-kernel.sh: unknown flavour $FL (2712, v8 or all)" >&2; exit 1 ;;+ esac+ B="$WORK/build-$FL"+ LV="-lordos-rpi-$FL"+ echo "== $FL: $DEFCONFIG -> $KV$LV"+ mkdir -p "$B"+ # shellcheck disable=SC2086+ make -s -C "$SRC" O="$B" ARCH=arm64 $CROSS "$DEFCONFIG"+ cp "$B/.config" "$B/config.defconfig"+ # ---- the LordOS changes (documented in docs/RASPBERRY.md; keep them in sync) ----+ # Landlock: filesystem and TCP confinement of apps (.lpk) and helpers (lord-doc, lord-media,+ # lord-maild): server/src/sec/sandbox.c. Raspberry Pi's defconfig leaves it out.+ "$SRC/scripts/config" --file "$B/.config" \+ --enable SECURITY \+ --enable SECURITYFS \+ --enable SECURITY_NETWORK \+ --enable SECURITY_PATH \+ --enable SECURITY_LANDLOCK \+ --set-str LSM "landlock,lockdown,yama,integrity,bpf" \+ --set-str LOCALVERSION "$LV" \+ --disable LOCALVERSION_AUTO+ # already in the defconfig, required by LordOS; enforced so a future defconfig can't drop them:+ # seccomp (sandbox.c), cgroup v2 + BPF (per-app limits, lord-netperm's cgroup/connect hooks)+ "$SRC/scripts/config" --file "$B/.config" \+ --enable SECCOMP --enable SECCOMP_FILTER \+ --enable CGROUPS --enable MEMCG --enable CGROUP_PIDS --enable CGROUP_SCHED \+ --enable BPF_SYSCALL --enable BPF_JIT --enable CGROUP_BPF+ # shellcheck disable=SC2086+ make -s -C "$SRC" O="$B" ARCH=arm64 $CROSS olddefconfig+ for o in SECURITY_LANDLOCK SECCOMP_FILTER CGROUP_BPF BPF_SYSCALL; do+ grep -q "^CONFIG_$o=y" "$B/.config" || { echo "build-kernel.sh: CONFIG_$o did not stick" >&2; exit 1; }+ done+ grep -q '^CONFIG_LSM="landlock' "$B/.config" || { echo "build-kernel.sh: CONFIG_LSM did not stick" >&2; exit 1; }+ # the diff against Raspberry Pi's defconfig, kept next to the packages+ diff "$B/config.defconfig" "$B/.config" > "$OUT/config-$KV$LV.diff" || true+ cp "$B/.config" "$OUT/config-$KV$LV"+ echo " config diff: $(grep -c '^[<>]' "$OUT/config-$KV$LV.diff") lines ($OUT/config-$KV$LV.diff)"++ T0=$(date +%s)+ rm -f "$WORK"/linux-*"$KV$LV"*.deb "$WORK"/linux-libc-dev_*.deb+ # bindeb-pkg leaves the .debs in the parent of the build folder ($WORK)+ # shellcheck disable=SC2086+ make -C "$SRC" O="$B" ARCH=arm64 $CROSS -j"$JOBS" \+ KDEB_PKGVERSION="$KV-$KREV+lordos" KDEB_SOURCENAME="linux-lordos-rpi-$FL" \+ KBUILD_BUILD_USER=lordos KBUILD_BUILD_HOST=lordos \+ bindeb-pkg > "$OUT/build-$FL.log" 2>&1 || { tail -40 "$OUT/build-$FL.log"; exit 1; }+ T1=$(date +%s)+ for d in "$WORK/linux-image-$KV$LV"_*.deb "$WORK/linux-headers-$KV$LV"_*.deb; do+ [ -f "$d" ] && mv "$d" "$OUT/"+ done+ rm -f "$WORK"/linux-libc-dev_*.deb "$WORK/linux-image-$KV$LV"-dbg_*.deb+ IMGDEB=$(ls "$OUT/linux-image-$KV$LV"_*.deb)+ add_overlay_readme "$IMGDEB" "$KV$LV"+ # the device trees and overlays where raspi-firmware's hook looks for them+ dpkg-deb -c "$IMGDEB" | grep -q "usr/lib/linux-image-$KV$LV/broadcom/bcm2712-rpi-5-b.dtb" ||+ { echo "build-kernel.sh: $IMGDEB has no device trees in /usr/lib/linux-image-$KV$LV/broadcom" >&2; exit 1; }+ dpkg-deb -c "$IMGDEB" | grep -q "usr/lib/linux-image-$KV$LV/overlays/.*\.dtbo" ||+ { echo "build-kernel.sh: $IMGDEB has no overlays" >&2; exit 1; }+ echo " built in $(( (T1 - T0) / 60 )) min: $(basename "$IMGDEB") ($(du -h "$IMGDEB" | cut -f1))"+done+(cd "$OUT" && sha256sum linux-*.deb > SHA256SUMS)+printf 'source=%s\nbranch=%s\ncommit=%s\nversion=%s\n' "$REPO" "$BRANCH" "$COMMIT" "$KV" > "$OUT/SOURCE"+ls -l "$OUT"/*.debdiff --git a/tools/rpi/rootfs/boot/firmware/lordos-user.txt.example b/tools/rpi/rootfs/boot/firmware/lordos-user.txt.exampleindex 7526ae7..35259f3 100644--- a/tools/rpi/rootfs/boot/firmware/lordos-user.txt.example+++ b/tools/rpi/rootfs/boot/firmware/lordos-user.txt.example@@ -17,3 +17,12 @@ lang=entimezone=America/Argentina/Buenos_Aireskeyboard=latamkeyboard_variant=+# Wi-Fi (optional): saved like Settings → Network does, joined at boot. Leave wifi_password empty+# for an open network. wifi_country (two letters) unlocks the country's 5 GHz channels from the+# second boot on. Without Wi-Fi, plug in an Ethernet cable (DHCP).+#wifi_ssid=MyNetwork+#wifi_password=+#wifi_country=AR+#+# Remote desktop and SSH are not set here: create an empty file named «remote-desktop» (and/or+# «ssh») on this partition. See docs/RASPBERRY.md, "Switch files".diff --git a/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot b/tools/rpi/rootfs/usr/lib/lordos/rpi/firstbootindex 7842802..e9fe9a2 100755--- a/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot+++ b/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot@@ -14,6 +14,15 @@# 3. On every boot in setup mode: if there is already a person administrator account# besides `lordos`, `lordos` (and its passwordless sudo) is removed and the system switches to the# login screen.+# 4. On every boot: the switch files on the boot partition, like Raspberry Pi OS's `ssh` file.+# Each one is applied, logged and deleted (docs/RASPBERRY.md, "Switch files"):+# - `ssh` (or `ssh.txt`): turns the SSH server on (if the image ships it) and keeps it on.+# - `remote-desktop` (or `remote-desktop.txt`; empty, or `port=<1024..65535>` and/or+# `allow=all|group`): turns LordOS remote desktop on, in the same file Settings → Sharing+# writes (/etc/lordos/remote/config, read by lord-sessiond when lordos.service starts).+# Logging in still needs an account with a password: while there is none (setup mode) the+# file is kept and applied on a later boot.+# Every boot also creates missing SSH host keys (the image ships none).set -uSTATE=/var/lib/lordos/rpiBOOT=/boot/firmware@@ -88,6 +97,41 @@ user_dirs() { # user folders by language, like Settings' user-addfor d in "$@"; do install -d -o "$u" -g "$u" "$h/$d"; done}+# ---- Wi-Fi from lordos-user.txt (wifi_ssid=, wifi_password=, wifi_country=) ----+# Saved exactly as Settings → Network saves a network (lord-netd, server/src/net/wifi.c):+# /etc/lordos/net/wifi/<ssid in hex>.json (public) and <ssid in hex>.key (0600). lord-netd loads the+# saved networks into wpa_supplicant when it brings Wi-Fi up at boot (DHCP, no NetworkManager).+NET_WIFI=/etc/lordos/net/wifi+json_esc() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; }+wifi_from() {+ WS=$(kv wifi_ssid "$1"); WP=$(kv wifi_password "$1"); WC=$(kv wifi_country "$1")+ [ -n "$WS" ] || return 0+ WL=$(printf '%s' "$WS" | wc -c); PL=$(printf '%s' "$WP" | wc -c)+ if [ "$WL" -gt 32 ] || printf '%s' "$WS" | LC_ALL=C grep -q '[[:cntrl:]]'; then+ log "$(basename "$1"): wifi_ssid is longer than 32 bytes or has control characters: Wi-Fi not saved"+ elif [ -n "$WP" ] && { [ "$PL" -lt 8 ] || [ "$PL" -gt 128 ] || printf '%s' "$WP" | LC_ALL=C grep -q '[[:cntrl:]]'; }; then+ log "$(basename "$1"): wifi_password must be 8–128 characters: Wi-Fi not saved"+ else+ SH=$(printf '%s' "$WS" | od -An -v -tx1 | tr -d ' \n')+ install -d -m 755 /etc/lordos/net "$NET_WIFI"+ if [ -n "$WP" ]; then SEC=psk; else SEC=open; fi+ printf '{"ssid":"%s","security":"%s"}\n' "$(json_esc "$WS")" "$SEC" > "$NET_WIFI/$SH.json"+ chmod 644 "$NET_WIFI/$SH.json"+ (umask 077; printf 'pass=%s\n' "$WP" > "$NET_WIFI/$SH.key")+ log "Wi-Fi network saved: $WS ($SEC)"+ fi+ # regulatory domain (5 GHz channels): kernel option, takes effect from the next boot+ if [ -n "$WC" ]; then+ WC=$(echo "$WC" | tr '[:lower:]' '[:upper:]')+ if echo "$WC" | grep -Eq '^[A-Z]{2}$' && [ -f "$BOOT/cmdline.txt" ]; then+ sed -i -e 's/ *cfg80211\.ieee80211_regdom=[A-Z0-9]*//g' -e "1s/\$/ cfg80211.ieee80211_regdom=$WC/" "$BOOT/cmdline.txt"+ log "Wi-Fi country $WC (cmdline.txt, from the next boot)"+ else+ log "$(basename "$1"): wifi_country must be a two-letter code (AR, US, DE…)"+ fi+ fi+}+# ---- 2. first boot: the user ----if [ -e "$STATE/firstboot-pending" ]; thenF=""@@ -100,6 +144,7 @@ if [ -e "$STATE/firstboot-pending" ]; thenHASH=$(kv password_hash "$F"); PASS=$(kv password "$F"); HOST=$(kv hostname "$F")L=$(kv lang "$F"); case "$L" in es|en|pt) LANG_UI=$L ;; esacTZ_=$(kv timezone "$F"); KB=$(kv keyboard "$F"); KBV=$(kv keyboard_variant "$F")+ wifi_from "$F"elif [ -f "$BOOT/userconf.txt" ]; thenF="$BOOT/userconf.txt"LINE=$(head -1 "$F" | tr -d '\r')@@ -164,4 +209,76 @@ if [ -e "$STATE/setup-mode" ]; thenrm -f "$STATE/setup-mode"fifi++# ---- 4. switch files on the boot partition ----+# SSH host keys: the image ships none (each board gets its own); created on the first boot that+# has the SSH server installed.+if [ -x /usr/sbin/sshd ] && ! ls /etc/ssh/ssh_host_*_key >/dev/null 2>&1; then+ if ssh-keygen -A >/dev/null 2>&1; then log "SSH host keys created"; else log "ssh-keygen -A failed"; fi+fi++consume() { # overwrites and deletes a switch file (it can hold a password)+ dd if=/dev/zero of="$1" bs=1 count="$(stat -c %s "$1")" conv=notrunc 2>/dev/null || true+ rm -f "$1"+ sync+}++for S in "$BOOT/ssh" "$BOOT/ssh.txt"; do+ [ -e "$S" ] || continue+ if [ -x /usr/sbin/sshd ]; then+ # enable for the following boots; --no-block: this unit runs inside the boot transaction+ systemctl enable ssh.service >/dev/null 2>&1 || true+ systemctl start --no-block ssh.service >/dev/null 2>&1 || true+ log "$(basename "$S"): SSH server turned on (password logins need an account with a password; root is locked)"+ else+ log "$(basename "$S"): this image has no SSH server (openssh-server): ignored"+ fi+ consume "$S"+done++has_login_account() { # a person account (uid 1000–59999) with a real password: remote login refuses the rest+ getent passwd | awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }' | while read -r u; do+ [ "$u" = "$SETUP_USER" ] && continue+ getent shadow "$u" | cut -d: -f2 | grep -q '^\$' && echo "$u"+ done | grep -q .+}++RD_DIR=/etc/lordos/remote+for S in "$BOOT/remote-desktop" "$BOOT/remote-desktop.txt"; do+ [ -e "$S" ] || continue+ N=$(basename "$S")+ if [ -e "$STATE/setup-mode" ] || ! has_login_account; then+ log "$N: kept until an account with a password exists (lordos-user.txt, or Settings → Users and a reboot)"+ continue+ fi+ # the current values (Settings → Sharing may have saved some), then the file's+ PORT=5673; ALLOW=all; DEV=0+ if [ -f "$RD_DIR/config" ]; then+ v=$(kv port "$RD_DIR/config"); [ -n "$v" ] && PORT=$v+ v=$(kv allow "$RD_DIR/config"); [ "$v" = group ] && ALLOW=group+ v=$(kv insecure_dev "$RD_DIR/config"); [ "$v" = 1 ] && DEV=1+ fi+ v=$(kv port "$S")+ if [ -n "$v" ]; then+ if echo "$v" | grep -Eq '^[0-9]{4,5}$' && [ "$v" -ge 1024 ] && [ "$v" -le 65535 ]; then PORT=$v+ else log "$N: port=$v is not 1024–65535: using $PORT"; fi+ fi+ v=$(kv allow "$S")+ case "$v" in+ '') ;;+ all|group) ALLOW=$v ;;+ *) log "$N: allow=$v is not all or group: using $ALLOW" ;;+ esac+ if [ "$ALLOW" = group ] && ! getent group lordos-remote >/dev/null; then+ groupadd --system lordos-remote 2>/dev/null || true+ fi+ install -d -m 755 /etc/lordos "$RD_DIR"+ # the same file and format as remote-enable/remote-config (server/src/remote/remote_admin.c)+ printf '# LordOS · remote desktop (Settings → Sharing). See docs/REMOTE.md\nenabled=1\nport=%s\nallow=%s\ninsecure_dev=%s\n' \+ "$PORT" "$ALLOW" "$DEV" > "$RD_DIR/config.lordos"+ chmod 644 "$RD_DIR/config.lordos"+ mv -f "$RD_DIR/config.lordos" "$RD_DIR/config"+ log "$N: remote desktop on, port $PORT, allow=$ALLOW (https://<this board's IP>:$PORT; log in with your account)"+ consume "$S"+doneexit 0diff --git a/tools/rpi/verify-board.sh b/tools/rpi/verify-board.shnew file mode 100644index 0000000..b009223--- /dev/null+++ b/tools/rpi/verify-board.sh@@ -0,0 +1,194 @@+#!/bin/sh+# verify-board.sh — checks a Raspberry Pi freshly flashed with the LordOS image and prints a+# PASS/FAIL table. See docs/RASPBERRY.md, "After flashing".+#+# Usage, on the board (as root, or with sudo, so the kernel log and listening sockets are visible):+# sudo sh verify-board.sh # system checks only (nothing to install)+# sudo sh verify-board.sh --repo ~/LordOS # also builds the tree and runs make -C server test-full+# # (needs the build packages of "Developing on the board")+#+# It changes nothing on the system: it only reads /sys, /proc, the kernel log and the configs, and+# with --repo builds inside that tree as the user who owns it. Exit status: 0 if nothing failed.+set -u++REPO=""+while [ $# -gt 0 ]; do+ case "$1" in+ --repo) REPO=${2:-}; shift 2 ;;+ -h|--help) sed -n '2,12p' "$0"; exit 0 ;;+ *) echo "verify-board.sh: unknown option $1" >&2; exit 2 ;;+ esac+done++PASS=0; FAIL=0; WARN=0+ROWS=""+row() { # status, check, detail+ case "$1" in PASS) PASS=$((PASS + 1)) ;; FAIL) FAIL=$((FAIL + 1)) ;; *) WARN=$((WARN + 1)) ;; esac+ ROWS="$ROWS$(printf '%-5s | %-26s | %s' "$1" "$2" "$3")+"+}+[ "$(id -u)" = 0 ] || echo "verify-board.sh: not root: some checks (kernel log, sockets) may show WARN" >&2++# ---- board and kernel ----+MODEL=$(tr -d '\0' < /proc/device-tree/model 2>/dev/null || echo unknown)+KREL=$(uname -r)+row INFO "board" "$MODEL"+case "$KREL" in+ *-lordos-rpi-*) row PASS "kernel (LordOS build)" "$KREL" ;;+ *) row FAIL "kernel (LordOS build)" "$KREL is not a -lordos-rpi-* kernel (Raspberry Pi's has no Landlock)" ;;+esac+PS=$(getconf PAGESIZE 2>/dev/null || echo ?)+case "$KREL:$PS" in+ *-rpi-2712:16384|*-rpi-v8:4096) row PASS "page size" "$PS bytes" ;;+ *) row WARN "page size" "$PS bytes for $KREL" ;;+esac++# ---- Landlock and the rest of the isolation ----+LSM=$(cat /sys/kernel/security/lsm 2>/dev/null || echo "")+case ",$LSM," in+ *,landlock,*) row PASS "Landlock in the LSM list" "$LSM" ;;+ *) row FAIL "Landlock in the LSM list" "/sys/kernel/security/lsm = '${LSM:-unreadable}'" ;;+esac+KLOG=$( (dmesg 2>/dev/null || journalctl -k -b --no-pager 2>/dev/null) | grep -i 'landlock' | head -1)+if echo "$KLOG" | grep -qi 'up and running'; then row PASS "Landlock initialized" "$(echo "$KLOG" | sed 's/^.*\] //')"+elif [ -z "$KLOG" ]; then row WARN "Landlock initialized" "no landlock line in the kernel log$([ "$(id -u)" = 0 ] || echo " (run as root)")"+else row FAIL "Landlock initialized" "$KLOG"; fi+CFG=/boot/config-$KREL+if [ -f "$CFG" ]; then+ MISS=""+ for o in SECURITY_LANDLOCK SECCOMP_FILTER CGROUP_BPF BPF_SYSCALL MEMCG; do+ grep -q "^CONFIG_$o=y" "$CFG" || MISS="$MISS $o"+ done+ if [ -z "$MISS" ]; then row PASS "kernel config" "LANDLOCK SECCOMP_FILTER CGROUP_BPF BPF_SYSCALL MEMCG"+ else row FAIL "kernel config" "missing:$MISS"; fi+fi+grep -q '^Seccomp:' /proc/self/status && row PASS "seccomp" "available" || row FAIL "seccomp" "no Seccomp field in /proc/self/status"+CTRL=$(cat /sys/fs/cgroup/cgroup.controllers 2>/dev/null || echo "")+case " $CTRL " in+ *" memory "*) row PASS "cgroup v2 memory" "controllers: $CTRL" ;;+ *) row FAIL "cgroup v2 memory" "controllers: '${CTRL}' (cmdline.txt needs cgroup_enable=memory)" ;;+esac++# ---- first boot ----+DF=$(df -h / | awk 'NR == 2 { print $2 " (" $5 " used)" }')+if [ -e /var/lib/lordos/rpi/resize-pending ]; then row FAIL "root partition grown" "resize still pending: $DF"+else row PASS "root partition grown" "$DF"; fi+LEFT=""+for f in ssh ssh.txt remote-desktop remote-desktop.txt lordos-user.txt userconf.txt; do+ [ -e "/boot/firmware/$f" ] && LEFT="$LEFT $f"+done+if [ -z "$LEFT" ]; then row PASS "switch files consumed" "none left on /boot/firmware"+else row WARN "switch files consumed" "still there:$LEFT (remote-desktop waits for an account with a password)"; fi+if [ -e /var/lib/lordos/rpi/setup-mode ]; then row WARN "user account" "setup mode (create your account in Settings → Users)"+else row PASS "user account" "first-boot user created (login screen)"; fi++# ---- display and GPU ----+CONN=""+for s in /sys/class/drm/card*-*/status; do+ [ -f "$s" ] || continue+ c=$(basename "$(dirname "$s")")+ st=$(cat "$s")+ m=$(head -1 "$(dirname "$s")/modes" 2>/dev/null)+ CONN="$CONN ${c#card?-}=$st${m:+@$m}"+done+if echo "$CONN" | grep -q '=connected'; then row PASS "KMS outputs" "${CONN# }"+elif [ -n "$CONN" ]; then row WARN "KMS outputs" "nothing connected:${CONN}"+else row FAIL "KMS outputs" "no DRM connectors (vc4 not loaded? dtoverlay=vc4-kms-v3d)"; fi+DRV=""+for d in /sys/class/drm/card?; do+ [ -e "$d/device/driver" ] && DRV="$DRV $(basename "$d")=$(basename "$(readlink "$d/device/driver")")"+done+row INFO "DRM cards" "${DRV# }"+if command -v eglinfo >/dev/null; then+ R=$(eglinfo -B -p gbm 2>/dev/null | grep -m1 -i 'renderer' | sed 's/^[^:]*: *//')+ if echo "$R" | grep -q 'V3D'; then row PASS "GPU (EGL on GBM)" "$R"+ else row FAIL "GPU (EGL on GBM)" "renderer: '${R:-none}'"; fi+else row WARN "GPU (EGL on GBM)" "eglinfo missing (mesa-utils)"; fi+SLOG=$(ls -t /home/*/.cache/lordos/session.log 2>/dev/null | head -1)+if [ -n "$SLOG" ]; then+ G=$(grep -m1 'gpu:' "$SLOG" | sed 's/^.*gpu: //')+ if echo "$G" | grep -q 'GPU composition'; then row PASS "LordOS GPU composition" "$G"+ else row WARN "LordOS GPU composition" "${G:-no gpu: line} ($SLOG)"; fi+fi++# ---- fan and temperature ----+FAN=""+for h in /sys/class/hwmon/hwmon*; do+ n=$(cat "$h/name" 2>/dev/null)+ case "$n" in *fan*) FAN="$n"; [ -f "$h/fan1_input" ] && FAN="$FAN $(cat "$h/fan1_input") rpm"+ [ -f "$h/pwm1" ] && FAN="$FAN, pwm $(cat "$h/pwm1")/255" ;; esac+done+if [ -n "$FAN" ]; then row PASS "fan detected" "$FAN"+else row WARN "fan detected" "no fan hwmon (no Active Cooler or case fan connected?)"; fi+if systemctl list-unit-files lord-fand.service >/dev/null 2>&1 && systemctl cat lord-fand.service >/dev/null 2>&1; then+ if systemctl is-active -q lord-fand.service; then row PASS "lord-fand" "active"+ else row FAIL "lord-fand" "$(systemctl is-active lord-fand.service)"; fi+fi+T=$(cat /sys/class/thermal/thermal_zone0/temp 2>/dev/null || echo 0)+TC=$((T / 1000))+if [ "$TC" -gt 0 ] && [ "$TC" -lt 75 ]; then row PASS "SoC temperature" "${TC} °C"+elif [ "$TC" -ge 75 ]; then row FAIL "SoC temperature" "${TC} °C (≥ 75 °C idle: check the cooling)"+else row WARN "SoC temperature" "unreadable"; fi+if command -v vcgencmd >/dev/null; then+ TH=$(vcgencmd get_throttled 2>/dev/null | sed 's/^throttled=//')+ if [ "$TH" = 0x0 ]; then row PASS "throttling" "throttled=0x0"+ else row WARN "throttling" "throttled=$TH (under-voltage or heat; 0x50000 = happened before)"; fi+fi++# ---- remote desktop: listening on its port only when enabled ----+RC=/etc/lordos/remote/config+EN=0; PORT=5673+if [ -f "$RC" ]; then+ EN=$(sed -n 's/^enabled=//p' "$RC" | head -1); PORT=$(sed -n 's/^port=//p' "$RC" | head -1)+fi+[ -n "$PORT" ] || PORT=5673+LIST=$(ss -Hltn 2>/dev/null | awk '{ print $4 }' | grep -E "[:.]$PORT\$" | head -1)+if [ "$EN" = 1 ]; then+ if [ -n "$LIST" ]; then row PASS "remote desktop" "enabled, listening on $LIST (https, login required)"+ else row FAIL "remote desktop" "enabled in $RC but nothing listens on $PORT"; fi+else+ if [ -z "$LIST" ]; then row PASS "remote desktop" "off, port $PORT closed"+ else row FAIL "remote desktop" "off in config but $LIST is listening"; fi+fi+if systemctl is-enabled -q ssh.service 2>/dev/null; then+ if systemctl is-active -q ssh.service; then row INFO "SSH server" "on (ssh switch file or RPI_SSH=1)"+ else row FAIL "SSH server" "enabled but $(systemctl is-active ssh.service)"; fi+else row INFO "SSH server" "off"; fi+if systemctl is-active -q lordos.service; then row PASS "lordos.service" "active"+else row FAIL "lordos.service" "$(systemctl is-active lordos.service)"; fi++# ---- the test suites (optional: needs the tree and the build packages) ----+if [ -n "$REPO" ]; then+ if [ ! -f "$REPO/server/Makefile" ]; then row FAIL "test-full" "$REPO is not a LordOS tree"+ else+ OWNER=$(stat -c %U "$REPO")+ LOG=/tmp/lordos-verify-tests.log+ run() { if [ "$(id -u)" = 0 ] && [ "$OWNER" != root ]; then su "$OWNER" -s /bin/sh -c "$1"; else sh -c "$1"; fi; }+ echo "verify-board.sh: building and running make -C server test-full as $OWNER (log $LOG)…" >&2+ if run "cd '$REPO' && make -C server -j$(nproc) && make -C server test-full" > "$LOG" 2>&1; then+ row PASS "make -C server test-full" "$(grep -E '[0-9]+ passed' "$LOG" | tail -1)"+ else+ row FAIL "make -C server test-full" "$(grep -E '[0-9]+ passed|FAIL|fail' "$LOG" | tail -1) (see $LOG)"+ fi+ # doc_evil.sh on its own: run_suites.sh only shows its output when it fails+ run "cd '$REPO/server' && sh tests/doc_evil.sh" > "$LOG.doc" 2>&1+ DE=$(grep -m1 '^doc-evil: ' "$LOG.doc" | sed 's/^doc-evil: //')+ if [ -z "$DE" ]; then row FAIL "doc_evil.sh" "did not run (see $LOG.doc)"+ elif [ "${DE%/*}" = "${DE#*/}" ]; then row PASS "doc_evil.sh" "$DE"+ else row FAIL "doc_evil.sh" "$DE (see $LOG.doc)"; fi+ SB=$(grep -c '^ ok *sandbox-test' "$LOG")+ if grep -q 'skipped sandbox-test' "$LOG"; then row FAIL "sandbox-test" "skipped (no Landlock)"+ elif [ "$SB" -ge 3 ]; then row PASS "sandbox-test" "app, app net, helper: ok"+ else row FAIL "sandbox-test" "$SB/3 ok (see $LOG)"; fi+ fi+else+ row INFO "test-full" "not run (pass --repo <LordOS tree> with the build packages installed)"+fi++echo+printf '%-5s | %-26s | %s\n' RESULT CHECK DETAIL+echo "------+----------------------------+--------------------------------------------------------------"+printf '%s' "$ROWS"+echo+echo "PASS $PASS · FAIL $FAIL · WARN/INFO $WARN"+[ "$FAIL" = 0 ]