Skip to content

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

Settings: "Browsers: tabs in the title bar" switch

Federico Pereirab5044b1ee075
diff --git a/apps/settings/BrowserFrame.jsx b/apps/settings/BrowserFrame.jsx
new file mode 100644
index 0000000..e0da39c
--- /dev/null
+++ b/apps/settings/BrowserFrame.jsx
@@ -0,0 +1,47 @@
+// Settings → Appearance → "Browsers: tabs in the title bar" (docs/WAYLAND.md, "The switch in
+// Settings"). On: Chromium and Firefox draw one bar with their tabs and LordOS's window buttons;
+// off: they use LordOS's frame. The SDK (sdk/browserframe.js) writes that one preference in the
+// user's own browser profiles through lord.browserFrame.
+import { View, Button, Toggle, useLocale, useSettings, useStore, browserFrameResult, browserFrameState, browserTabsInTitlebar, setBrowserTabsInTitlebar } from '@lordos/sdk';
+import { useEffect, useState } from 'react';
+import { Section, SettingRow, Note, Actions } from './ui.jsx';
+
+// What the last change did, as notes under the switch.
+function ResultNotes({ r, pending }) {
+ const { t: tr } = useLocale();
+ if (!r) return null;
+ const failed = (r.chromium?.failed | 0) + (r.firefox?.failed | 0);
+ const out = [];
+ if (pending) out.push(<Note key="open" tone="warn">{tr('settings.browserTabs.chromiumOpen')}</Note>);
+ if (failed) out.push(<Note key="failed" tone="error">{tr('settings.browserTabs.failed', { count: failed })}</Note>);
+ if (r.firefox?.kept) out.push(<Note key="kept">{tr('settings.browserTabs.firefoxKept')}</Note>);
+ if (!pending && !failed && (r.chromium?.changed || r.firefox?.changed)) out.push(<Note key="ok" tone="ok">{tr('settings.browserTabs.done')}</Note>);
+ return out.length ? out : null;
+}
+
+export function BrowserFrameSettings() {
+ const { t: tr } = useLocale();
+ const [s] = useSettings();
+ const on = browserTabsInTitlebar(s);
+ const result = useStore(browserFrameResult);
+ // Chromium profiles that don't follow the switch (made before 0.8.4, or changed in Chromium)
+ const [state, setState] = useState(null);
+ useEffect(() => { setState(browserFrameState()); }, [on, result]);
+ const other = state ? (on ? state.off : state.on) : 0;
+ const pick = (v) => setBrowserTabsInTitlebar(v);
+ return (
+ <View style={{ gap: 6 }}>
+ <Section footer={tr('settings.browserTabs.hint')}>
+ <SettingRow label={tr('settings.browserTabs.label')}>
+ <Toggle small on={on} onChange={pick} />
+ </SettingRow>
+ {other > 0 && !s.browserFramePending ? (
+ <SettingRow label={tr(on ? 'settings.browserTabs.othersOff' : 'settings.browserTabs.othersOn', { count: other })}>
+ <Actions><Button label={tr('settings.browserTabs.applyAll')} onClick={() => pick(on)} /></Actions>
+ </SettingRow>
+ ) : null}
+ </Section>
+ <ResultNotes r={result} pending={!!s.browserFramePending} />
+ </View>
+ );
+}
diff --git a/apps/settings/index.jsx b/apps/settings/index.jsx
index dfb1779..c165ed8 100644
--- a/apps/settings/index.jsx
+++ b/apps/settings/index.jsx
@@ -18,6 +18,7 @@ import { PrivacySettings } from './Privacy.jsx';
import { PrintersSettings } from './Printers.jsx';
import { TrackpadSettings } from './Trackpad.jsx';
import { DockSettings } from './Dock.jsx';
+import { BrowserFrameSettings } from './BrowserFrame.jsx';
// hardware pages (docs/SETTINGS.md)
import { DisplaysSettings } from './Displays.jsx';
import { BluetoothSettings } from './Bluetooth.jsx';
@@ -194,6 +195,7 @@ function Appearance() {
options={[['auto', tr('settings.scrollBarsAuto')], ['scrolling', tr('settings.scrollBarsScrolling')], ['always', tr('settings.scrollBarsAlways')]]} />
</SettingRow>
</Section>
+ <BrowserFrameSettings />
</Stack>
);
}
diff --git a/assets/locales/en/settings.json b/assets/locales/en/settings.json
index 2f7e16a..1c566ec 100644
--- a/assets/locales/en/settings.json
+++ b/assets/locales/en/settings.json
@@ -5,6 +5,24 @@
"admin.system-locale": "System region",
"admin.timezone": "Time zone",
"admin.unavailable": "The admin helper is not running: lord-server must start with sudo and the user must be in the sudo group.",
+ "browserTabs.label": "Browsers: tabs in the title bar",
+ "browserTabs.hint": "On: Chromium and Firefox draw a single bar with their tabs and LordOS's window buttons. Off: they use the LordOS frame. It changes your browser profiles and applies the next time each browser opens.",
+ "browserTabs.chromiumOpen": "Chromium is open: its profiles change as soon as you quit it.",
+ "browserTabs.failed": {
+ "one": "{count} browser profile could not be changed and was left as it was.",
+ "other": "{count} browser profiles could not be changed and were left as they were."
+ },
+ "browserTabs.firefoxKept": "A Firefox profile sets this in its own user.js file, so it was left alone.",
+ "browserTabs.done": "Done. The browsers use it the next time they open.",
+ "browserTabs.othersOff": {
+ "one": "{count} Chromium profile still uses the LordOS frame",
+ "other": "{count} Chromium profiles still use the LordOS frame"
+ },
+ "browserTabs.othersOn": {
+ "one": "{count} Chromium profile still draws its own bar",
+ "other": "{count} Chromium profiles still draw their own bar"
+ },
+ "browserTabs.applyAll": "Change them",
"change": "Change…",
"clipboard.add": "Add",
"clipboard.appId": "app id",
@@ -55,7 +73,7 @@
"kb.test": "Test keyboard",
"kb.testHint": "Type here: ñ, accents (´ + vowel), ç, AltGr…",
"kb.use": "Use",
- "keywords.appearance": "dark light mode accent transparency",
+ "keywords.appearance": "dark light mode accent transparency browser tabs title bar frame",
"keywords.clipboard": "copy paste history copied",
"keywords.general": "about computer system version processor memory disk",
"keywords.keyboard": "layout input method japanese chinese korean",
diff --git a/assets/locales/es/settings.json b/assets/locales/es/settings.json
index da10d4b..2daa142 100644
--- a/assets/locales/es/settings.json
+++ b/assets/locales/es/settings.json
@@ -5,6 +5,24 @@
"admin.system-locale": "Región del sistema",
"admin.timezone": "Zona horaria",
"admin.unavailable": "El ayudante de administración no está activo: lord-server tiene que arrancar con sudo y el usuario estar en el grupo sudo.",
+ "browserTabs.label": "Navegadores: pestañas en la barra de título",
+ "browserTabs.hint": "Activado: Chromium y Firefox dibujan una sola barra con sus pestañas y los botones de ventana de LordOS. Desactivado: usan el marco de LordOS. Cambia tus perfiles de navegador y se aplica la próxima vez que se abre cada navegador.",
+ "browserTabs.chromiumOpen": "Chromium está abierto: sus perfiles cambian en cuanto lo cierres.",
+ "browserTabs.failed": {
+ "one": "No se pudo cambiar {count} perfil de navegador y quedó como estaba.",
+ "other": "No se pudieron cambiar {count} perfiles de navegador y quedaron como estaban."
+ },
+ "browserTabs.firefoxKept": "Un perfil de Firefox lo define en su propio archivo user.js, así que no se tocó.",
+ "browserTabs.done": "Listo. Los navegadores lo usan la próxima vez que se abren.",
+ "browserTabs.othersOff": {
+ "one": "{count} perfil de Chromium todavía usa el marco de LordOS",
+ "other": "{count} perfiles de Chromium todavía usan el marco de LordOS"
+ },
+ "browserTabs.othersOn": {
+ "one": "{count} perfil de Chromium todavía dibuja su propia barra",
+ "other": "{count} perfiles de Chromium todavía dibujan su propia barra"
+ },
+ "browserTabs.applyAll": "Cambiarlos",
"change": "Cambiar…",
"clipboard.add": "Agregar",
"clipboard.appId": "id de la app",
@@ -55,7 +73,7 @@
"kb.test": "Probar teclado",
"kb.testHint": "Escribí acá: ñ, tildes (´ + vocal), ç, AltGr…",
"kb.use": "Usar",
- "keywords.appearance": "modo oscuro claro acento transparencia",
+ "keywords.appearance": "modo oscuro claro acento transparencia navegador pestañas barra de título marco",
"keywords.clipboard": "copiar pegar historial copiado",
"keywords.general": "acerca equipo sistema versión procesador memoria disco",
"keywords.keyboard": "distribución método de entrada japonés chino coreano",
diff --git a/assets/locales/pt/settings.json b/assets/locales/pt/settings.json
index 019014f..6d832b3 100644
--- a/assets/locales/pt/settings.json
+++ b/assets/locales/pt/settings.json
@@ -5,6 +5,24 @@
"admin.system-locale": "Região do sistema",
"admin.timezone": "Fuso horário",
"admin.unavailable": "O assistente de administração não está ativo: o lord-server deve iniciar com sudo e o usuário estar no grupo sudo.",
+ "browserTabs.label": "Navegadores: abas na barra de título",
+ "browserTabs.hint": "Ativado: o Chromium e o Firefox desenham uma única barra com suas abas e os botões de janela do LordOS. Desativado: usam a moldura do LordOS. Altera seus perfis de navegador e vale na próxima vez que cada navegador abrir.",
+ "browserTabs.chromiumOpen": "O Chromium está aberto: seus perfis mudam assim que você o fechar.",
+ "browserTabs.failed": {
+ "one": "Não foi possível alterar {count} perfil de navegador, que ficou como estava.",
+ "other": "Não foi possível alterar {count} perfis de navegador, que ficaram como estavam."
+ },
+ "browserTabs.firefoxKept": "Um perfil do Firefox define isso no seu próprio arquivo user.js, então não foi alterado.",
+ "browserTabs.done": "Pronto. Os navegadores usam isso na próxima vez que abrirem.",
+ "browserTabs.othersOff": {
+ "one": "{count} perfil do Chromium ainda usa a moldura do LordOS",
+ "other": "{count} perfis do Chromium ainda usam a moldura do LordOS"
+ },
+ "browserTabs.othersOn": {
+ "one": "{count} perfil do Chromium ainda desenha sua própria barra",
+ "other": "{count} perfis do Chromium ainda desenham sua própria barra"
+ },
+ "browserTabs.applyAll": "Alterá-los",
"change": "Alterar…",
"clipboard.add": "Adicionar",
"clipboard.appId": "id do app",
@@ -55,7 +73,7 @@
"kb.test": "Testar teclado",
"kb.testHint": "Digite aqui: ñ, acentos (´ + vogal), ç, AltGr…",
"kb.use": "Usar",
- "keywords.appearance": "modo escuro claro destaque transparência",
+ "keywords.appearance": "modo escuro claro destaque transparência navegador abas barra de título moldura",
"keywords.clipboard": "copiar colar histórico copiado",
"keywords.general": "sobre computador sistema versão processador memória disco",
"keywords.keyboard": "layout método de entrada japonês chinês coreano",
diff --git a/sdk/browserframe.js b/sdk/browserframe.js
new file mode 100644
index 0000000..32e7c73
--- /dev/null
+++ b/sdk/browserframe.js
@@ -0,0 +1,56 @@
+// browserframe.js — Settings → Appearance → "Browsers: tabs in the title bar" (docs/WAYLAND.md,
+// "The switch in Settings"). On (the default): the preinstalled Chromium and Firefox draw one bar
+// with their tabs and LordOS's window buttons. Off: they use LordOS's frame.
+//
+// lord.browserFrame (server/src/hw/brframe.c) writes that one preference in the user's own
+// profiles, and only when the switch is turned (never at login on its own):
+// - Chromium: Preferences, only while Chromium is closed. If it is open, the change waits in
+// settings.browserFramePending and is applied as soon as Chromium quits (checked every 5 s
+// while pending, and at login);
+// - Firefox: a line in user.js, read the next time Firefox opens; at login lord.browserFrame.tidy()
+// removes it again once Firefox has read it, so a later choice in Firefox's own settings sticks.
+import { settings } from './settings.js';
+import { createStore } from './store.js';
+
+// The last result of lord.browserFrame.apply: { chromium: {...}, firefox: {...} } counts, or null.
+export const browserFrameResult = createStore(null);
+
+const api = () => typeof lord !== 'undefined' && lord.browserFrame;
+
+export const browserTabsInTitlebar = (s = settings.get()) => s.browserTabsInTitlebar !== false;
+
+let timer = 0;
+function retryChromium() {
+ clearTimeout(timer);
+ if (!api() || !settings.get().browserFramePending) return;
+ if (lord.browserFrame.chromiumRunning()) { timer = setTimeout(retryChromium, 5000); return; }
+ const r = lord.browserFrame.apply(browserTabsInTitlebar(), 'chromium');
+ if (r) browserFrameResult.set((cur) => ({ ...(cur || {}), chromium: r.chromium }));
+ if (r && r.chromium.running) timer = setTimeout(retryChromium, 5000); // reopened meanwhile
+ else settings.set({ browserFramePending: false });
+}
+
+export function setBrowserTabsInTitlebar(on) {
+ settings.set({ browserTabsInTitlebar: !!on });
+ if (!api()) return;
+ const r = lord.browserFrame.apply(!!on, 'all');
+ browserFrameResult.set(r);
+ settings.set({ browserFramePending: !!r?.chromium?.running });
+ retryChromium();
+}
+
+// Chromium profiles whose own setting doesn't match the switch (made before 0.8.4, or changed in
+// Chromium): { on, off } or null.
+export function browserFrameState() {
+ if (!api()) return null;
+ const s = lord.browserFrame.state();
+ return s ? { on: s.chromiumOn | 0, off: s.chromiumOff | 0 } : null;
+}
+
+export function startBrowserFrame() {
+ if (!api()) return;
+ setTimeout(() => {
+ lord.browserFrame.tidy();
+ retryChromium();
+ }, 2000);
+}
diff --git a/sdk/index.js b/sdk/index.js
index 876e321..6c80922 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -38,6 +38,8 @@ import { EmojiPanel } from './emoji.jsx';
export { admin } from './admin.js';
export { videoPrefs, setVideoPrefs, videoHardware, videoError, videoOptimizing, VIDEO_MODES, VIDEO_DEFAULTS } from './video.js'; // docs/VIDEO.md
import { startVideo } from './video.js';
+export { browserFrameResult, browserFrameState, browserTabsInTitlebar, setBrowserTabsInTitlebar } from './browserframe.js'; // docs/WAYLAND.md
+import { startBrowserFrame } from './browserframe.js';
export { errorText, statusText, codeError, parseCode } from './errors.js';
export { logs } from './logs.js';
export { LordOSLogo, LordOSGlyph, LordOSWordmark } from './logo.js';
@@ -193,6 +195,7 @@ export function startShell(element) {
startHardware(); // Night Light, idle timers, battery in the menu bar (hardware.jsx)
startDiskWatch(); // notices when a disk gets too hot or its health gets worse
startVideo(); // browser video without hardware decoding (video.js, docs/VIDEO.md)
+ startBrowserFrame(); // "Browsers: tabs in the title bar" left for Chromium to quit (browserframe.js)
setTimeout(reportRefusedCode, 800); // "This LordOS component was modified and was not loaded" (docs/SIGNING.md)
}
diff --git a/sdk/settings.js b/sdk/settings.js
index 116065c..6db8552 100644
--- a/sdk/settings.js
+++ b/sdk/settings.js
@@ -7,6 +7,8 @@ const DEFAULTS = {
accent: 'azul',
effects: true, // transparency with blur
reduceMotion: false, // decorative animations off (Settings → Appearance)
+ browserTabsInTitlebar: true, // 0.8.4, Settings → Appearance: Chromium and Firefox draw their own bar (browserframe.js)
+ browserFramePending: false, // that switch is still waiting for Chromium to quit
scrollBars: 'auto', // 0.8.3, Settings → Appearance → Show scroll bars: 'auto' | 'scrolling' | 'always'
wallpaper: DEFAULT_WALLPAPER, // 0.8.2: Lumo Celestial (before: 'aurora', still available)
keyboard: 'latam', // before M5; now keyboards (see keyboard.js)
diff --git a/server/mk/settings.mk b/server/mk/settings.mk
index 9c708c0..b341938 100644
--- a/server/mk/settings.mk
+++ b/server/mk/settings.mk
@@ -2,7 +2,7 @@
# 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/hw/hwscan.c src/ui/js_hw.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/hw/hwscan.c src/hw/brframe.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.h
HW_OBJ := $(HW_SRC:src/%.c=build/obj/%.o)
@@ -29,3 +29,11 @@ build/hwscan-test: tests/hwscan_test.c src/hw/hwscan.c src/hw/jbuf.c src/sec/jso
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/hwscan_test.c src/hw/hwscan.c src/hw/jbuf.c src/sec/json.c
./$@ || { rm -f $@; exit 1; }
+# Settings → Appearance → "Browsers: tabs in the title bar" (brframe.c): Chromium's Preferences edit
+# (malformed JSON, missing keys, theme extensions, idempotence), Firefox's user.js line and tidy,
+# running browsers, missing and hostile profile folders, over fake homes
+test: build/brframe-test
+build/brframe-test: tests/brframe_test.c src/hw/brframe.c src/hw/jbuf.c src/sec/json.c $(HW_HDR)
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/brframe_test.c src/hw/brframe.c src/hw/jbuf.c src/sec/json.c
+ ./$@ || { rm -f $@; exit 1; }
diff --git a/server/src/hw/brframe.c b/server/src/hw/brframe.c
new file mode 100644
index 0000000..51730b9
--- /dev/null
+++ b/server/src/hw/brframe.c
@@ -0,0 +1,625 @@
+/* brframe.c — the browsers' own title bar preference in the user's profiles (see brframe.h). */
+#include "brframe.h"
+#include "jbuf.h"
+#include "../sec/json.h"
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define PREFS_MAX (32u * 1024 * 1024) /* Chromium's Preferences */
+#define USERJS_MAX (1024u * 1024) /* Firefox's user.js */
+#define FFPREFS_MAX (16u * 1024 * 1024) /* Firefox's prefs.js */
+#define INI_MAX (64u * 1024) /* profiles.ini */
+#define MAX_PROFILES 64
+
+#define FF_PREF "browser.tabs.inTitlebar"
+#define FF_MARK "// lordos: Settings > Appearance" /* i18n-ok: a marker in a config file */
+
+/* ---- JSON: just enough scanning to find a member's value span (the text was validated with
+ * json_parse first, and the result is validated again) ---- */
+
+static size_t sk_ws(const char *s, size_t n, size_t i) {
+ while (i < n && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r')) i++;
+ return i;
+}
+
+/* s[i] == '"': the index after the closing quote, 0 if unterminated */
+static size_t sk_str(const char *s, size_t n, size_t i) {
+ for (i++; i < n; i++) {
+ if (s[i] == '\\') { i++; continue; }
+ if (s[i] == '"') return i + 1;
+ }
+ return 0;
+}
+
+/* the index after the value at s[i], 0 if it isn't one */
+static size_t sk_val(const char *s, size_t n, size_t i, int depth) {
+ if (i >= n || depth > 64) return 0;
+ if (s[i] == '"') return sk_str(s, n, i);
+ if (s[i] == '{' || s[i] == '[') {
+ int obj = s[i] == '{';
+ char close = obj ? '}' : ']';
+ i = sk_ws(s, n, i + 1);
+ if (i < n && s[i] == close) return i + 1;
+ for (;;) {
+ if (obj) {
+ if (i >= n || s[i] != '"' || !(i = sk_str(s, n, i))) return 0;
+ i = sk_ws(s, n, i);
+ if (i >= n || s[i] != ':') return 0;
+ i = sk_ws(s, n, i + 1);
+ }
+ if (!(i = sk_val(s, n, i, depth + 1))) return 0;
+ i = sk_ws(s, n, i);
+ if (i < n && s[i] == ',') { i = sk_ws(s, n, i + 1); continue; }
+ if (i < n && s[i] == close) return i + 1;
+ return 0;
+ }
+ }
+ size_t st = i;
+ while (i < n && ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= '0' && s[i] <= '9') || s[i] == '-' || s[i] == '+' ||
+ s[i] == '.' || s[i] == 'E')) i++;
+ return i > st ? i : 0;
+}
+
+/* The member `key` (compared byte for byte) of the object at s[o] == '{'. 1 found (value in
+ * [*vs, *ve)), 0 missing, -1 malformed. *empty: the object has no members. */
+static int find_member(const char *s, size_t n, size_t o, const char *key, size_t *vs, size_t *ve, int *empty) {
+ size_t kl = strlen(key);
+ size_t i = sk_ws(s, n, o + 1);
+ *empty = i < n && s[i] == '}';
+ if (*empty) return 0;
+ for (;;) {
+ if (i >= n || s[i] != '"') return -1;
+ size_t ke = sk_str(s, n, i);
+ if (!ke) return -1;
+ int match = ke - i - 2 == kl && !memcmp(s + i + 1, key, kl);
+ i = sk_ws(s, n, ke);
+ if (i >= n || s[i] != ':') return -1;
+ i = sk_ws(s, n, i + 1);
+ size_t e = sk_val(s, n, i, 1);
+ if (!e) return -1;
+ if (match) { *vs = i; *ve = e; return 1; }
+ i = sk_ws(s, n, e);
+ if (i < n && s[i] == ',') { i = sk_ws(s, n, i + 1); continue; }
+ if (i < n && s[i] == '}') return 0;
+ return -1;
+ }
+}
+
+/* *b[from, to) replaced with text. */
+static int text_splice(char **b, size_t *bn, size_t from, size_t to, const char *text) {
+ size_t tl = strlen(text), nn = *bn - (to - from) + tl;
+ char *p = malloc(nn + 1);
+ if (!p) return BRF_BAD;
+ memcpy(p, *b, from);
+ memcpy(p + from, text, tl);
+ memcpy(p + from + tl, *b + to, *bn - to);
+ p[nn] = 0;
+ free(*b);
+ *b = p;
+ *bn = nn;
+ return BRF_CHANGED;
+}
+
+/* keys[0].keys[1]… = lit (a JSON literal): replaced if present, otherwise inserted as the first
+ * member of the deepest object that exists. */
+static int set_path(char **b, size_t *bn, const char *const *keys, int nk, const char *lit) {
+ const char *s = *b;
+ size_t n = *bn, o = sk_ws(s, n, 0);
+ if (o >= n || s[o] != '{') return BRF_BAD;
+ for (int k = 0; k < nk; k++) {
+ size_t vs = 0, ve = 0;
+ int empty, f = find_member(s, n, o, keys[k], &vs, &ve, &empty);
+ if (f < 0) return BRF_BAD;
+ if (f == 1) {
+ if (k == nk - 1) {
+ size_t ll = strlen(lit);
+ if (ve - vs == ll && !memcmp(s + vs, lit, ll)) return BRF_SAME;
+ return text_splice(b, bn, vs, ve, lit);
+ }
+ if (s[vs] != '{') return BRF_BAD; /* not an object: don't guess */
+ o = vs;
+ continue;
+ }
+ HBuf h = {0};
+ for (int j = k; j < nk; j++) hb_printf(&h, "\"%s\":%s", keys[j], j == nk - 1 ? lit : "{");
+ for (int j = k; j < nk - 1; j++) hb_printf(&h, "}");
+ if (!empty) hb_printf(&h, ",");
+ char *ins = hb_take(&h);
+ if (!ins) return BRF_BAD;
+ int r = text_splice(b, bn, o + 1, o + 1, ins);
+ free(ins);
+ return r;
+ }
+ return BRF_BAD;
+}
+
+int brf_chrome_edit(const char *in, size_t n, int on, char **out, size_t *outn) {
+ *out = NULL;
+ *outn = 0;
+ on = !!on;
+ if (!in || !n || n > PREFS_MAX) return BRF_BAD;
+ JDoc d;
+ if (json_parse(in, n, &d, NULL, 0)) return BRF_BAD;
+ int ok = d.root && d.root->type == J_OBJ;
+ const JVal *ext = ok ? json_get(d.root, "extensions") : NULL, *th = ext ? json_get(ext, "theme") : NULL;
+ const char *tid = th ? json_str(th, "id") : NULL;
+ int theme_ext = tid && tid[0]; /* a theme extension the user installed: kept */
+ json_free(&d);
+ if (!ok) return BRF_BAD;
+
+ char *b = malloc(n + 1);
+ if (!b) return BRF_BAD;
+ memcpy(b, in, n);
+ b[n] = 0;
+ size_t bn = n;
+ static const char *const frame[] = { "browser", "custom_chrome_frame" };
+ static const char *const theme[] = { "extensions", "theme", "system_theme" };
+ int r = set_path(&b, &bn, frame, 2, on ? "true" : "false"), changed = r == BRF_CHANGED;
+ if (r != BRF_BAD && on && !theme_ext) {
+ r = set_path(&b, &bn, theme, 3, "1");
+ changed |= r == BRF_CHANGED;
+ }
+ if (r == BRF_BAD || !changed) { free(b); return r == BRF_BAD ? BRF_BAD : BRF_SAME; }
+
+ /* the result must parse and say what was asked */
+ if (json_parse(b, bn, &d, NULL, 0)) { free(b); return BRF_BAD; }
+ const JVal *br = json_get(d.root, "browser"), *ccf = br ? json_get(br, "custom_chrome_frame") : NULL;
+ ok = ccf && ccf->type == J_BOOL && (int)ccf->num == on;
+ json_free(&d);
+ if (!ok) { free(b); return BRF_BAD; }
+ *out = b;
+ *outn = bn;
+ return BRF_CHANGED;
+}
+
+/* ---- Firefox's user.js / prefs.js lines ---- */
+
+/* Is the line l[0..n) a user_pref of FF_PREF? *val its value (0/1; true/false too), *ours if marked. */
+static int ff_line(const char *l, size_t n, int *val, int *ours) {
+ size_t i = 0, kl = strlen(FF_PREF);
+ while (i < n && (l[i] == ' ' || l[i] == '\t')) i++;
+ static const char up[] = "user_pref(";
+ if (n - i < sizeof up - 1 || memcmp(l + i, up, sizeof up - 1)) return 0;
+ i += sizeof up - 1;
+ while (i < n && (l[i] == ' ' || l[i] == '\t')) i++;
+ if (i >= n || (l[i] != '"' && l[i] != '\'')) return 0;
+ char q = l[i++];
+ if (n - i < kl + 1 || memcmp(l + i, FF_PREF, kl) || l[i + kl] != q) return 0;
+ i += kl + 1;
+ while (i < n && (l[i] == ' ' || l[i] == '\t')) i++;
+ if (i >= n || l[i] != ',') return 0;
+ i++;
+ while (i < n && (l[i] == ' ' || l[i] == '\t')) i++;
+ *val = -1;
+ if (i < n && l[i] >= '0' && l[i] <= '9') *val = l[i] != '0';
+ else if (n - i >= 4 && !memcmp(l + i, "true", 4)) *val = 1;
+ else if (n - i >= 5 && !memcmp(l + i, "false", 5)) *val = 0;
+ *ours = memmem(l, n, FF_MARK, strlen(FF_MARK)) != NULL;
+ return 1;
+}
+
+int brf_prefs_value(const char *in, size_t n) {
+ int v = -1;
+ for (size_t i = 0; i < n;) {
+ const char *e = memchr(in + i, '\n', n - i);
+ size_t len = e ? (size_t)(e - (in + i)) : n - i;
+ int val, ours;
+ if (ff_line(in + i, len, &val, &ours) && val >= 0) v = val;
+ i += len + 1;
+ }
+ return v;
+}
+
+int brf_userjs_ours(const char *in, size_t n) {
+ int v = -1;
+ for (size_t i = 0; i < n;) {
+ const char *e = memchr(in + i, '\n', n - i);
+ size_t len = e ? (size_t)(e - (in + i)) : n - i;
+ int val, ours;
+ if (ff_line(in + i, len, &val, &ours) && ours) v = val;
+ i += len + 1;
+ }
+ return v;
+}
+
+int brf_userjs_edit(const char *in, size_t n, int value, char **out, size_t *outn, int *own) {
+ *out = NULL;
+ *outn = 0;
+ *own = 0;
+ if (n > USERJS_MAX || (n && !in) || memchr(in ? in : "", 0, n)) return BRF_BAD;
+ HBuf h = {0};
+ for (size_t i = 0; i < n;) {
+ const char *e = memchr(in + i, '\n', n - i);
+ size_t len = e ? (size_t)(e - (in + i)) : n - i;
+ int val, ours;
+ if (ff_line(in + i, len, &val, &ours)) {
+ if (!ours) { *own = 1; free(h.p); return BRF_SAME; } /* the user's own line: theirs */
+ } else {
+ hb_printf(&h, "%.*s%s", (int)len, in + i, e ? "\n" : "");
+ }
+ i += len + 1;
+ }
+ if (value >= 0) {
+ if (h.n && h.p[h.n - 1] != '\n') hb_printf(&h, "\n");
+ hb_printf(&h, "user_pref(\"%s\", %d); %s, removed once Firefox has read it\n", FF_PREF, !!value, FF_MARK);
+ }
+ if (h.oom) { free(h.p); return BRF_BAD; }
+ size_t hn = h.n;
+ char *res = hb_take(&h);
+ if (!res && hn) return BRF_BAD;
+ if (hn == n && (!n || !memcmp(res, in, n))) { free(res); return BRF_SAME; }
+ if (!res) { res = strdup(""); if (!res) return BRF_BAD; }
+ *out = res;
+ *outn = hn;
+ return BRF_CHANGED;
+}
+
+/* ---- files ---- */
+
+/* name in dfd: a regular file owned by the user, at most max bytes, opened without following
+ * links. NULL (errno ENOENT if it doesn't exist). */
+static char *read_at(int dfd, const char *name, size_t max, size_t *len, struct stat *st) {
+ *len = 0;
+ int fd = openat(dfd, name, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
+ if (fd < 0) return NULL;
+ struct stat s;
+ if (fstat(fd, &s) || !S_ISREG(s.st_mode) || s.st_uid != getuid() || (size_t)s.st_size > max) {
+ close(fd);
+ errno = EINVAL;
+ return NULL;
+ }
+ char *b = malloc((size_t)s.st_size + 1);
+ size_t got = 0;
+ while (b && got < (size_t)s.st_size) {
+ ssize_t r = read(fd, b + got, (size_t)s.st_size - got);
+ if (r < 0 && errno == EINTR) continue;
+ if (r <= 0) break;
+ got += (size_t)r;
+ }
+ close(fd);
+ if (!b || got != (size_t)s.st_size) { free(b); errno = EIO; return NULL; }
+ b[got] = 0;
+ *len = got;
+ if (st) *st = s;
+ return b;
+}
+
+/* Atomic replace of name in dfd: a new file next to it (O_EXCL, never through a link), synced,
+ * then renamed over it. */
+static int write_at(int dfd, const char *name, const char *data, size_t len, mode_t mode) {
+ char tmp[256];
+ if ((size_t)snprintf(tmp, sizeof tmp, "%s.lordos-tmp", name) >= sizeof tmp) return -1;
+ unlinkat(dfd, tmp, 0);
+ int fd = openat(dfd, tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600);
+ if (fd < 0) return -1;
+ int ok = fchmod(fd, mode & 0777) == 0;
+ for (size_t put = 0; ok && put < len;) {
+ ssize_t w = write(fd, data + put, len - put);
+ if (w < 0 && errno == EINTR) continue;
+ if (w <= 0) ok = 0;
+ else put += (size_t)w;
+ }
+ ok = ok && fsync(fd) == 0;
+ ok = close(fd) == 0 && ok;
+ if (!ok || renameat(dfd, tmp, dfd, name)) { unlinkat(dfd, tmp, 0); return -1; }
+ fsync(dfd);
+ return 0;
+}
+
+/* base/sub as a folder owned by the user (base itself may be a link the user made). */
+static int open_root(const char *base, const char *sub) {
+ char p[4096];
+ if (!base || base[0] != '/' || (size_t)snprintf(p, sizeof p, "%s/%s", base, sub) >= sizeof p) return -1;
+ int fd = open(p, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ struct stat st;
+ if (fd >= 0 && (fstat(fd, &st) || st.st_uid != getuid())) { close(fd); fd = -1; }
+ return fd;
+}
+
+/* Is pid one of the user's processes whose name starts with one of names? */
+static int pid_is(long pid, const char *const *names) {
+ char p[64], comm[64];
+ struct stat st;
+ if (pid <= 1) return 0;
+ snprintf(p, sizeof p, "/proc/%ld", pid);
+ if (stat(p, &st) || st.st_uid != getuid()) return 0;
+ snprintf(p, sizeof p, "/proc/%ld/comm", pid);
+ int fd = open(p, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) return 0;
+ ssize_t k = read(fd, comm, sizeof comm - 1);
+ close(fd);
+ if (k <= 0) return 0;
+ comm[k] = 0;
+ comm[strcspn(comm, "\n")] = 0;
+ for (; *names; names++) if (!strncmp(comm, *names, strlen(*names))) return 1;
+ return 0;
+}
+
+static const char *const CHROMIUM_NAMES[] = { "chromium", "chrome", NULL };
+static const char *const FIREFOX_NAMES[] = { "firefox", "GeckoMain", NULL };
+
+/* Chromium's SingletonLock is a link to "<host>-<pid>". Anything unexpected counts as running. */
+static int chromium_locked(int dfd) {
+ char t[300], host[256];
+ ssize_t k = readlinkat(dfd, "SingletonLock", t, sizeof t - 1);
+ if (k < 0) return errno == ENOENT ? 0 : 1;
+ t[k] = 0;
+ char *dash = strrchr(t, '-'), *e;
+ if (!dash || gethostname(host, sizeof host)) return 1;
+ host[sizeof host - 1] = 0;
+ if ((size_t)(dash - t) != strlen(host) || memcmp(t, host, (size_t)(dash - t))) return 1; /* another computer */
+ long pid = strtol(dash + 1, &e, 10);
+ if (*e || pid <= 0) return 1;
+ return pid_is(pid, CHROMIUM_NAMES); /* a dead or unrelated pid: a stale lock */
+}
+
+int brf_chromium_running(const char *cfg) {
+ int dfd = open_root(cfg, "chromium");
+ if (dfd < 0) return 0;
+ int r = chromium_locked(dfd);
+ close(dfd);
+ return r;
+}
+
+/* A Firefox profile is open: a lock on .parentlock, or the "lock" link "<ip>:+<pid>" of a live Firefox. */
+static int ff_locked(int pfd) {
+ int fd = openat(pfd, ".parentlock", O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
+ if (fd >= 0) {
+ struct flock fl = { .l_type = F_WRLCK, .l_whence = SEEK_SET };
+ int r = fcntl(fd, F_GETLK, &fl);
+ close(fd);
+ if (!r && fl.l_type != F_UNLCK) return 1;
+ }
+ char t[128], *e;
+ ssize_t k = readlinkat(pfd, "lock", t, sizeof t - 1);
+ if (k > 0) {
+ t[k] = 0;
+ char *plus = strrchr(t, '+');
+ if (plus) {
+ long pid = strtol(plus + 1, &e, 10);
+ if (!*e && pid_is(pid, FIREFOX_NAMES)) return 1;
+ }
+ }
+ return 0;
+}
+
+static int chromium_profile_name(const char *n) {
+ if (!strcmp(n, "Default")) return 1;
+ if (strncmp(n, "Profile ", 8) || !n[8] || strlen(n) > 12) return 0;
+ for (const char *p = n + 8; *p; p++) if (*p < '0' || *p > '9') return 0;
+ return 1;
+}
+
+static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
+
+/* The profile folder names under Chromium's folder (Default, Profile N), sorted; malloc'd. */
+static int chromium_profiles(int dfd, char **names) {
+ int dup_fd = dup(dfd), nn = 0;
+ DIR *d = dup_fd >= 0 ? fdopendir(dup_fd) : NULL;
+ if (!d) { if (dup_fd >= 0) close(dup_fd); return -1; }
+ for (struct dirent *de; nn < MAX_PROFILES && (de = readdir(d));)
+ if (chromium_profile_name(de->d_name) && (names[nn] = strdup(de->d_name))) nn++;
+ closedir(d);
+ qsort(names, (size_t)nn, sizeof *names, cmp_str);
+ return nn;
+}
+
+void brf_chromium_apply(const char *cfg, int on, BrfResult *r) {
+ memset(r, 0, sizeof *r);
+ int dfd = open_root(cfg, "chromium");
+ if (dfd < 0) return;
+ r->found = 1;
+ if (chromium_locked(dfd)) { r->running = 1; close(dfd); return; }
+ char *names[MAX_PROFILES];
+ int nn = chromium_profiles(dfd, names);
+ if (nn < 0) { r->failed++; close(dfd); return; }
+ for (int i = 0; i < nn; i++) {
+ int pfd = r->running ? -1 : openat(dfd, names[i], O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
+ free(names[i]);
+ if (pfd < 0) continue;
+ struct stat st;
+ size_t n;
+ char *data = read_at(pfd, "Preferences", PREFS_MAX, &n, &st), *out = NULL;
+ if (!data) {
+ if (errno != ENOENT) { r->profiles++; r->failed++; } /* no Preferences yet: not a profile in use */
+ close(pfd);
+ continue;
+ }
+ r->profiles++;
+ size_t on_n;
+ int e = brf_chrome_edit(data, n, on, &out, &on_n);
+ if (e == BRF_BAD) r->failed++;
+ else if (e == BRF_SAME) r->unchanged++;
+ else if (chromium_locked(dfd)) r->running = 1; /* it started meanwhile: later */
+ else if (write_at(pfd, "Preferences.lordos-backup", data, n, st.st_mode) ||
+ write_at(pfd, "Preferences", out, on_n, st.st_mode)) r->failed++;
+ else r->changed++;
+ free(out);
+ free(data);
+ close(pfd);
+ }
+ close(dfd);
+}
+
+void brf_chromium_state(const char *cfg, int *on, int *off) {
+ *on = *off = 0;
+ int dfd = open_root(cfg, "chromium");
+ if (dfd < 0) return;
+ char *names[MAX_PROFILES];
+ int nn = chromium_profiles(dfd, names);
+ for (int i = 0; i < nn; i++) {
+ int pfd = openat(dfd, names[i], O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
+ free(names[i]);
+ if (pfd < 0) continue;
+ size_t n;
+ char *data = read_at(pfd, "Preferences", PREFS_MAX, &n, NULL);
+ close(pfd);
+ JDoc d;
+ if (!data || json_parse(data, n, &d, NULL, 0)) { free(data); continue; }
+ const JVal *b = json_get(d.root, "browser"), *f = b ? json_get(b, "custom_chrome_frame") : NULL;
+ if (f && f->type == J_BOOL) { if (f->num) (*on)++; else (*off)++; }
+ json_free(&d);
+ free(data);
+ }
+ close(dfd);
+}
+
+/* ---- Firefox profiles ---- */
+
+typedef void (*FfFn)(int pfd, void *ctx);
+
+static int ff_path_ok(const char *p) {
+ size_t n = strlen(p);
+ if (!n || n > 200 || !strcmp(p, ".") || !strcmp(p, "..")) return 0;
+ for (size_t i = 0; i < n; i++) if ((unsigned char)p[i] < 0x20 || p[i] == '/' || p[i] == 0x7f) return 0;
+ return 1;
+}
+
+/* Every relative profile listed in each root's profiles.ini, once. Returns how many roots exist. */
+static int ff_each(const char *cfg, const char *home, FfFn fn, void *ctx) {
+ char roots[2][64];
+ const char *base[2] = { cfg, home };
+ snprintf(roots[0], sizeof roots[0], "mozilla/firefox");
+ snprintf(roots[1], sizeof roots[1], ".mozilla/firefox");
+ dev_t devs[MAX_PROFILES];
+ ino_t inos[MAX_PROFILES];
+ int seen = 0, found = 0;
+ for (int ri = 0; ri < 2; ri++) {
+ int rfd = open_root(base[ri], roots[ri]);
+ if (rfd < 0) continue;
+ found++;
+ size_t n;
+ char *ini = read_at(rfd, "profiles.ini", INI_MAX, &n, NULL);
+ char path[256] = "";
+ int in_profile = 0, relative = 0;
+ for (size_t i = 0; ini && i <= n;) {
+ const char *e = i < n ? memchr(ini + i, '\n', n - i) : NULL;
+ size_t len = i >= n ? 0 : e ? (size_t)(e - (ini + i)) : n - i;
+ char line[300];
+ int end = i >= n; /* one more pass to flush the last section */
+ if (!end) {
+ size_t l = len < sizeof line - 1 ? len : sizeof line - 1;
+ memcpy(line, ini + i, l);
+ line[l] = 0;
+ line[strcspn(line, "\r")] = 0;
+ }
+ if (end || line[0] == '[') {
+ if (in_profile && relative && ff_path_ok(path) && seen < MAX_PROFILES) {
+ int pfd = openat(rfd, path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
+ struct stat st;
+ if (pfd >= 0 && !fstat(pfd, &st) && st.st_uid == getuid()) {
+ int dup_seen = 0;
+ for (int k = 0; k < seen; k++) if (devs[k] == st.st_dev && inos[k] == st.st_ino) dup_seen = 1;
+ if (!dup_seen) { devs[seen] = st.st_dev; inos[seen] = st.st_ino; seen++; fn(pfd, ctx); }
+ }
+ if (pfd >= 0) close(pfd);
+ }
+ if (end) break;
+ in_profile = !strncmp(line, "[Profile", 8);
+ relative = 0;
+ path[0] = 0;
+ } else if (in_profile && !strncmp(line, "Path=", 5) && strlen(line + 5) < sizeof path) {
+ snprintf(path, sizeof path, "%s", line + 5);
+ } else if (in_profile && !strncmp(line, "IsRelative=", 11)) {
+ relative = !strcmp(line + 11, "1");
+ }
+ i = e ? i + len + 1 : n;
+ }
+ free(ini);
+ close(rfd);
+ }
+ return found;
+}
+
+typedef struct { BrfResult *r; int value; } FfApply;
+
+static void ff_apply_one(int pfd, void *ctx) {
+ FfApply *a = ctx;
+ BrfResult *r = a->r;
+ r->profiles++;
+ int open_now = ff_locked(pfd);
+ struct stat st;
+ size_t n = 0, outn;
+ char *u = read_at(pfd, "user.js", USERJS_MAX, &n, &st), *out = NULL;
+ if (!u && errno != ENOENT) { r->failed++; return; }
+ int existed = u != NULL, own;
+ int e = brf_userjs_edit(u ? u : "", n, a->value, &out, &outn, &own);
+ if (own) r->kept++;
+ else if (e == BRF_BAD) r->failed++;
+ else if (e == BRF_SAME) r->unchanged++;
+ else {
+ /* no line needed when prefs.js already holds the value and there was none of ours */
+ size_t pn;
+ char *p = brf_userjs_ours(u ? u : "", n) < 0 ? read_at(pfd, "prefs.js", FFPREFS_MAX, &pn, NULL) : NULL;
+ if (p && brf_prefs_value(p, pn) == a->value) r->unchanged++;
+ else if ((existed && n && write_at(pfd, "user.js.lordos-backup", u, n, st.st_mode)) ||
+ write_at(pfd, "user.js", out, outn, existed ? st.st_mode : 0600)) r->failed++;
+ else { r->changed++; if (open_now) r->running++; }
+ free(p);
+ }
+ free(out);
+ free(u);
+}
+
+void brf_firefox_apply(const char *cfg, const char *home, int on, BrfResult *r) {
+ memset(r, 0, sizeof *r);
+ FfApply a = { r, !!on };
+ r->found = ff_each(cfg, home, ff_apply_one, &a) > 0;
+}
+
+static int newer(const struct timespec *a, const struct timespec *b) {
+ return a->tv_sec > b->tv_sec || (a->tv_sec == b->tv_sec && a->tv_nsec > b->tv_nsec);
+}
+
+/* Has Firefox started this profile since t? Firefox makes the "lock" link and .parentlock when it
+ * opens a profile (and leaves them when it quits), so their times are its last start. prefs.js is
+ * no proof: Firefox also writes it when it quits, after a line written while it ran. */
+static int ff_started_after(int pfd, const struct timespec *t) {
+ struct stat st;
+ if (!fstatat(pfd, "lock", &st, AT_SYMLINK_NOFOLLOW) && newer(&st.st_mtim, t)) return 1;
+ return !fstatat(pfd, ".parentlock", &st, AT_SYMLINK_NOFOLLOW) && S_ISREG(st.st_mode) && newer(&st.st_mtim, t);
+}
+
+static void ff_tidy_one(int pfd, void *ctx) {
+ int *removed = ctx;
+ struct stat us;
+ size_t n, outn;
+ char *u = read_at(pfd, "user.js", USERJS_MAX, &n, &us), *out = NULL;
+ if (!u) return;
+ int own;
+ if (brf_userjs_ours(u, n) >= 0 && !ff_locked(pfd) && ff_started_after(pfd, &us.st_mtim) &&
+ brf_userjs_edit(u, n, -1, &out, &outn, &own) == BRF_CHANGED) {
+ /* Firefox has started with the line since it was written: the value is its own now */
+ if (outn ? !write_at(pfd, "user.js", out, outn, us.st_mode) : !unlinkat(pfd, "user.js", 0)) (*removed)++;
+ }
+ free(out);
+ free(u);
+}
+
+int brf_firefox_tidy(const char *cfg, const char *home) {
+ int removed = 0;
+ ff_each(cfg, home, ff_tidy_one, &removed);
+ return removed;
+}
+
+static void put_result(HBuf *h, const char *name, const BrfResult *r) {
+ hb_printf(h, "\"%s\":{\"found\":%s,\"profiles\":%d,\"changed\":%d,\"unchanged\":%d,\"running\":%d,\"kept\":%d,\"failed\":%d}",
+ name, r->found ? "true" : "false", r->profiles, r->changed, r->unchanged, r->running, r->kept, r->failed);
+}
+
+char *brf_result_json(const BrfResult *chromium, const BrfResult *firefox) {
+ HBuf h = {0};
+ hb_printf(&h, "{");
+ put_result(&h, "chromium", chromium);
+ hb_printf(&h, ",");
+ put_result(&h, "firefox", firefox);
+ hb_printf(&h, "}");
+ return hb_take(&h);
+}
diff --git a/server/src/hw/brframe.h b/server/src/hw/brframe.h
new file mode 100644
index 0000000..e4b9baa
--- /dev/null
+++ b/server/src/hw/brframe.h
@@ -0,0 +1,59 @@
+/* brframe.h — Settings → Appearance → "Browsers: tabs in the title bar" (docs/WAYLAND.md, "The
+ * switch in Settings"). Writes ONE preference of the preinstalled browsers in the user's own
+ * profiles, and nothing else:
+ *
+ * Chromium ~/.config/chromium/{Default,Profile N}/Preferences
+ * browser.custom_chrome_frame = on, and with on extensions.theme.system_theme = 1
+ * (the GTK theme, for LordOS's window buttons) unless the profile uses a theme
+ * extension. Only while Chromium is not running (it rewrites the file when it quits);
+ * a surgical edit of those keys, the rest of the file byte for byte, validated as JSON
+ * before and after, a backup (Preferences.lordos-backup) and an atomic rename.
+ * Firefox ~/.config/mozilla/firefox and ~/.mozilla/firefox, the relative profiles listed in
+ * profiles.ini: one marked line user_pref("browser.tabs.inTitlebar", 1|0) in user.js
+ * (Firefox reads it at start, so it can be written while Firefox runs). brf_firefox_tidy
+ * removes the line again once Firefox has started with it (its "lock" link or .parentlock
+ * newer than user.js, the profile not open), so later choices in Firefox's own «Title Bar» stick. A
+ * user.js line the user wrote themselves is never touched ("kept").
+ *
+ * No program is run, no path comes from the caller: the folders are fixed under the user's home.
+ * Every file is opened with O_NOFOLLOW, must be a regular file owned by the user, and is size-capped. */
+#ifndef LORD_HW_BRFRAME_H
+#define LORD_HW_BRFRAME_H
+
+#include <stddef.h>
+
+typedef struct {
+ int found; /* the browser's data folder exists */
+ int profiles; /* profiles looked at */
+ int changed; /* written now */
+ int unchanged; /* already as asked */
+ int running; /* Chromium: it is open and nothing was written (try again after it quits);
+ Firefox: profiles that are open (the line applies when Firefox restarts) */
+ int kept; /* Firefox: the user's own user.js sets the preference; left alone */
+ int failed; /* unreadable, malformed or unwritable: left exactly as it was */
+} BrfResult;
+
+enum { BRF_CHANGED = 0, BRF_SAME = 1, BRF_BAD = -1 };
+
+/* Pure edits (tests/brframe_test.c). *out is malloc'd (NUL-terminated) only with BRF_CHANGED. */
+int brf_chrome_edit(const char *in, size_t n, int on, char **out, size_t *outn);
+/* user.js: value 0/1 sets LordOS's marked line, -1 removes it. *own = 1 if a line the user wrote
+ * sets the preference (then nothing is changed: BRF_SAME). */
+int brf_userjs_edit(const char *in, size_t n, int value, char **out, size_t *outn, int *own);
+/* The value prefs.js holds for browser.tabs.inTitlebar, or -1 if it isn't set there. */
+int brf_prefs_value(const char *in, size_t n);
+/* The value of LordOS's marked line in user.js, or -1. */
+int brf_userjs_ours(const char *in, size_t n);
+
+/* On disk. cfg: the user's config folder (~/.config); home: the home folder (legacy ~/.mozilla). */
+void brf_chromium_apply(const char *cfg, int on, BrfResult *r);
+void brf_firefox_apply(const char *cfg, const char *home, int on, BrfResult *r);
+int brf_firefox_tidy(const char *cfg, const char *home); /* marked lines removed */
+int brf_chromium_running(const char *cfg);
+/* How many Chromium profiles say custom_chrome_frame true / false (unset ones aren't counted). */
+void brf_chromium_state(const char *cfg, int *on, int *off);
+
+/* {"chromium":{…},"firefox":{…}} for lord.browserFrame.apply (malloc, NULL on OOM). */
+char *brf_result_json(const BrfResult *chromium, const BrfResult *firefox);
+
+#endif
diff --git a/server/src/ui/js_hw.c b/server/src/ui/js_hw.c
index f745272..93e78e3 100644
--- a/server/src/ui/js_hw.c
+++ b/server/src/ui/js_hw.c
@@ -22,9 +22,17 @@
* (hw/hwscan.c: DMI, device tree, PCI/USB IDs, virtio
* ports, missing firmware when the kernel log is readable)
* lord.fan.status() / setProfile(p) / setCurve(pts) / force(v) / caseConfig() (js_fan.c, lord-fand)
+ * lord.browserFrame.apply(on, which) Settings → Appearance → "Browsers: tabs in the title bar":
+ * one preference in the user's Chromium/Firefox profiles
+ * (hw/brframe.c); which = 'all' | 'chromium' | 'firefox';
+ * { chromium: {…}, firefox: {…} } counts
+ * lord.browserFrame.tidy() removes LordOS's Firefox user.js line once Firefox read it
+ * lord.browserFrame.chromiumRunning() Chromium's profile folder is in use
+ * lord.browserFrame.state() { chromiumOn, chromiumOff }: profiles with each frame
*/
#include "js_hw.h"
#include "js_fan.h"
+#include "../hw/brframe.h"
#include "../hw/bt.h"
#include "../hw/defaults.h"
#include "../hw/display.h"
@@ -358,6 +366,65 @@ static JSValue f_hwinfo_scan(JSContext *c, JSValueConst t, int argc, JSValueCons
static const JSCFunctionListEntry hwinfo_funcs[] = { JS_CFUNC_DEF("scan", 0, f_hwinfo_scan) };
+/* ---- lord.browserFrame (Settings → Appearance; hw/brframe.c, docs/WAYLAND.md) ---- */
+
+/* The folders are fixed: $XDG_CONFIG_HOME (absolute) or ~/.config, and ~ for the legacy ~/.mozilla. */
+static int brf_dirs(char *cfg, size_t n, const char **home) {
+ const char *h = getenv("HOME"), *x = getenv("XDG_CONFIG_HOME");
+ if (!h || h[0] != '/') return -1;
+ *home = h;
+ if (x && x[0] == '/' && !strstr(x, "..")) return (size_t)snprintf(cfg, n, "%s", x) < n ? 0 : -1;
+ return (size_t)snprintf(cfg, n, "%s/.config", h) < n ? 0 : -1;
+}
+
+static JSValue f_brf_apply(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ char which[16] = "all", cfg[4096];
+ const char *home;
+ if (argc < 1 || !JS_IsBool(argv[0])) return JS_NULL;
+ if (argc > 1 && arg_str(c, argv[1], which, sizeof which)) return JS_NULL;
+ int ch = !strcmp(which, "all") || !strcmp(which, "chromium"), ff = !strcmp(which, "all") || !strcmp(which, "firefox");
+ if ((!ch && !ff) || brf_dirs(cfg, sizeof cfg, &home)) return JS_NULL;
+ int on = JS_ToBool(c, argv[0]);
+ BrfResult rc = {0}, rf = {0};
+ if (ch) brf_chromium_apply(cfg, on, &rc);
+ if (ff) brf_firefox_apply(cfg, home, on, &rf);
+ return json_or_null(c, brf_result_json(&rc, &rf));
+}
+
+static JSValue f_brf_tidy(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char cfg[4096];
+ const char *home;
+ return JS_NewInt32(c, brf_dirs(cfg, sizeof cfg, &home) ? 0 : brf_firefox_tidy(cfg, home));
+}
+
+static JSValue f_brf_running(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char cfg[4096];
+ const char *home;
+ return JS_NewBool(c, !brf_dirs(cfg, sizeof cfg, &home) && brf_chromium_running(cfg));
+}
+
+static JSValue f_brf_state(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ char cfg[4096];
+ const char *home;
+ int on = 0, off = 0;
+ if (!brf_dirs(cfg, sizeof cfg, &home)) brf_chromium_state(cfg, &on, &off);
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyStr(c, o, "chromiumOn", JS_NewInt32(c, on));
+ JS_SetPropertyStr(c, o, "chromiumOff", JS_NewInt32(c, off));
+ return o;
+}
+
+static const JSCFunctionListEntry brf_funcs[] = {
+ JS_CFUNC_DEF("state", 0, f_brf_state),
+ JS_CFUNC_DEF("apply", 2, f_brf_apply),
+ JS_CFUNC_DEF("tidy", 0, f_brf_tidy),
+ JS_CFUNC_DEF("chromiumRunning", 0, f_brf_running),
+};
+
static void add(JSContext *c, JSValue lord, const char *name, const JSCFunctionListEntry *f, int n) {
JSValue o = JS_NewObject(c);
JS_SetPropertyFunctionList(c, o, f, n);
@@ -372,5 +439,6 @@ void js_hw_register(JSContext *c, JSValue lord) {
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]);
add(c, lord, "hwinfo", hwinfo_funcs, sizeof hwinfo_funcs / sizeof hwinfo_funcs[0]);
+ add(c, lord, "browserFrame", brf_funcs, sizeof brf_funcs / sizeof brf_funcs[0]);
js_fan_register(c, lord); /* lord.fan: Settings → Cooling and Monitor (js_fan.c) */
}
diff --git a/server/tests/brframe_test.c b/server/tests/brframe_test.c
new file mode 100644
index 0000000..0f74c42
--- /dev/null
+++ b/server/tests/brframe_test.c
@@ -0,0 +1,445 @@
+/* brframe_test.c — Settings → Appearance → "Browsers: tabs in the title bar" (src/hw/brframe.c):
+ * Chromium's Preferences edit (malformed JSON, missing keys, theme extensions, idempotence, the
+ * rest of the file kept byte for byte), Firefox's user.js line and its tidy-up, running browsers,
+ * stale locks, missing and hostile profile folders, over fake homes in a temporary folder.
+ *
+ * build/brframe-test (make test)
+ * build/brframe-test edit <Preferences> on|off prints the edited file (or why not) to stdout */
+#include "hw/brframe.h"
+#include "sec/json.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+static int n_ok, n_bad;
+#define CHECK(cond, ...) do { if (cond) n_ok++; else { n_bad++; printf("✗ %s:%d ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)
+
+static char root[256];
+
+static void mkdirs(const char *path) {
+ char p[1024];
+ snprintf(p, sizeof p, "%s", path);
+ for (char *s = p + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(p, 0700); *s = '/'; }
+ mkdir(p, 0700);
+}
+
+static void put(const char *rel, const char *text) {
+ char p[1024], d[1024];
+ snprintf(p, sizeof p, "%s/%s", root, rel);
+ snprintf(d, sizeof d, "%s", p);
+ char *sl = strrchr(d, '/');
+ if (sl) { *sl = 0; mkdirs(d); }
+ FILE *f = fopen(p, "wb");
+ if (!f) { printf("cannot write %s: %s\n", p, strerror(errno)); exit(2); }
+ fputs(text, f);
+ fclose(f);
+}
+
+static char *get(const char *rel) {
+ char p[1024];
+ snprintf(p, sizeof p, "%s/%s", root, rel);
+ FILE *f = fopen(p, "rb");
+ if (!f) return NULL;
+ static char buf[8][65536];
+ static int k;
+ char *b = buf[k++ % 8];
+ size_t n = fread(b, 1, sizeof buf[0] - 1, f);
+ b[n] = 0;
+ fclose(f);
+ return b;
+}
+
+static int exists(const char *rel) {
+ char p[1024];
+ struct stat st;
+ snprintf(p, sizeof p, "%s/%s", root, rel);
+ return lstat(p, &st) == 0;
+}
+
+static void path(char *out, size_t n, const char *rel) { snprintf(out, n, "%s/%s", root, rel); }
+
+/* the parsed value of browser.custom_chrome_frame (-1 missing) and extensions.theme.system_theme */
+static void chrome_values(const char *text, int *frame, int *theme) {
+ JDoc d;
+ *frame = *theme = -2;
+ if (!text || json_parse(text, strlen(text), &d, NULL, 0)) return;
+ const JVal *b = json_get(d.root, "browser"), *f = b ? json_get(b, "custom_chrome_frame") : NULL;
+ const JVal *e = json_get(d.root, "extensions"), *t = e ? json_get(e, "theme") : NULL, *s = t ? json_get(t, "system_theme") : NULL;
+ *frame = f && f->type == J_BOOL ? (int)f->num : -1;
+ *theme = s && s->type == J_NUM ? (int)s->num : -1;
+ json_free(&d);
+}
+
+static int edit(const char *in, int on, char **out) {
+ size_t n;
+ return brf_chrome_edit(in, strlen(in), on, out, &n);
+}
+
+static void test_chrome_edit(void) {
+ char *o, *o2;
+ int f, t;
+ CHECK(edit("{}", 1, &o) == BRF_CHANGED, "empty object, on");
+ chrome_values(o, &f, &t);
+ CHECK(f == 1 && t == 1, "empty on → frame %d theme %d", f, t);
+ CHECK(edit(o, 1, &o2) == BRF_SAME && !o2, "second time is the same");
+ free(o);
+
+ CHECK(edit("{}", 0, &o) == BRF_CHANGED, "empty off");
+ chrome_values(o, &f, &t);
+ CHECK(f == 0 && t == -1, "off writes only the frame (%d %d)", f, t);
+ free(o);
+
+ /* the rest of the file is kept byte for byte */
+ const char *real = "{\"a\":\"}\\\"{\",\"browser\":{\"has_seen_welcome_page\":true,\"custom_chrome_frame\":false,\"window_placement\":{\"x\":1}},"
+ "\"extensions\":{\"theme\":{\"system_theme\":0}},\"z\":[1,2,{\"q\":null}]}";
+ CHECK(edit(real, 1, &o) == BRF_CHANGED, "real-looking prefs");
+ CHECK(o && !strcmp(o, "{\"a\":\"}\\\"{\",\"browser\":{\"has_seen_welcome_page\":true,\"custom_chrome_frame\":true,\"window_placement\":{\"x\":1}},"
+ "\"extensions\":{\"theme\":{\"system_theme\":1}},\"z\":[1,2,{\"q\":null}]}"), "surgical edit: %s", o ? o : "(null)");
+ CHECK(edit(o, 1, &o2) == BRF_SAME, "idempotent");
+ CHECK(edit(o, 0, &o2) == BRF_CHANGED, "off again");
+ chrome_values(o2, &f, &t);
+ CHECK(f == 0 && t == 1, "off keeps the GTK theme (%d %d)", f, t);
+ free(o2);
+ free(o);
+
+ /* pretty-printed, members missing in an existing object */
+ CHECK(edit("{\n \"browser\": {\n \"x\": 1\n },\n \"extensions\": { }\n}\n", 1, &o) == BRF_CHANGED, "pretty");
+ chrome_values(o, &f, &t);
+ CHECK(f == 1 && t == 1, "pretty → %d %d", f, t);
+ free(o);
+
+ /* a theme extension the user installed: the frame changes, the theme doesn't */
+ CHECK(edit("{\"extensions\":{\"theme\":{\"id\":\"abcdefghijklmnopabcdefghijklmnop\",\"system_theme\":0}}}", 1, &o) == BRF_CHANGED, "theme ext");
+ chrome_values(o, &f, &t);
+ CHECK(f == 1 && t == 0, "theme extension kept (%d %d)", f, t);
+ free(o);
+ CHECK(edit("{\"browser\":{\"custom_chrome_frame\":true},\"extensions\":{\"theme\":{\"id\":\"x\"}}}", 1, &o) == BRF_SAME, "theme ext, already on");
+
+ /* malformed or unexpected: refused, never guessed */
+ const char *bad[] = {
+ "", "{", "{\"browser\":{\"custom_chrome_frame\":tru}}", "{} x", "[1,2]", "\"str\"", "null",
+ "{\"browser\":5}", "{\"browser\":{\"custom_chrome_frame\":true},\"extensions\":{\"theme\":7}}",
+ "{\"browser\":{},\"browser\":{}}", /* duplicate keys */
+ "{\"\\u0062rowser\":{\"x\":1}}", /* the same key, escaped: inserting would duplicate it */
+ "{\"a\":\"\\u0000\"}",
+ };
+ for (size_t i = 0; i < sizeof bad / sizeof *bad; i++) {
+ o = (char *)1;
+ int r = edit(bad[i], 1, &o);
+ CHECK(r == BRF_BAD && o == NULL, "bad[%zu] %s → %d", i, bad[i], r);
+ }
+}
+
+static int uedit(const char *in, int v, char **out, int *own) {
+ size_t n;
+ return brf_userjs_edit(in, strlen(in), v, out, &n, own);
+}
+
+static void test_userjs(void) {
+ char *o, *o2;
+ int own;
+ CHECK(uedit("", 0, &o, &own) == BRF_CHANGED && !own, "empty user.js");
+ CHECK(o && brf_userjs_ours(o, strlen(o)) == 0 && brf_prefs_value(o, strlen(o)) == 0, "line with 0: %s", o);
+ CHECK(uedit(o, 0, &o2, &own) == BRF_SAME, "same value again");
+ CHECK(uedit(o, 1, &o2, &own) == BRF_CHANGED && brf_userjs_ours(o2, strlen(o2)) == 1, "replaced by 1");
+ CHECK(!strstr(strstr(o2, "inTitlebar") + 1, "inTitlebar"), "only one line: %s", o2);
+ free(o);
+ CHECK(uedit(o2, -1, &o, &own) == BRF_CHANGED && o && !o[0], "removed: empty");
+ free(o);
+ free(o2);
+
+ /* other lines are kept, with or without a final newline */
+ CHECK(uedit("user_pref(\"a.b\", true);\n// note", 1, &o, &own) == BRF_CHANGED, "keeps others");
+ CHECK(o && !strncmp(o, "user_pref(\"a.b\", true);\n// note\nuser_pref(\"browser.tabs.inTitlebar\", 1);", 61), "appended: %s", o);
+ CHECK(uedit(o, -1, &o2, &own) == BRF_CHANGED && !strcmp(o2, "user_pref(\"a.b\", true);\n// note\n"), "removed again: [%s]", o2);
+ free(o);
+ free(o2);
+ CHECK(uedit("user_pref(\"a.b\", true);\n", -1, &o, &own) == BRF_SAME, "nothing of ours to remove");
+
+ /* the user's own line (either quotes): theirs, untouched */
+ CHECK(uedit("user_pref(\"browser.tabs.inTitlebar\", 0);\n", 1, &o, &own) == BRF_SAME && own && !o, "own line kept");
+ CHECK(uedit(" user_pref('browser.tabs.inTitlebar', 1);\n", 0, &o, &own) == BRF_SAME && own, "own line, single quotes");
+ CHECK(uedit("// user_pref(\"browser.tabs.inTitlebar\", 0);\n", 1, &o, &own) == BRF_CHANGED && !own, "a comment isn't a line");
+ free(o);
+ CHECK(uedit("user_pref(\"browser.tabs.inTitlebarX\", 0);\n", 1, &o, &own) == BRF_CHANGED && !own, "another pref name");
+ free(o);
+ size_t n;
+ CHECK(brf_userjs_edit("a\0b", 3, 1, &o, &n, &own) == BRF_BAD, "NUL bytes refused");
+
+ /* prefs.js values */
+ const char *pj = "// Mozilla User Preferences\nuser_pref(\"browser.startup.page\", 3);\nuser_pref(\"browser.tabs.inTitlebar\", 0);\n";
+ CHECK(brf_prefs_value(pj, strlen(pj)) == 0, "prefs.js 0");
+ CHECK(brf_prefs_value("", 0) == -1, "prefs.js unset");
+ CHECK(brf_prefs_value("user_pref(\"browser.tabs.inTitlebar\", true);", 44) == 1, "true");
+}
+
+/* ---- on disk ---- */
+
+static pid_t child_named(const char *name) {
+ pid_t p = fork();
+ if (p == 0) {
+ prctl(PR_SET_NAME, name, 0, 0, 0);
+ for (;;) pause();
+ }
+ usleep(50000);
+ return p;
+}
+
+static void stop(pid_t p) { kill(p, SIGKILL); waitpid(p, NULL, 0); }
+
+static void lock_link(const char *rel, const char *target) {
+ char p[1024];
+ path(p, sizeof p, rel);
+ unlink(p);
+ if (symlink(target, p)) printf("symlink %s: %s\n", p, strerror(errno));
+}
+
+static void test_chromium_disk(void) {
+ char cfg[512], host[256], t[512];
+ BrfResult r;
+ path(cfg, sizeof cfg, "h1/.config");
+ mkdirs(cfg);
+ brf_chromium_apply(cfg, 1, &r);
+ CHECK(!r.found && !r.profiles && !r.changed, "no chromium folder");
+ CHECK(!brf_chromium_running(cfg), "no folder: not running");
+
+ const char *orig = "{\"browser\":{\"custom_chrome_frame\":false},\"zz\":1}";
+ put("h1/.config/chromium/Default/Preferences", orig);
+ put("h1/.config/chromium/Profile 1/Preferences", "{}");
+ put("h1/.config/chromium/Profile 2/Preferences", "{\"browser\":"); /* truncated */
+ put("h1/.config/chromium/System Profile/Preferences", "{}"); /* not a user profile */
+ put("h1/.config/chromium/Profile x/Preferences", "{}");
+ mkdirs(root);
+ put("h1/.config/chromium/Profile 3/.keep", ""); /* never started */
+ put("h1/target.json", "{}");
+ mkdirs(cfg);
+ {
+ char p[1024];
+ path(p, sizeof p, "h1/.config/chromium/Profile 4");
+ mkdirs(p);
+ lock_link("h1/.config/chromium/Profile 4/Preferences", "../../../target.json"); /* a link: refused */
+ path(p, sizeof p, "h1/.config/chromium/Default/Preferences");
+ chmod(p, 0600);
+ }
+ char *before2 = strdup(get("h1/.config/chromium/Profile 2/Preferences"));
+ int son0, soff0;
+ brf_chromium_state(cfg, &son0, &soff0);
+ CHECK(son0 == 0 && soff0 == 1, "state before: %d on, %d off (unset and malformed not counted)", son0, soff0);
+
+ /* running: a live "chromium" process of ours holds the lock → nothing is written */
+ gethostname(host, sizeof host);
+ pid_t ch = child_named("chromium");
+ snprintf(t, sizeof t, "%s-%d", host, (int)ch);
+ lock_link("h1/.config/chromium/SingletonLock", t);
+ CHECK(brf_chromium_running(cfg), "running");
+ brf_chromium_apply(cfg, 1, &r);
+ CHECK(r.found && r.running && !r.changed && !strcmp(get("h1/.config/chromium/Default/Preferences"), orig), "running: untouched");
+ stop(ch);
+
+ /* a stale lock (dead pid, or a pid that isn't chromium) doesn't stop it; another host does */
+ snprintf(t, sizeof t, "%s-%d", host, (int)getpid());
+ lock_link("h1/.config/chromium/SingletonLock", t);
+ CHECK(!brf_chromium_running(cfg), "our own pid isn't chromium");
+ lock_link("h1/.config/chromium/SingletonLock", "some-other-host-12");
+ CHECK(brf_chromium_running(cfg), "another computer counts as running");
+ snprintf(t, sizeof t, "%s-%d", host, (int)ch); /* dead now */
+ lock_link("h1/.config/chromium/SingletonLock", t);
+ CHECK(!brf_chromium_running(cfg), "dead pid: stale");
+
+ brf_chromium_apply(cfg, 1, &r);
+ CHECK(r.found && !r.running && r.profiles == 4 && r.changed == 2 && r.failed == 2 && !r.unchanged,
+ "apply: profiles %d changed %d failed %d unchanged %d", r.profiles, r.changed, r.failed, r.unchanged);
+ int f, th;
+ chrome_values(get("h1/.config/chromium/Default/Preferences"), &f, &th);
+ CHECK(f == 1 && th == 1, "Default on (%d %d)", f, th);
+ CHECK(strstr(get("h1/.config/chromium/Default/Preferences"), "\"zz\":1") != NULL, "other keys kept");
+ CHECK(!strcmp(get("h1/.config/chromium/Default/Preferences.lordos-backup"), orig), "backup is the original");
+ chrome_values(get("h1/.config/chromium/Profile 1/Preferences"), &f, &th);
+ CHECK(f == 1 && th == 1, "Profile 1 on");
+ CHECK(!strcmp(get("h1/.config/chromium/Profile 2/Preferences"), before2) && !exists("h1/.config/chromium/Profile 2/Preferences.lordos-backup"),
+ "malformed profile untouched, no backup");
+ CHECK(!strcmp(get("h1/target.json"), "{}"), "a linked Preferences is never followed");
+ CHECK(!strcmp(get("h1/.config/chromium/System Profile/Preferences"), "{}") && !strcmp(get("h1/.config/chromium/Profile x/Preferences"), "{}"),
+ "other folders untouched");
+ CHECK(!exists("h1/.config/chromium/Default/Preferences.lordos-tmp"), "no temporary file left");
+ {
+ char p[1024];
+ struct stat st;
+ path(p, sizeof p, "h1/.config/chromium/Default/Preferences");
+ CHECK(!stat(p, &st) && (st.st_mode & 0777) == 0600, "mode kept: %o", st.st_mode & 0777);
+ }
+
+ int son, soff;
+ brf_chromium_state(cfg, &son, &soff);
+ CHECK(son == 2 && soff == 0, "state after on: %d on, %d off", son, soff);
+ brf_chromium_apply(cfg, 1, &r);
+ CHECK(r.changed == 0 && r.unchanged == 2 && r.failed == 2, "idempotent: changed %d unchanged %d", r.changed, r.unchanged);
+ brf_chromium_apply(cfg, 0, &r);
+ CHECK(r.changed == 2, "off: changed %d", r.changed);
+ chrome_values(get("h1/.config/chromium/Default/Preferences"), &f, &th);
+ CHECK(f == 0 && th == 1, "Default off (%d %d)", f, th);
+ brf_chromium_state(cfg, &son, &soff);
+ CHECK(son == 0 && soff == 2, "state after off: %d on, %d off", son, soff);
+ free(before2);
+}
+
+static void touch_later(const char *rel, int secs) {
+ char p[1024];
+ path(p, sizeof p, rel);
+ struct timespec ts[2];
+ clock_gettime(CLOCK_REALTIME, &ts[0]);
+ ts[0].tv_sec += secs;
+ ts[1] = ts[0];
+ utimensat(AT_FDCWD, p, ts, AT_SYMLINK_NOFOLLOW);
+}
+
+static void test_firefox_disk(void) {
+ char cfg[512], home[512];
+ BrfResult r;
+ path(home, sizeof home, "h2");
+ path(cfg, sizeof cfg, "h2/.config");
+ mkdirs(cfg);
+ brf_firefox_apply(cfg, home, 1, &r);
+ CHECK(!r.found && !r.profiles, "no Firefox folders");
+
+ put("h2/.config/mozilla/firefox/profiles.ini",
+ "[Profile1]\nName=default\nIsRelative=1\nPath=aaaa.default\nDefault=1\n\n"
+ "[Profile0]\r\nName=default-esr\r\nIsRelative=1\r\nPath=bbbb.default-esr\r\n\r\n"
+ "[Profile2]\nName=abs\nIsRelative=0\nPath=/tmp\n\n"
+ "[Profile3]\nName=evil\nIsRelative=1\nPath=../../etc\n\n"
+ "[Profile4]\nName=missing\nIsRelative=1\nPath=nothere\n\n"
+ "[Install3B6073811A6ABF12]\nDefault=bbbb.default-esr\nLocked=1\n\n"
+ "[General]\nStartWithLastProfile=1\nVersion=2"); /* no final newline */
+ put("h2/.config/mozilla/firefox/aaaa.default/prefs.js", "user_pref(\"browser.tabs.inTitlebar\", 1);\n");
+ put("h2/.config/mozilla/firefox/bbbb.default-esr/prefs.js", "user_pref(\"x\", 1);\n");
+ put("h2/.config/mozilla/firefox/bbbb.default-esr/user.js", "user_pref(\"x.y\", 2);");
+ /* legacy folder with a profile whose user wrote the line themselves */
+ put("h2/.mozilla/firefox/profiles.ini", "[Profile0]\nIsRelative=1\nPath=cccc.mine\n");
+ put("h2/.mozilla/firefox/cccc.mine/user.js", "user_pref(\"browser.tabs.inTitlebar\", 0);\n");
+
+ brf_firefox_apply(cfg, home, 1, &r);
+ CHECK(r.found && r.profiles == 3 && r.changed == 1 && r.unchanged == 1 && r.kept == 1 && !r.failed,
+ "apply on: profiles %d changed %d unchanged %d kept %d failed %d", r.profiles, r.changed, r.unchanged, r.kept, r.failed);
+ CHECK(!exists("h2/.config/mozilla/firefox/aaaa.default/user.js"), "prefs.js already 1: no line needed");
+ char *u = get("h2/.config/mozilla/firefox/bbbb.default-esr/user.js");
+ CHECK(u && !strncmp(u, "user_pref(\"x.y\", 2);\nuser_pref(\"browser.tabs.inTitlebar\", 1);", 61), "line appended: %s", u ? u : "");
+ CHECK(!strcmp(get("h2/.config/mozilla/firefox/bbbb.default-esr/user.js.lordos-backup"), "user_pref(\"x.y\", 2);"), "user.js backup");
+ CHECK(!strcmp(get("h2/.mozilla/firefox/cccc.mine/user.js"), "user_pref(\"browser.tabs.inTitlebar\", 0);\n"), "own line untouched");
+
+ brf_firefox_apply(cfg, home, 1, &r);
+ CHECK(r.changed == 0 && r.unchanged == 2 && r.kept == 1, "idempotent: changed %d unchanged %d", r.changed, r.unchanged);
+
+ /* off: both profiles get the line (aaaa's prefs.js says 1) */
+ brf_firefox_apply(cfg, home, 0, &r);
+ CHECK(r.changed == 2, "off: changed %d", r.changed);
+ CHECK(brf_userjs_ours(get("h2/.config/mozilla/firefox/aaaa.default/user.js"), strlen(get("h2/.config/mozilla/firefox/aaaa.default/user.js"))) == 0, "aaaa 0");
+ {
+ char p[1024];
+ struct stat st;
+ path(p, sizeof p, "h2/.config/mozilla/firefox/aaaa.default/user.js");
+ CHECK(!stat(p, &st) && (st.st_mode & 0777) == 0600, "new user.js is 0600");
+ }
+
+ /* tidy: not before Firefox has started with the line. prefs.js written after it is no proof
+ * (Firefox writes it when it quits, also after a line written while it ran) */
+ touch_later("h2/.config/mozilla/firefox/aaaa.default/prefs.js", 100);
+ touch_later("h2/.config/mozilla/firefox/bbbb.default-esr/prefs.js", 100);
+ CHECK(brf_firefox_tidy(cfg, home) == 0, "no start since the line: nothing to tidy");
+ put("h2/.config/mozilla/firefox/aaaa.default/.parentlock", "");
+ touch_later("h2/.config/mozilla/firefox/aaaa.default/.parentlock", -100);
+ lock_link("h2/.config/mozilla/firefox/bbbb.default-esr/lock", "127.0.1.1:+1");
+ touch_later("h2/.config/mozilla/firefox/bbbb.default-esr/lock", -100);
+ CHECK(brf_firefox_tidy(cfg, home) == 0, "last start before the line: nothing to tidy");
+
+ /* running: a process holds .parentlock → the line is written anyway (read at the next start),
+ * counted as running, and tidy waits */
+ put("h2/.config/mozilla/firefox/bbbb.default-esr/.parentlock", "");
+ char p[1024];
+ path(p, sizeof p, "h2/.config/mozilla/firefox/bbbb.default-esr/.parentlock");
+ int pipefd[2];
+ if (pipe(pipefd)) { perror("pipe"); exit(2); }
+ pid_t ff = fork();
+ if (ff == 0) {
+ int fd = open(p, O_RDWR);
+ struct flock fl = { .l_type = F_WRLCK, .l_whence = SEEK_SET };
+ fcntl(fd, F_SETLK, &fl);
+ if (write(pipefd[1], "k", 1) < 0) _exit(1);
+ for (;;) pause();
+ }
+ char k;
+ if (read(pipefd[0], &k, 1) != 1) { perror("read"); exit(2); }
+ brf_firefox_apply(cfg, home, 1, &r);
+ CHECK(r.changed == 2 && r.running == 1, "running profile: changed %d running %d", r.changed, r.running);
+ /* both profiles "started" after the line; only the closed one is tidied */
+ touch_later("h2/.config/mozilla/firefox/aaaa.default/.parentlock", 100);
+ touch_later("h2/.config/mozilla/firefox/bbbb.default-esr/.parentlock", 100);
+ CHECK(brf_firefox_tidy(cfg, home) == 1, "tidy only the closed profile");
+ CHECK(!exists("h2/.config/mozilla/firefox/aaaa.default/user.js"), "a user.js that held only our line is removed");
+ stop(ff);
+ close(pipefd[0]);
+ close(pipefd[1]);
+
+ /* the "lock" link of a live firefox counts too; a stale one doesn't */
+ char t[64];
+ pid_t fx = child_named("firefox-esr");
+ snprintf(t, sizeof t, "127.0.1.1:+%d", (int)fx);
+ lock_link("h2/.config/mozilla/firefox/bbbb.default-esr/lock", t);
+ touch_later("h2/.config/mozilla/firefox/bbbb.default-esr/lock", 100);
+ CHECK(brf_firefox_tidy(cfg, home) == 0, "lock link of a live firefox: wait");
+ stop(fx);
+ CHECK(brf_firefox_tidy(cfg, home) == 1, "stale lock link: tidied");
+ CHECK(!strcmp(get("h2/.config/mozilla/firefox/bbbb.default-esr/user.js"), "user_pref(\"x.y\", 2);\n"), "other lines kept: %s",
+ get("h2/.config/mozilla/firefox/bbbb.default-esr/user.js"));
+ CHECK(brf_firefox_tidy(cfg, home) == 0, "tidy is idempotent");
+ CHECK(!strcmp(get("h2/.mozilla/firefox/cccc.mine/user.js"), "user_pref(\"browser.tabs.inTitlebar\", 0);\n"), "own line still untouched");
+
+ /* a user.js that is a link or too big is refused */
+ lock_link("h2/.config/mozilla/firefox/aaaa.default/user.js", "../../../../target");
+ put("h2/target", "keep");
+ brf_firefox_apply(cfg, home, 0, &r);
+ CHECK(r.failed == 1 && !strcmp(get("h2/target"), "keep"), "linked user.js refused (failed %d)", r.failed);
+}
+
+static int edit_file(const char *file, int on) {
+ FILE *f = fopen(file, "rb");
+ if (!f) { perror(file); return 2; }
+ static char buf[32 << 20];
+ size_t n = fread(buf, 1, sizeof buf, f), outn;
+ fclose(f);
+ char *out;
+ int r = brf_chrome_edit(buf, n, on, &out, &outn);
+ if (r == BRF_CHANGED) fwrite(out, 1, outn, stdout);
+ fprintf(stderr, "%s\n", r == BRF_CHANGED ? "changed" : r == BRF_SAME ? "same" : "bad");
+ free(out);
+ return r == BRF_BAD ? 1 : 0;
+}
+
+int main(int argc, char **argv) {
+ if (argc == 4 && !strcmp(argv[1], "edit")) return edit_file(argv[2], !strcmp(argv[3], "on"));
+ snprintf(root, sizeof root, "%s/brframe-test.XXXXXX", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
+ if (!mkdtemp(root)) { perror("mkdtemp"); return 2; }
+ test_chrome_edit();
+ test_userjs();
+ test_chromium_disk();
+ test_firefox_disk();
+ BrfResult a = { 1, 2, 1, 1, 0, 0, 0 }, b = { 0 };
+ char *j = brf_result_json(&a, &b);
+ JDoc d;
+ CHECK(j && !json_parse(j, strlen(j), &d, NULL, 0), "result JSON: %s", j ? j : "");
+ if (j) json_free(&d);
+ free(j);
+ char cmd[512];
+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", root);
+ if (system(cmd)) printf("could not remove %s\n", root);
+ printf("brframe-test: %d ok, %d failed\n", n_ok, n_bad);
+ return n_bad ? 1 : 0;
+}