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.

Mail, Calendar, Contacts and Reminders run as isolated system apps

Federico Pereira8b09b19697fe
diff --git a/apps/calendar/manifest.json b/apps/calendar/manifest.json
index be7ff6b..cb70002 100644
--- a/apps/calendar/manifest.json
+++ b/apps/calendar/manifest.json
@@ -6,5 +6,6 @@
"minSize": [640, 440],
"dock": true,
"category": "Office",
- "permissions": []
+ "permissions": [],
+ "process": "isolated"
}
diff --git a/apps/contacts/card.jsx b/apps/contacts/card.jsx
index e50512b..d8944e9 100644
--- a/apps/contacts/card.jsx
+++ b/apps/contacts/card.jsx
@@ -2,6 +2,7 @@
// (name, photo, phones, emails, addresses, web pages, birthday and notes).
import {
View, Text, useTheme, Button, TextInput, ScrollView, Hairline, ContactPhoto, contacts, contactName, wm, getApp, formatDate, FilePicker, t,
+ isolatedPim, pickFileFd,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
import { RED, Popover, MenuList, Choice, TextArea, DateField, ymd, parseYmd, monthName } from './ui.jsx';
@@ -38,7 +39,7 @@ function bdayText(s) {
const addrLines = (a) => [a.street, [a.code, a.city].filter(Boolean).join(' '), a.region, a.country].filter(Boolean);
function openMail(name, email) {
- if (!getApp('mail')) return;
+ if (!getApp('mail') && !isolatedPim()) return; // in its own process, the session opens Mail
wm.open('mail', { new: true, args: { compose: { to: [{ name: name || '', email }] } } });
}
@@ -180,7 +181,12 @@ export function Editor({ contact, groups, onCancel, onSave, onDelete }) {
{photoMenu ? (
<Popover anchor={photoRef} width={200} onClose={() => setPhotoMenu(false)}>
<MenuList onDone={() => setPhotoMenu(false)} items={[
- { label: t('contacts.choosePhoto'), onClick: () => setPicking(true) },
+ { label: t('contacts.choosePhoto'), onClick: () => {
+ if (!isolatedPim()) { setPicking(true); return; }
+ let f = null; // the system's file dialog (only the chosen image reaches this process)
+ try { f = pickFileFd(); } catch (e) { f = null; }
+ if (f) setPhoto(f);
+ } },
{ label: t('contacts.removePhoto'), destructive: true, disabled: !d.photo && photo === 'keep', onClick: () => setPhoto('remove') },
]} />
</Popover>
diff --git a/apps/contacts/index.jsx b/apps/contacts/index.jsx
index 32e3264..44deaf0 100644
--- a/apps/contacts/index.jsx
+++ b/apps/contacts/index.jsx
@@ -4,6 +4,7 @@
import {
View, Text, useTheme, useLocale, useKeyboard, useWindowState, usePim, addressBooks, contacts, contactName,
Button, TextInput, SearchField, Hairline, EmptyState, ToolbarButton, FilePicker, addListener, direction, formatNumber, t,
+ isolatedPim, pickFileFd, closeFileFd,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
import { RED, Sheet, Popover, MenuList, Layers, useLoad } from './ui.jsx';
@@ -120,12 +121,20 @@ export default function ContactsApp() {
const r = await contacts.importFile(path, await targetBook());
setSheet({ notice: t('contacts.imported', { count: r && r.added != null ? r.added : 0, n: formatNumber(r && r.added != null ? r.added : 0, 0) }) });
} catch (e) { setSheet({ notice: t('contacts.importFailed') }); }
+ closeFileFd(path);
+ };
+ // in its own process Contacts gets the .vcf from the system's file dialog (only that file)
+ const startImport = () => {
+ if (!isolatedPim()) { setSheet({ pick: 'vcf' }); return; }
+ let f = null;
+ try { f = pickFileFd(); } catch (e) { setSheet({ notice: t('contacts.importFailed') }); }
+ if (f) importVcf(f);
};
return (
<View style={{ flex: 1, flexDirection: 'row', backgroundColor: th.windowBg }}>
<Sources books={books} groups={groups} src={src} counts={people} onSrc={(s) => { setSrc(s); setDraft(null); }}
- onNewGroup={() => setSheet({ newGroup: true })} onImport={() => setSheet({ pick: 'vcf' })}
+ onNewGroup={() => setSheet({ newGroup: true })} onImport={startImport}
onRenameGroup={(g) => setSheet({ group: g })} onDeleteGroup={(g) => { contacts.remove(g.book, g.uid).catch(() => {}); if (src === `group:${keyOf(g)}`) setSrc('all'); }} />
<View style={{ width: 270 }}>
<Hairline edge="end" />
diff --git a/apps/contacts/manifest.json b/apps/contacts/manifest.json
index e82e6db..9067e79 100644
--- a/apps/contacts/manifest.json
+++ b/apps/contacts/manifest.json
@@ -6,5 +6,6 @@
"minSize": [700, 400],
"dock": true,
"category": "Office",
- "permissions": []
+ "permissions": [],
+ "process": "isolated"
}
diff --git a/apps/mail/Compose.jsx b/apps/mail/Compose.jsx
index 02324fa..6f8cb0c 100644
--- a/apps/mail/Compose.jsx
+++ b/apps/mail/Compose.jsx
@@ -1,12 +1,21 @@
// Compose.jsx — the compose window: From, To/Cc/Bcc with autocomplete (Contacts and people you
// wrote to), subject, a body in rich text (formatting buttons and a live preview), markdown or
// plain text, attachments, signature, drafts saved to the server, send now or later.
-import { View, Text, useTheme, useAppWindow, Button, TextInput, Segmented, ScrollView, Markdown, FilePicker, t, wm, fs, mailRequest, mailAccounts, contacts, useKeyboard } from '@lordos/sdk';
+import { View, Text, useTheme, useAppWindow, Button, TextInput, Segmented, ScrollView, Markdown, FilePicker, t, wm, fs, mailRequest, mailAccounts, contacts, useKeyboard, isolatedPim, pickFileFd, closeFileFd } from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
import { BodyEditor } from './BodyEditor.jsx';
import { mdToHtml, mdToText } from './md.js';
import { formatSize } from './util.js';
+// An attachment is a path (Mail in the session) or { fd, name, size } (Mail in its own process: a
+// file from the system dialog, or a cached attachment lord-server opened for it).
+const attName = (p) => (typeof p === 'object' ? p.name : fs.basename(p));
+const attKey = (p) => (typeof p === 'object' ? `fd:${p.fd}` : p);
+function attSize(p) {
+ if (typeof p === 'object') return p.size || 0;
+ try { return fs.stat(p)?.size || 0; } catch (e) { return 0; }
+}
+
const emailOk = (e) => /^[^@\s<>,;"]+@[^@\s<>,;"]+\.[^@\s<>,;"]+$/.test(e);
function parseTyped(s) {
@@ -104,13 +113,17 @@ export function Compose({ draft: initial }) {
const set = (patch) => { dirty.current = true; setD((x) => ({ ...x, ...patch })); };
useEffect(() => { wm.setTitle(wid, d.subject || t('mail.compose.newMessage')); }, [d.subject]);
+ // files held as fds (isolated Mail) are closed with the window
+ const atts = useRef(d.attachments);
+ atts.current = d.attachments;
+ useEffect(() => () => { for (const p of atts.current) closeFileFd(p); }, []);
const payload = () => {
const html = d.format === 'plain' ? undefined : mdToHtml(d.body);
const text = d.format === 'plain' ? d.body : mdToText(d.body);
return {
acct: d.acct, to: d.to, cc: d.cc, bcc: d.bcc, subject: d.subject, text, ...(html ? { html } : {}),
- attachments: d.attachments.map((p) => ({ name: fs.basename(p) })),
+ attachments: d.attachments.map((p) => ({ name: attName(p) })),
...(d.inReplyTo ? { inReplyTo: d.inReplyTo } : {}), ...(d.references ? { references: d.references } : {}),
...(d.original ? { original: d.original } : {}),
...(d.draftUid ? { draftUid: d.draftUid, draftFolder: d.draftFolder } : {}),
@@ -174,7 +187,13 @@ export function Compose({ draft: initial }) {
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 12, height: 46 }}>
<Button primary label={`➤ ${t('mail.compose.send')}`} onClick={() => send()} />
<Button label={t('mail.compose.later')} onClick={() => setLater(!later)} />
- <Button label={`📎 ${t('mail.compose.attach')}`} onClick={() => setPicker(true)} />
+ <Button label={`📎 ${t('mail.compose.attach')}`} onClick={() => {
+ if (!isolatedPim()) { setPicker(true); return; }
+ // the system's file dialog: this process receives only the chosen file
+ let f = null;
+ try { f = pickFileFd(); } catch (e) { setErr(e.message); }
+ if (f) set({ attachments: [...d.attachments, f].slice(0, 15) });
+ }} />
<Button label={t('mail.compose.saveDraft')} onClick={() => saveDraft()} />
<View style={{ flex: 1 }} />
<Segmented small options={fmtOpts} value={d.format} onChange={(format) => set({ format })} />
@@ -242,13 +261,12 @@ export function Compose({ draft: initial }) {
{d.attachments.length > 0 && (
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 6, padding: 10 }}>
{d.attachments.map((p) => {
- let size = 0;
- try { size = fs.stat(p)?.size || 0; } catch (e) { size = 0; }
+ const size = attSize(p);
return (
- <View key={p} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 10, height: 28, borderRadius: 8, backgroundColor: th.control }}>
- <Text style={{ fontSize: 12, color: th.text }}>{`📄 ${fs.basename(p)}`}</Text>
+ <View key={attKey(p)} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, paddingHorizontal: 10, height: 28, borderRadius: 8, backgroundColor: th.control }}>
+ <Text style={{ fontSize: 12, color: th.text }}>{`📄 ${attName(p)}`}</Text>
<Text style={{ fontSize: 11, color: th.textDim }}>{formatSize(size)}</Text>
- <Text onClick={() => set({ attachments: d.attachments.filter((x) => x !== p) })} style={{ fontSize: 11, color: th.textDim }}>✕</Text>
+ <Text onClick={() => { closeFileFd(p); set({ attachments: d.attachments.filter((x) => x !== p) }); }} style={{ fontSize: 11, color: th.textDim }}>✕</Text>
</View>
);
})}
diff --git a/apps/mail/index.jsx b/apps/mail/index.jsx
index 6733588..031c996 100644
--- a/apps/mail/index.jsx
+++ b/apps/mail/index.jsx
@@ -6,6 +6,7 @@ import {
View, Text, useTheme, useStore, useAppWindow, useKeyboard, Button, TextInput, ScrollView, t, wm, fs, monthName, formatDate, formatTime,
Toolbar, ToolbarButton, ToolbarSpacer, ToolbarDivider, SearchField, Hairline, direction, textDirection,
mailRequest, onMailEvent, mailStatus, mailConfig, mailAccounts, mailAvailable, addListener, clipboard, registerDockActions,
+ trackMailStatus, isolatedPim, saveFile,
} from '@lordos/sdk';
import { useEffect, useRef, useState } from 'react';
import { HtmlView, TextView } from './HtmlView.jsx';
@@ -297,13 +298,26 @@ function Attachments({ msg }) {
const [busy, setBusy] = useState(null);
const atts = (msg.atts || []).filter((a) => !(a.inline && a.cid && msg.html));
if (!atts.length) return null;
- const fetch = async (a) => {
- const r = await mailRequest('attachment', { acct: msg.acct, folder: msg.folder, uid: msg.uid, idx: a.idx });
- return `${lord.mail.cacheDir()}/${r.path}`;
+ const rel = async (a) => (await mailRequest('attachment', { acct: msg.acct, folder: msg.folder, uid: msg.uid, idx: a.idx })).path;
+ const fetch = async (a) => `${lord.mail.cacheDir()}/${await rel(a)}`;
+ const open = async (a) => {
+ setBusy(a.idx);
+ // in its own process Mail cannot open files: lord-server checks the cached attachment and the
+ // session opens it with the user's apps
+ try { if (isolatedPim()) lord.mail.openAttachment(await rel(a), a.name); else openPath(await fetch(a), a.name); } catch (e) { /* shown in the row */ }
+ setBusy(null);
};
- const open = async (a) => { setBusy(a.idx); try { openPath(await fetch(a), a.name); } catch (e) { /* shown in the row */ } setBusy(null); };
const save = async (a) => {
setBusy(a.idx);
+ if (isolatedPim()) {
+ // a read-only fd of the cached attachment, then the system's save dialog
+ try {
+ const fd = lord.mail.attachmentFd(await rel(a));
+ if (fd >= 0) { const data = lord.broker.fdRead(fd); lord.broker.fdClose(fd); await saveFile(safeName(a.name), data); }
+ } catch (e) { /* cancelled or restricted */ }
+ setBusy(null);
+ return;
+ }
try {
const p = await fetch(a);
const dir = ['Descargas', 'Downloads', 'Transferências'].map((d) => `${fs.home()}/${d}`).find((d) => { try { return fs.stat(d); } catch (e) { return false; } }) || fs.home();
@@ -413,6 +427,7 @@ function MessageView({ msg, width, onLink, cfg, onTrustSender, collapsed, onExpa
export default function Mail() {
const { args } = useAppWindow();
+ trackMailStatus(); // only in its own process (lord.mail.appMode)
if (args?.compose) return <Compose draft={typeof args.compose === 'object' ? args.compose : {}} />;
return <MailMain />;
}
@@ -518,7 +533,13 @@ function MailMain() {
// the original's attachments go along (saved from the cache)
const paths = [];
for (const a of msg.atts || []) {
- try { const r = await mailRequest('attachment', { acct: msg.acct, folder: msg.folder, uid: msg.uid, idx: a.idx }); paths.push(`${lord.mail.cacheDir()}/${r.path}`); } catch (e) { /* skip */ }
+ try {
+ const r = await mailRequest('attachment', { acct: msg.acct, folder: msg.folder, uid: msg.uid, idx: a.idx });
+ if (isolatedPim()) {
+ const fd = lord.mail.attachmentFd(r.path);
+ if (fd >= 0) paths.push({ fd, name: safeName(a.name), size: a.size || 0 });
+ } else paths.push(`${lord.mail.cacheDir()}/${r.path}`);
+ } catch (e) { /* skip */ }
}
delete d.forwardAtts;
compose({ ...d, attachments: paths, noSignature: false });
diff --git a/apps/mail/manifest.json b/apps/mail/manifest.json
index eadd379..967f7e2 100644
--- a/apps/mail/manifest.json
+++ b/apps/mail/manifest.json
@@ -6,5 +6,6 @@
"minSize": [820, 480],
"dock": true,
"category": "Office",
- "permissions": ["network", "fs:home"]
+ "permissions": ["network", "fs:home"],
+ "process": "isolated"
}
diff --git a/apps/mail/util.js b/apps/mail/util.js
index 9387ee7..eac6555 100644
--- a/apps/mail/util.js
+++ b/apps/mail/util.js
@@ -1,6 +1,6 @@
// util.js — small helpers for Mail: dates in the list, folder names, color categories, opening
// an attachment the way Files would.
-import { t, formatDate, formatTime, weekdayName, wm, getApp, fs, defaultOpenerId, nativeOf, calendarEvents, contacts, addressBooks } from '@lordos/sdk';
+import { t, formatDate, formatTime, weekdayName, openFileWithApps, revealPath } from '@lordos/sdk';
export const CATEGORY_COLORS = ['#ff453a', '#ff9f0a', '#ffd60a', '#30d158', '#0a84ff', '#bf5af2'];
// labels are built at render time (they follow the language)
@@ -30,30 +30,9 @@ export function formatSize(n) {
return `${(n / 1048576).toFixed(1)} MB`;
}
-// The same rules as Files (apps/files/ops.js): our apps for documents, images and media, the
-// system's default app for the rest, and otherwise reveal it in Files.
-export function openPath(path, name) {
- const n = String(name || path).toLowerCase();
- if (/\.pdf$/.test(n) && getApp('pdf')) return wm.open('pdf', { new: true, args: { path } });
- if (/\.(png|jpe?g|gif|webp|bmp|heic|avif)$/.test(n) && getApp('photos')) return wm.open('photos', { new: true, args: { path } });
- if (/\.(mp3|ogg|flac|wav|m4a|opus|mp4|mkv|webm|mov|avi)$/.test(n) && getApp('player')) return wm.open('player', { args: { path } });
- if (/\.(txt|md|csv|log|json|xml|ya?ml|c|h|js|py|sh)$/.test(n) && getApp('editor')) return wm.open('editor', { args: { path } });
- if (/\.ics$/.test(n) && getApp('calendar')) { calendarEvents.importFile(path).then(() => wm.open('calendar')).catch(() => revealPath(path)); return true; }
- if (/\.vcf$/.test(n) && getApp('contacts')) {
- addressBooks.list().then((b) => (b[0] ? contacts.importFile(path, b[0].id) : null)).then(() => wm.open('contacts')).catch(() => revealPath(path));
- return true;
- }
- try {
- const def = defaultOpenerId(typeof lord.mime !== 'undefined' ? lord.mime.guess(n) : '');
- const native = nativeOf(def);
- if (native && getApp(native)) return wm.open(native, { new: true, args: { path } });
- if (def && lord.apps.launchWith(def.replace(/\.desktop$/, ''), path)) return true;
- if (lord.apps.launchWith('', path)) return true;
- } catch (e) { /* no default app */ }
- return revealPath(path);
-}
-
-export const revealPath = (path) => wm.open('files', { new: true, args: { path: fs.parent(path), select: fs.basename(path), nonce: Date.now() } });
+// The same rules as Files (apps/files/ops.js), in the session (sdk/sysopen.js).
+export const openPath = (path, name) => openFileWithApps(path, name);
+export { revealPath };
// The same rule as lord-maild (mime_safe_filename): a sender-chosen attachment name becomes a
// plain basename: no path parts, no leading dots, no control, bidi-override or FAT-reserved
diff --git a/apps/monitor/Processes.jsx b/apps/monitor/Processes.jsx
index c127d09..d7b0a8b 100644
--- a/apps/monitor/Processes.jsx
+++ b/apps/monitor/Processes.jsx
@@ -11,10 +11,10 @@
import {
View, Text, ScrollView, Segmented, SearchField, ToolbarButton, Button, GroupBox, FormRow, typeScale, spacing, useTheme, useLocale,
useStore, useSettings, useKeyboard, createStore, monitor, monitorProcesses, monitorDetail, firewall, firewallState, formatNumber,
- formatDate, formatTime, addListener,
+ formatDate, formatTime, addListener, appName,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
-import { fmt, AppGlyph, Table, Cell } from './index.jsx';
+import { fmt, AppGlyph, Table, Cell, isolatedAppOf } from './index.jsx';
const RED = '#ff453a';
@@ -31,7 +31,7 @@ const isAdmin = () => {
};
const myUid = (procs) => procs?.list.find((p) => p.self)?.uid;
-const procLabel = (tr, p) => (p.app === 'lordos' ? tr('monitor.lordos') : p.name);
+const procLabel = (tr, p) => (p.app === 'lordos' ? tr('monitor.lordos') : isolatedAppOf(p) ? appName(isolatedAppOf(p)) : p.name);
const findProc = (procs, sel) => (sel ? procs?.list.find((p) => p.pid === sel.pid && p.st === sel.st) || null : null);
// ---- icons (drawn: a circle with a cross, and a circled "i") ----
diff --git a/apps/monitor/index.jsx b/apps/monitor/index.jsx
index bcb759a..555c58c 100644
--- a/apps/monitor/index.jsx
+++ b/apps/monitor/index.jsx
@@ -5,7 +5,7 @@
// four times per second.
import {
View, Text, Image, ScrollView, Segmented, Toolbar, typeScale, useTheme, useLocale, useStore, useSettings, useAppWindow,
- useMonitor, monitor, monitorSamples, formatBytes, formatNumber, LordOSLogo, iconFromFile,
+ useMonitor, monitor, monitorSamples, formatBytes, formatNumber, LordOSLogo, iconFromFile, getApp,
} from '@lordos/sdk';
import { registerDockActions } from '@lordos/sdk';
import * as sdk from '@lordos/sdk';
@@ -352,8 +352,14 @@ function DisksTab({ s, last }) {
// ---- Processes ----
+// An isolated LordOS app (its own process and scope, "lpk:<id>"): a package or a built-in app such
+// as Mail or Passwords; the process is shown with the app's name and icon.
+export const isolatedAppOf = (item) => (typeof item?.app === 'string' && item.app.startsWith('lpk:') ? getApp(item.app.slice(4)) : null);
+
export function AppGlyph({ item, size = 16 }) {
if (item.app === 'lordos') return <LordOSLogo size={size} />;
+ const iso = isolatedAppOf(item);
+ if (iso?.Icon) return <iso.Icon size={size} />;
if (item.appIcon) return <Image src={item.appIcon} style={{ width: size, height: size, objectFit: 'contain' }} />;
const Ico = iconFromFile(null, item.appName || item.name || '?');
return <Ico size={size} />;
diff --git a/apps/passwords/manifest.json b/apps/passwords/manifest.json
index b3b4092..f923f2d 100644
--- a/apps/passwords/manifest.json
+++ b/apps/passwords/manifest.json
@@ -16,5 +16,6 @@
"usb"
],
"process": "isolated",
- "protected": true
+ "protected": true,
+ "singleWindow": true
}
diff --git a/apps/reminders/manifest.json b/apps/reminders/manifest.json
index ebded59..c2ab123 100644
--- a/apps/reminders/manifest.json
+++ b/apps/reminders/manifest.json
@@ -6,5 +6,6 @@
"minSize": [600, 400],
"dock": true,
"category": "Office",
- "permissions": []
+ "permissions": [],
+ "process": "isolated"
}
diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.json
index c1886e6..3e70209 100644
--- a/assets/locales/en/errors.json
+++ b/assets/locales/en/errors.json
@@ -264,6 +264,7 @@
"lpk.tooLarge": "The package is too large",
"lpk.writeFailed": "Could not write the app (is the disk full?)",
"mail.badAccounts": "The mail accounts are not valid",
+ "mail.denied": "This app may not ask Mail for that",
"mail.requestTooLarge": "The request to Mail is too large",
"mail.tooManyFiles": "At most {max} files at a time",
"media.audioConvertFailed": "Could not convert the audio",
diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.json
index 51eb699..6d9c893 100644
--- a/assets/locales/es/errors.json
+++ b/assets/locales/es/errors.json
@@ -264,6 +264,7 @@
"lpk.tooLarge": "El paquete es demasiado grande",
"lpk.writeFailed": "No se pudo escribir la app (¿el disco está lleno?)",
"mail.badAccounts": "Las cuentas de correo no son válidas",
+ "mail.denied": "Esta app no puede pedirle eso a Mail",
"mail.requestTooLarge": "El pedido a Mail es demasiado grande",
"mail.tooManyFiles": "Como mucho {max} archivos a la vez",
"media.audioConvertFailed": "No se pudo convertir el audio",
diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.json
index 0543704..bb8ca59 100644
--- a/assets/locales/pt/errors.json
+++ b/assets/locales/pt/errors.json
@@ -264,6 +264,7 @@
"lpk.tooLarge": "O pacote é grande demais",
"lpk.writeFailed": "Não foi possível gravar o app (o disco está cheio?)",
"mail.badAccounts": "As contas de e-mail não são válidas",
+ "mail.denied": "Este app não pode pedir isso ao Mail",
"mail.requestTooLarge": "O pedido ao Mail é grande demais",
"mail.tooManyFiles": "No máximo {max} arquivos por vez",
"media.audioConvertFailed": "Não foi possível converter o áudio",
diff --git a/runtime/app-host.js b/runtime/app-host.js
index 3e1a2e4..e12619f 100644
--- a/runtime/app-host.js
+++ b/runtime/app-host.js
@@ -110,6 +110,12 @@ globalThis.__lordBrokerEvent = (kind, data) => {
else if (data.type === 'focus') wm.focus(id);
}
else if (kind === 'window' && data && data.new) wm.open(APP, { new: true }); // Dock → «New window»
+ else if (kind === 'open' && data && data.args && typeof data.args === 'object') {
+ // the session opened this app with args (sdk/packages.js isolatedApp → lord.broker.openArgs):
+ // a notification's "Open", the Dock's "New message", a link from another system app
+ const args = data.args;
+ if (data.new || Object.keys(args).length) wm.open(APP, data.new ? { new: true, args } : { args });
+ }
else if (kind === 'quit') {
// ❖Q or Dock → Quit: close every window; a close guard can still keep one open (unsaved
// changes). The process ends when the last window closes (appclient.c).
diff --git a/sdk/apps.js b/sdk/apps.js
index ad4f9b8..9c5b3ad 100644
--- a/sdk/apps.js
+++ b/sdk/apps.js
@@ -93,6 +93,7 @@ export function launchApp(id) {
if (app && app.isolated && typeof lord.apps !== 'undefined' && typeof lord.apps.launchPackage === 'function') {
const running = windows.get().filter((w) => w.args?.pkg && w.args?.appId === id);
if (running.length) { wm.focus(running[running.length - 1].id); return true; }
+ if (globalThis.__lordTiming && lord.now) console.log(`timing: ${id} isolated launch at ${lord.now().toFixed(1)} ms (monotonic)`);
if (lord.apps.launchPackage(id)) return true;
}
return wm.open(id) != null;
diff --git a/sdk/components.jsx b/sdk/components.jsx
index 382c6e2..9b6233a 100644
--- a/sdk/components.jsx
+++ b/sdk/components.jsx
@@ -3,7 +3,7 @@
import { View, Text, addListener, displayFor } from '@lordos/runtime';
import { createContext, useContext, useEffect, useRef, useState } from 'react';
import { useTheme } from './theme.js';
-import { getApp, windows } from './windows.js';
+import { getApp, windows, openedAt } from './windows.js';
import { useStore } from './store.js';
import { textDirection } from './i18n.js';
import { ime, useIme, Preedit } from './ime.js';
@@ -303,6 +303,10 @@ export function AppHost({ id, focused }) {
// the window's overlay host (sdk/layers.js): lists and popovers of an isolated app's process go
// here, above all of the window's content; in the desktop's process they go to the shell layers
const [overlayHost, setOverlayHost] = useState(null);
+ useEffect(() => { // developer timing: open → first commit of this window
+ const t0 = openedAt.get(id);
+ if (t0 != null && app && !app.isolated) { openedAt.delete(id); console.log(`timing: ${app.id} window committed ${(lord.now() - t0).toFixed(1)} ms after wm.open`); }
+ }, []);
if (!app) return null;
const C = app.Component;
// the content goes in its own node: `protected` paints it black in screenshots (wm.setProtected)
diff --git a/sdk/dock.js b/sdk/dock.js
index bf1a309..1c92a50 100644
--- a/sdk/dock.js
+++ b/sdk/dock.js
@@ -251,6 +251,9 @@ addListener('keydown', (e) => {
// ---- quick actions ----
+// Can the session hand args and «new window» to an isolated built-in app's process?
+const isolatedArgs = () => typeof lord !== 'undefined' && !!lord.broker && typeof lord.broker.openArgs === 'function';
+
// The quick actions of a Dock item: a LordOS app's (manifest "dockActions" + registerDockActions),
// or a Linux app's desktop actions (Actions= in its .desktop, run by lord.apps.launchAction).
export function dockQuickActions(e) {
@@ -264,7 +267,9 @@ export function dockQuickActions(e) {
}
if (p.kind !== 'app') return []; // .lpk: launchPackage takes no arguments
const app = getApp(p.key);
- if (!app || app.isolated) return [];
+ // an isolated built-in app (its own process) gets the action's args through the session
+ // (sdk/packages.js isolatedApp → lord.broker.openArgs)
+ if (!app || (app.isolated && !isolatedArgs())) return [];
let fromModule = [];
try { fromModule = actionProviders.get(p.key)?.() || []; } catch (err) { fromModule = []; }
return cleanActions([...(Array.isArray(app.dockActions) ? app.dockActions : []), ...fromModule]).map((a) => ({
@@ -291,7 +296,10 @@ export function dockMenu(e, opts = {}) {
const appKey = p && p.kind === 'app' ? p.key : null;
const custom = appKey && menuProviders.get(appKey) ? menuProviders.get(appKey)(e) : null;
if (custom && custom.length) items.push(...custom, '-');
- else if (e.windows.length && p) items.push({ label: t('shell.dock.newWindow'), onClick: () => (appKey && !getApp(appKey)?.isolated ? wm.open(appKey, { new: true }) : launchDockItem(e.id)) }, '-');
+ else if (e.windows.length && p && !(appKey && getApp(appKey)?.singleWindow)) {
+ const iso = appKey && getApp(appKey)?.isolated;
+ items.push({ label: t('shell.dock.newWindow'), onClick: () => (appKey && (!iso || isolatedArgs()) ? wm.open(appKey, { new: true }) : launchDockItem(e.id)) }, '-');
+ }
if (p) {
const options = [];
if (!dock.isPinned(e.id)) options.push({ label: opts.keepLabel || t('shell.dock.keep'), onClick: () => dock.pin(e.id) });
diff --git a/sdk/index.js b/sdk/index.js
index 8827657..061655c 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -53,7 +53,7 @@ export * as fwRule from './fwrule.js'; // checks what the user types
export { packages, packageList, refreshPackages, packageFile, loadWasm } from './packages.js';
import { refreshPackages } from './packages.js';
export {
- windows, wm, useWindows, configureWindows, getApp, listApps, isLiveSystem, appIdOf, workArea, workAreaOf, pointerWorkArea, appMenus, useAppMenus, windowTitle, appRegistry, appMenuClick,
+ windows, wm, openedAt, useWindows, configureWindows, getApp, listApps, isLiveSystem, appIdOf, workArea, workAreaOf, pointerWorkArea, appMenus, useAppMenus, windowTitle, appRegistry, appMenuClick,
registerBuiltinApp,
} from './windows.js';
export { WindowShell, WINDOW_EDGE } from './windowshell.jsx';
@@ -93,9 +93,10 @@ export { lordosUpdate, restartNeeded, updatePrefs, setUpdatePrefs, UPDATE_DEFAUL
export { vaultAvailable, vaultRequest, onVaultEvent, keyring, autofill, autofillReveal, KeyringPrompt, AutofillButton } from './vault.js'; // Passwords and keyring (docs/PASSWORDS.md)
import { KeyringPrompt } from './vault.js';
// Mail, Calendar, Contacts and Reminders through the sandboxed helper lord-maild (docs/MAIL.md)
-export { mailAvailable, mailRequest, onMailEvent, mailConfig, mailAccounts, mailStatus, autoconfig, OAUTH_PROVIDERS } from './mail.js';
+export { mailAvailable, mailRequest, onMailEvent, mailConfig, mailAccounts, mailStatus, autoconfig, OAUTH_PROVIDERS, trackMailStatus, isolatedPim, pickFileFd, closeFileFd } from './mail.js';
export { calendars, events as calendarEvents, reminders, usePim, usePimQuery, pimRev, startOfDay } from './calendar.js';
export { FilePicker } from './filepicker.jsx';
+export { openFileWithApps, revealPath } from './sysopen.js'; // opening files/apps for the isolated system apps
export { books as addressBooks, contacts, displayName as contactName, initials as contactInitials, ContactPhoto } from './contacts.js';
import { startMail } from './mail.js';
import { startReminders } from './calendar.js';
diff --git a/sdk/mail.js b/sdk/mail.js
index 7361249..badcb83 100644
--- a/sdk/mail.js
+++ b/sdk/mail.js
@@ -4,7 +4,8 @@
// so the desktop never waits for the network.
//
// mailAvailable() is lord-maild installed?
-// mailRequest(op, args, { files }) → promise with the reply, or an Error with .code
+// mailRequest(op, args, { files }) → promise with the reply, or an Error with .code; files are paths, or
+// { fd } in an isolated app (lord.mail.appMode)
// onMailEvent(fn) events: new, changed, folders, status, need-auth, auth-failed,
// cert, sent, send-failed, pim-changed, crash
// mailConfig.get() / mailConfig.save(cfg) the accounts file (no passwords: those live in the keyring)
@@ -23,6 +24,19 @@ import { wm, getApp } from './windows.js';
const has = () => typeof lord !== 'undefined' && typeof lord.mail !== 'undefined';
export const mailAvailable = () => has() && lord.mail.available();
+// Mail, Calendar, Contacts and Reminders in their own process (lord.mail.appMode): files come from
+// the system file dialog as fds, never as paths.
+export const isolatedPim = () => has() && !!lord.mail.appMode;
+// → { fd, name, size } | null; the system draws the dialog, this process only gets the fd
+export function pickFileFd() {
+ if (typeof lord === 'undefined' || !lord.broker || typeof lord.broker.pick !== 'function') return null;
+ const r = lord.broker.pick(false, '');
+ if (!r) return null;
+ const size = typeof lord.broker.fdSize === 'function' ? lord.broker.fdSize(r.fd) : -1;
+ return { fd: r.fd, name: r.name, size: size > 0 ? size : 0 };
+}
+export const closeFileFd = (f) => { if (f && typeof f === 'object' && f.fd >= 0) { try { lord.broker.fdClose(f.fd); } catch (e) { /* closed */ } } };
+
const waiting = new Map();
const listeners = new Set();
let fast = null, slow = null;
@@ -57,7 +71,9 @@ function startSlow() { if (!slow && has()) slow = setInterval(pump, 500); }
export function mailRequest(op, args = {}, { files } = {}) {
if (!has()) return Promise.reject(Object.assign(new Error('unavailable'), { code: 'unavailable' }));
let id;
- try { id = lord.mail.request(JSON.stringify({ op, ...args }), files && files.length ? files : undefined); }
+ // a file is a path (in the session) or { fd } (the isolated apps: an fd from the system file dialog)
+ const list = files && files.length ? files.map((f) => (f && typeof f === 'object' ? f.fd : f)) : undefined;
+ try { id = lord.mail.request(JSON.stringify({ op, ...args }), list); }
catch (e) { return Promise.reject(Object.assign(new Error(e.message), { code: 'file' })); }
if (id < 0) return Promise.reject(Object.assign(new Error('unavailable'), { code: 'unavailable' }));
startSlow();
@@ -198,6 +214,35 @@ function openMessage(acct, folder, uid) {
if (getApp('mail')) wm.open('mail', { args: { acct, folder, uid, nonce: Date.now() } });
}
+// In the isolated Mail app (lord-server --app mail, lord.mail.appMode) startMail never runs: the
+// session keeps notifications, the unread count and passwords on demand. The app keeps its own copy
+// of the account status from the events lord-server forwards to it (sec/brokermail.c), seeded with
+// lord-maild's current status.
+let tracking = false;
+export function trackMailStatus() {
+ if (tracking || !has() || !lord.mail.appMode) return;
+ tracking = true;
+ onMailEvent(async (ev) => {
+ if (ev.ev === 'status') mailStatus.set((s) => ({ ...s, accounts: { ...s.accounts, [ev.acct]: { status: ev.status, error: ev.error } } }));
+ else if (ev.ev === 'cert') mailStatus.set((s) => ({ ...s, certs: [...s.certs.filter((c) => !(c.acct === ev.acct && c.host === ev.host)), ev] }));
+ else if (ev.ev === 'auth-failed') mailStatus.set((s) => ({ ...s, authFailed: { ...s.authFailed, [ev.acct]: true } }));
+ else if (ev.ev === 'need-auth') {
+ // the session answers too; here it only matters whether a password exists at all
+ const a = mailAccounts.get(ev.acct);
+ const pw = a ? await passwordFor(a) : null;
+ if (pw) mailRequest('auth', { acct: ev.acct, password: pw }).catch(() => {});
+ else mailStatus.set((s) => ({ ...s, authFailed: { ...s.authFailed, [ev.acct]: true } }));
+ } else if (ev.ev === 'new' || ev.ev === 'changed' || ev.ev === 'folders' || ev.ev === 'ready') refreshCounts();
+ });
+ lord.mail.start();
+ mailRequest('status').then((st) => {
+ const accounts = {};
+ for (const a of st.accounts || []) accounts[a.id] = { status: a.status, error: a.error };
+ mailStatus.set((s) => ({ ...s, accounts: { ...accounts, ...s.accounts } }));
+ }).catch(() => {});
+ refreshCounts();
+}
+
export function startMail() {
if (started || !has() || !lord.mail.available()) return;
started = true;
diff --git a/sdk/packages.js b/sdk/packages.js
index fa6947f..6962d9f 100644
--- a/sdk/packages.js
+++ b/sdk/packages.js
@@ -69,12 +69,29 @@ export function isolatedApp(id, Fallback) {
const win = sdk.useAppWindow();
const [inproc, setInproc] = React.useState(false);
React.useEffect(() => {
- // already running: focus its window (a single window: it holds a vault)
const running = windows.get().filter((w) => w.args?.pkg && w.args?.appId === id);
- if (isolated() && running.length) { wm.focus(running[running.length - 1].id); if (win && win.id) wm.close(win.id, true); }
- else if (isolated() && lord.apps.launchPackage(id)) { if (win && win.id) wm.close(win.id, true); }
+ // what the window was opened with (a notification's "Open", the Dock's "New message", another
+ // app's link) goes to the app process: now if it runs, or when it starts (lord.broker.openArgs)
+ // a single-window app (manifest "singleWindow": Passwords holds one vault view) only gets focused
+ const wantsNew = !!(win && win.id && String(win.id).includes('#')) && !sdk.getApp(id)?.singleWindow;
+ const { nonce, ...args } = win?.args || {};
+ const hasArgs = Object.keys(args).length > 0;
+ const forward = () => { if ((hasArgs || wantsNew) && lord.broker && typeof lord.broker.openArgs === 'function') lord.broker.openArgs(id, JSON.stringify(args), wantsNew); };
+ if (globalThis.__lordTiming && lord.now) {
+ const t0 = sdk.openedAt?.get(win?.id);
+ console.log(`timing: ${id} isolated launch at ${lord.now().toFixed(1)} ms (monotonic)${t0 != null ? `, ${(lord.now() - t0).toFixed(1)} ms after wm.open at ${t0.toFixed(1)}` : ''}`);
+ }
+ if (isolated() && running.length) {
+ forward();
+ if (!wantsNew) wm.focus(running[running.length - 1].id);
+ if (win && win.id) wm.close(win.id, true);
+ } else if (isolated() && lord.apps.launchPackage(id)) { forward(); if (win && win.id) wm.close(win.id, true); }
else setInproc(true);
}, []);
+ React.useEffect(() => { // developer timing of the in-process fallback
+ const t0 = inproc && globalThis.__lordTiming ? sdk.openedAt?.get(win?.id) : null;
+ if (t0 != null) { sdk.openedAt.delete(win.id); console.log(`timing: ${id} in-process window committed ${(lord.now() - t0).toFixed(1)} ms after wm.open`); }
+ }, [inproc]);
return inproc && Fallback ? h(Fallback, props) : null;
};
}
diff --git a/sdk/privacy.js b/sdk/privacy.js
index e30b90c..4096f03 100644
--- a/sdk/privacy.js
+++ b/sdk/privacy.js
@@ -60,6 +60,10 @@ if (typeof globalThis !== 'undefined') {
if (typeof globalThis.__lordApplyAppMenus === 'function') globalThis.__lordApplyAppMenus(data.app);
} else if (kind === 'pick') {
if (typeof globalThis.__lordBrokerPick === 'function') globalThis.__lordBrokerPick(data.reqid, data.app, data.save, data.suggest);
+ } else if (kind === 'mailopen' || kind === 'launch') {
+ // an isolated system app asked the session to open an attachment or another app; lord-server
+ // checked it (sec/brokermail.c), sdk/sysopen.js does it
+ if (typeof globalThis.__lordSysOpen === 'function') globalThis.__lordSysOpen(kind, data);
} else if (kind === 'device') {
if (data.off) brokerDevicesByApp(data.app, null, false);
else brokerDevicesByApp(data.app, data.kind, !!data.on);
diff --git a/sdk/settings.js b/sdk/settings.js
index 3ff6496..1b4dcf0 100644
--- a/sdk/settings.js
+++ b/sdk/settings.js
@@ -40,6 +40,9 @@ function load() {
}
export const settings = createStore(load());
+// Developer timing (settings.json "debugTiming": true, no UI): opening an app logs how long its
+// first window took (sdk/components.jsx AppHost, sdk/packages.js isolatedApp, docs/PRIVACY.md).
+globalThis.__lordTiming = !!settings.get().debugTiming;
let pending = 0;
settings.subscribe(() => {
diff --git a/sdk/sysopen.js b/sdk/sysopen.js
new file mode 100644
index 0000000..20bcc71
--- /dev/null
+++ b/sdk/sysopen.js
@@ -0,0 +1,52 @@
+// sysopen.js — opening things for the isolated system apps (docs/PRIVACY.md, "System apps in their
+// own process"). Mail, Calendar, Contacts and Reminders run as `lord-server --app <id>` and cannot
+// open files or other apps themselves; lord-server checks what they ask (sec/brokermail.c) and the
+// session does it here:
+//
+// openFileWithApps(path, name) the same rules as Files: our apps for documents, images and media,
+// the default app for the rest, otherwise reveal it in Files. Used by
+// Mail in-process and, for the isolated Mail, on a cached attachment
+// lord-server validated ("mailopen" broker event).
+// revealPath(path)
+// "launch" broker event one of these apps opens another one with args (no paths).
+import { wm, getApp } from './windows.js';
+import * as fs from './fs.js';
+import { defaultOpenerId, nativeOf } from './defaults.js';
+import { events as calendarEvents } from './calendar.js';
+import { books as addressBooks, contacts } from './contacts.js';
+
+export const revealPath = (path) => wm.open('files', { new: true, args: { path: fs.parent(path), select: fs.basename(path), nonce: Date.now() } });
+
+export function openFileWithApps(path, name) {
+ const n = String(name || path).toLowerCase();
+ if (/\.pdf$/.test(n) && getApp('pdf')) return wm.open('pdf', { new: true, args: { path } });
+ if (/\.(png|jpe?g|gif|webp|bmp|heic|avif)$/.test(n) && getApp('photos')) return wm.open('photos', { new: true, args: { path } });
+ if (/\.(mp3|ogg|flac|wav|m4a|opus|mp4|mkv|webm|mov|avi)$/.test(n) && getApp('player')) return wm.open('player', { args: { path } });
+ if (/\.(txt|md|csv|log|json|xml|ya?ml|c|h|js|py|sh)$/.test(n) && getApp('editor')) return wm.open('editor', { args: { path } });
+ if (/\.ics$/.test(n) && getApp('calendar')) { calendarEvents.importFile(path).then(() => wm.open('calendar')).catch(() => revealPath(path)); return true; }
+ if (/\.vcf$/.test(n) && getApp('contacts')) {
+ addressBooks.list().then((b) => (b[0] ? contacts.importFile(path, b[0].id) : null)).then(() => wm.open('contacts')).catch(() => revealPath(path));
+ return true;
+ }
+ try {
+ const def = defaultOpenerId(typeof lord !== 'undefined' && lord.mime ? lord.mime.guess(n) : '');
+ const native = nativeOf(def);
+ if (native && getApp(native)) return wm.open(native, { new: true, args: { path } });
+ if (def && lord.apps.launchWith(def.replace(/\.desktop$/, ''), path)) return true;
+ if (lord.apps.launchWith('', path)) return true;
+ } catch (e) { /* no default app */ }
+ return revealPath(path);
+}
+
+// the session side (privacy.js forwards these broker events here)
+const SYSTEM_APPS = ['mail', 'calendar', 'contacts', 'reminders'];
+if (typeof globalThis !== 'undefined') {
+ globalThis.__lordSysOpen = (kind, data) => {
+ if (!data) return;
+ if (kind === 'mailopen' && typeof data.path === 'string') openFileWithApps(data.path, data.name);
+ else if (kind === 'launch' && SYSTEM_APPS.includes(data.app) && getApp(data.app)) {
+ const args = data.args && typeof data.args === 'object' ? data.args : {};
+ wm.open(data.app, data.new ? { new: true, args } : { args });
+ }
+ };
+}
diff --git a/sdk/windows.js b/sdk/windows.js
index c671490..cee8cb0 100644
--- a/sdk/windows.js
+++ b/sdk/windows.js
@@ -159,15 +159,28 @@ globalThis.__lordWm = (type, d) => {
patch(id, { x: Math.round(f.x + d.dx), y: Math.round(f.y + d.dy), w: Math.round(f.w + d.dw), h: Math.round(f.h + d.dh), maximized: false });
};
+// when each window was opened (lord.now()), for the developer timing log (settings "debugTiming")
+export const openedAt = new Map();
+
export const wm = {
// opts: { new: true } another window of the same app; { instance: 'x' } named window;
// { frame: { x, y, w, h } } initial geometry; { args: {...} } data for the app
// (e.g. wm.open('files', { args: { path: '/home/lord/Documentos' } })).
// Returns the window id.
open(appId, opts = {}) {
- if (!registry.has(appId)) { console.warn('app desconocida:', appId); return null; }
+ if (!registry.has(appId)) {
+ // inside an isolated system app (lord-server --app): another system app is opened by the
+ // session, through the broker (Mail → Calendar, Contacts → a new message; sec/brokermail.c)
+ if (typeof lord !== 'undefined' && typeof lord.appId === 'string' && lord.broker && typeof lord.broker.openApp === 'function') {
+ lord.broker.openApp(String(appId), JSON.stringify(opts.args || {}), !!opts.new);
+ return null;
+ }
+ console.warn('unknown app:', appId);
+ return null;
+ }
const id = opts.instance ? `${appId}#${opts.instance}` : opts.new ? `${appId}#${seq++}` : appId;
const args = opts.args ? { ...opts.args, nonce: seq++ } : null;
+ if (globalThis.__lordTiming && typeof lord !== 'undefined' && lord.now) openedAt.set(id, lord.now());
windows.set((ws) => (ws.some((w) => w.id === id)
? raise(ws, id).map((w) => (w.id === id && args ? { ...w, args } : w))
: [...ws, { id, app: appId, title: null, args, ...place(appId, ws.length, opts.frame) }]));
diff --git a/server/Makefile b/server/Makefile
index 832ff4f..65f74c0 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -51,9 +51,9 @@ QJS_OBJ := $(patsubst %,build/qjs/%.o,quickjs libregexp libunicode cutils dtoa)
MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/proc_admin.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c
# Media (src/media, docs/MEDIA.md): only the lord-server side. Only lord-media links FFmpeg.
MEDIA_SRC := src/media/media.c src/media/mview.c src/media/capture.c src/media/annot.c src/media/maudio.c src/media/mpulse.c src/media/proto.c src/ui/js_media.c
-SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c src/sec/restrict.c src/sec/appid.c src/sec/pwguard.c
+SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c src/sec/brokermail.c src/sec/restrict.c src/sec/appid.c src/sec/pwguard.c
# App mode: lord-server --app <id> runs an .lpk app as an isolated Wayland client (src/app)
-APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.c
+APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.c src/ui/js_brokermail.c src/app/apphost_bc.c
SRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/remote/ssh_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/keylag.c src/ime.c src/wl/wl.c \
src/ui/node.c src/ui/style.c src/ui/layout.c src/ui/transform.c src/ui/text.c src/ui/image.c \
src/ui/paint.c src/ui/js.c src/ui/js_sys.c src/ui/js_term.c src/ui/js_wasm.c src/wasm/wasm.c src/wasm/wasm_run.c src/ui/js_sound.c src/ui/js_net.c src/sound/snd.c src/sound/pulse.c src/ui/otf.c src/ui/fonts.c \
@@ -237,6 +237,12 @@ build/broker-restrict-test: tests/broker_restrict_test.c $(BROKER_RESTRICT_SRC)
@mkdir -p build
$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/broker_restrict_test.c $(BROKER_RESTRICT_SRC) -Wl,--wrap=open
./$@ || { rm -f $@; exit 1; }
+# lord-maild for the isolated system apps (src/sec/brokermail.c): who may ask what, files, Mail-only verbs
+test: build/brokermail-test
+build/brokermail-test: tests/brokermail_test.c src/sec/brokermail.c src/sec/json.c $(wildcard src/sec/*.h src/mail/*.h)
+ @mkdir -p build
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/brokermail_test.c src/sec/brokermail.c src/sec/json.c
+ ./$@ || { rm -f $@; exit 1; }
# tests/launch_cli.c: the real Linux app launcher outside the desktop, for tests/fwlinux/files.sh
# (built by `make test`, run by that script in the VM)
LAUNCH_CLI_SRC := src/apps.c src/fsops.c src/hw/defaults.c src/hw/mimeapps.c src/sec/cgroup.c src/sec/sandbox.c \
diff --git a/server/src/app/appclient.c b/server/src/app/appclient.c
index 7f64c15..d363b7c 100644
--- a/server/src/app/appclient.c
+++ b/server/src/app/appclient.c
@@ -30,6 +30,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
+#include <sys/prctl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
@@ -67,6 +68,8 @@ typedef struct {
} AppWin;
static AppWin wins[MAX_WINS];
static int next_key = 1, closed;
+static double t_start; /* app_main entry (CLOCK_MONOTONIC ms), for the first-frame log */
+static int first_frame_logged;
static const char *app_id_str = "";
static AppWin *ptr_win, *kbd_win; /* window under the pointer / with keyboard focus */
@@ -148,6 +151,11 @@ static void render(AppWin *w) {
w->frame_pending = 1;
wl_surface_commit(w->surf);
w->need_render = 0;
+ if (!first_frame_logged && w->key == 0) { /* one line: how long the app took to show */
+ first_frame_logged = 1;
+ double t = now_ms();
+ fprintf(stderr, "app %s: first frame %.1f ms after the process started (at %.1f ms, monotonic)\n", app_id_str, t - t_start, t);
+ }
}
static void frame_done(void *d, struct wl_callback *cb, uint32_t t) {
@@ -457,7 +465,11 @@ static int manifest_pair(const char *dir, const char *key, int *w, int *h) {
}
int app_main(const char *id, const char *theme_bundle, const char *fonts) {
+ t_start = now_ms();
if (!lpk_valid_id(id)) { fprintf(stderr, "lord-server --app: invalid id\n"); return 2; }
+ /* the process name is the app's id ("mail"), not "exe" (it was started through /proc/self/exe):
+ * ps, top and the Monitor's process list show which app it is */
+ prctl(PR_SET_NAME, id, 0, 0, 0);
char dir[PATH_MAX];
{
/* <assets> = the parent of the fonts folder; a system app there wins over a user .lpk */
@@ -509,6 +521,9 @@ int app_main(const char *id, const char *theme_bundle, const char *fonts) {
snprintf(langs, sizeof langs, "%s/.local/share/lordos/locales", home ? home : "/nonexistent");
const char *ro[] = { fonts, hostdir, "/usr/share/fonts", langs, NULL }; /* + fuentes del sistema (emoji, respaldo por escritura) */
SandboxConfig sb = { .id = id, .pkg_dir = dir, .data_dir = data, .runtime_dir = getenv("XDG_RUNTIME_DIR"), .ro_extra = ro, .network = net };
+ /* the local time zone is read now (libc keeps it): /etc/localtime and the zone files are
+ * outside the sandbox, and without this dates in Mail and Calendar would be in UTC */
+ tzset();
sandbox_apply(&sb);
if (js_init_app(theme_bundle, id)) { fprintf(stderr, "lord-server --app: could not load the app\n"); return 1; }
diff --git a/server/src/app/apphost_bc.c b/server/src/app/apphost_bc.c
new file mode 100644
index 0000000..84ef034
--- /dev/null
+++ b/server/src/app/apphost_bc.c
@@ -0,0 +1,136 @@
+/* apphost_bc.c — the app host (assets/app-host.bundle.js: React, the runtime and the SDK) compiled
+ * to QuickJS bytecode once per session, so an isolated app does not parse 430 KB of JavaScript
+ * every time it starts (~80 ms on a 1.8 GHz core; reading the bytecode takes ~3 ms).
+ *
+ * lord-server compiles it on a thread of its own, with its own QuickJS runtime, a few seconds
+ * after the session starts, into a sealed memfd. app_spawn() hands the app process a read-only fd
+ * of it (LORD_APPHOST_BC_FD). The app uses it only if the header names the very file it would
+ * load (device, inode, size, modification time); otherwise, or with no fd, it parses the source as
+ * before. The bytecode comes from lord-server (the same binary and QuickJS), never from the app or
+ * from a file a user can write. */
+#include "apphost_bc.h"
+#include "quickjs.h"
+
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#define BC_MAGIC "LORDQBC1"
+#define BC_MAX (64u << 20)
+
+typedef struct {
+ char magic[8];
+ uint64_t dev, ino, size;
+ int64_t mtime_sec, mtime_nsec;
+ uint64_t len; /* bytecode bytes that follow */
+} BcHeader;
+
+static _Atomic int bc_fd = -1;
+static char bc_path[1024];
+
+static void header_of(const struct stat *st, BcHeader *h) {
+ memset(h, 0, sizeof *h);
+ memcpy(h->magic, BC_MAGIC, 8);
+ h->dev = (uint64_t)st->st_dev;
+ h->ino = (uint64_t)st->st_ino;
+ h->size = (uint64_t)st->st_size;
+ h->mtime_sec = (int64_t)st->st_mtim.tv_sec;
+ h->mtime_nsec = (int64_t)st->st_mtim.tv_nsec;
+}
+
+static void *compile_thread(void *arg) {
+ (void)arg;
+ struct timespec pause = { 3, 0 }; /* after the desktop has drawn its first frames */
+ nanosleep(&pause, NULL);
+ int fd = open(bc_path, O_RDONLY | O_CLOEXEC);
+ struct stat st;
+ if (fd < 0 || fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size <= 0 || st.st_size > (off_t)BC_MAX) { if (fd >= 0) close(fd); return NULL; }
+ char *src = malloc((size_t)st.st_size + 1);
+ ssize_t got = src ? read(fd, src, (size_t)st.st_size) : -1;
+ close(fd);
+ if (got != st.st_size) { free(src); return NULL; }
+ src[got] = 0;
+ JSRuntime *rt = JS_NewRuntime();
+ JSContext *cx = rt ? JS_NewContext(rt) : NULL;
+ uint8_t *bc = NULL;
+ size_t bl = 0;
+ if (cx) {
+ JSValue fn = JS_Eval(cx, src, (size_t)got, bc_path, JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_COMPILE_ONLY);
+ if (!JS_IsException(fn)) bc = JS_WriteObject(cx, &bl, fn, JS_WRITE_OBJ_BYTECODE);
+ else JS_FreeValue(cx, JS_GetException(cx));
+ JS_FreeValue(cx, fn);
+ }
+ free(src);
+ int mfd = -1;
+ if (bc && bl && bl < BC_MAX) {
+ BcHeader h;
+ header_of(&st, &h);
+ h.len = bl;
+ mfd = memfd_create("lordos-apphost-bc", MFD_CLOEXEC | MFD_ALLOW_SEALING);
+ int ok = mfd >= 0 && write(mfd, &h, sizeof h) == (ssize_t)sizeof h;
+ size_t off = 0;
+ while (ok && off < bl) { ssize_t w = write(mfd, bc + off, bl - off); if (w <= 0) ok = 0; else off += (size_t)w; }
+ ok = ok && !fcntl(mfd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL);
+ if (!ok && mfd >= 0) { close(mfd); mfd = -1; }
+ }
+ if (bc) js_free(cx, bc);
+ if (cx) JS_FreeContext(cx);
+ if (rt) JS_FreeRuntime(rt);
+ if (mfd >= 0) {
+ atomic_store(&bc_fd, mfd);
+ fprintf(stderr, "lord-server: app host compiled to bytecode (%zu KB) for isolated apps\n", bl / 1024);
+ }
+ return NULL;
+}
+
+void apphost_bc_start(const char *bundle_path) {
+ static int started;
+ if (started || !bundle_path || strlen(bundle_path) >= sizeof bc_path) return;
+ started = 1;
+ snprintf(bc_path, sizeof bc_path, "%s", bundle_path);
+ pthread_t t;
+ pthread_attr_t at;
+ pthread_attr_init(&at);
+ pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
+ if (pthread_create(&t, &at, compile_thread, NULL)) fprintf(stderr, "lord-server: no thread for the app host bytecode\n");
+ pthread_attr_destroy(&at);
+}
+
+int apphost_bc_dup_ro(void) {
+ int fd = atomic_load(&bc_fd);
+ if (fd < 0) return -1;
+ char proc[64];
+ snprintf(proc, sizeof proc, "/proc/self/fd/%d", fd);
+ return open(proc, O_RDONLY | O_CLOEXEC); /* read-only: the app can only map it PROT_READ */
+}
+
+int apphost_bc_eval(JSContext *ctx, const char *bundle_path, int fd, int *ok) {
+ *ok = 0;
+ struct stat st, fst;
+ if (fd < 0 || !bundle_path || stat(bundle_path, &st) || fstat(fd, &fst) || fst.st_size < (off_t)sizeof(BcHeader) || fst.st_size > (off_t)BC_MAX) return -1;
+ void *m = mmap(NULL, (size_t)fst.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
+ if (m == MAP_FAILED) return -1;
+ BcHeader want, h;
+ header_of(&st, &want);
+ memcpy(&h, m, sizeof h);
+ want.len = h.len;
+ if (memcmp(&h, &want, sizeof h) || h.len != (uint64_t)fst.st_size - sizeof h) { munmap(m, (size_t)fst.st_size); return -1; }
+ JSValue fn = JS_ReadObject(ctx, (const uint8_t *)m + sizeof h, (size_t)h.len, JS_READ_OBJ_BYTECODE);
+ munmap(m, (size_t)fst.st_size);
+ if (JS_IsException(fn)) { JS_FreeValue(ctx, JS_GetException(ctx)); return -1; }
+ JSValue r = JS_EvalFunction(ctx, fn); /* takes fn */
+ *ok = !JS_IsException(r);
+ if (!*ok) { /* it ran: the caller reports the exception, not a fallback */
+ JS_FreeValue(ctx, r);
+ return 1;
+ }
+ JS_FreeValue(ctx, r);
+ return 0;
+}
diff --git a/server/src/app/apphost_bc.h b/server/src/app/apphost_bc.h
new file mode 100644
index 0000000..9416664
--- /dev/null
+++ b/server/src/app/apphost_bc.h
@@ -0,0 +1,18 @@
+/* apphost_bc.h — the app host compiled to QuickJS bytecode once per session (see apphost_bc.c). */
+#ifndef LORD_APPHOST_BC_H
+#define LORD_APPHOST_BC_H
+
+#include "quickjs.h"
+
+#define APPHOST_BC_ENV "LORD_APPHOST_BC_FD"
+
+/* lord-server: compile <bundle_path> on a thread of its own, a few seconds from now (once). */
+void apphost_bc_start(const char *bundle_path);
+/* lord-server: a read-only fd of the bytecode for a new app process, or -1 if not ready yet. */
+int apphost_bc_dup_ro(void);
+/* The app process: run the bytecode in fd if it was compiled from exactly <bundle_path>.
+ * -1: not usable (parse the source instead); 0: ran (*ok = 1); 1: ran and threw (*ok = 0, the
+ * exception is pending in ctx). */
+int apphost_bc_eval(JSContext *ctx, const char *bundle_path, int fd, int *ok);
+
+#endif
diff --git a/server/src/app/appspawn.c b/server/src/app/appspawn.c
index bc3fdfc..a91e62b 100644
--- a/server/src/app/appspawn.c
+++ b/server/src/app/appspawn.c
@@ -8,6 +8,7 @@
#include "../sec/broker.h"
#include "../ui/js_sys.h"
#include "../vault/vclient.h"
+#include "apphost_bc.h"
#include <fcntl.h>
#include <limits.h>
@@ -65,6 +66,7 @@ int app_spawn(const char *id) {
if (pipe2(pp, O_CLOEXEC)) { close(sv[0]); close(sv[1]); return -1; }
/* Passwords talks to lord-vault on its own channel: decrypted data never passes through here */
int vfd = wants_vault(id, sys) ? vc_attach_app() : -1;
+ int bcfd = apphost_bc_dup_ro();
pid_t pid = fork();
if (pid == 0) {
@@ -85,6 +87,12 @@ int app_spawn(const char *id) {
snprintf(vstr, sizeof vstr, "%d", vfd);
setenv("LORD_VAULT_FD", vstr, 1);
} else unsetenv("LORD_VAULT_FD");
+ if (bcfd >= 0) { /* the app host as bytecode (apphost_bc.c), read-only */
+ char bstr[16];
+ fcntl(bcfd, F_SETFD, 0);
+ snprintf(bstr, sizeof bstr, "%d", bcfd);
+ setenv(APPHOST_BC_ENV, bstr, 1);
+ } else unsetenv(APPHOST_BC_ENV);
int null = open("/dev/null", O_RDWR);
if (null >= 0) { dup2(null, 0); if (null > 2) close(null); }
/* lord-server passes the id, already validated; there are no caller arguments */
@@ -95,6 +103,7 @@ int app_spawn(const char *id) {
close(sv[1]);
close(pp[1]);
if (vfd >= 0) close(vfd);
+ if (bcfd >= 0) close(bcfd);
if (pid < 0) { close(sv[0]); close(pp[0]); return -1; }
waitpid(pid, NULL, 0); /* the intermediate child exits right away */
pid_t app = -1;
@@ -102,6 +111,7 @@ int app_spawn(const char *id) {
close(pp[0]);
if (brokersrv_add(sv[0], id, (int)app)) { close(sv[0]); return -1; }
if (vfd >= 0) brokersrv_set_vault(sv[0]); /* this app may also ask for the FIDO2 device */
+ if (sys == 1) brokersrv_set_system(sv[0]); /* a system package: its keyring owner, lord-maild (brokermail.c) */
fprintf(stderr, "lord-server: app '%s' started as an isolated process (pid %d)\n", id, (int)app);
return 0;
}
diff --git a/server/src/mail/mailc.c b/server/src/mail/mailc.c
index d9af5e2..6c0b7d4 100644
--- a/server/src/mail/mailc.c
+++ b/server/src/mail/mailc.c
@@ -37,7 +37,15 @@ extern char **environ;
typedef struct { char host[256]; int port; int suffix; } Allow;
typedef struct { char host[256]; int port; time_t until; } Grant;
-typedef struct { int handle, w, h; uint32_t *px; uint64_t seq; } Img;
+typedef struct { int handle, w, h, owner; uint32_t *px; uint64_t seq; } Img;
+
+/* Isolated system apps (Mail, Calendar, Contacts, Reminders as `lord-server --app <id>`): each
+ * app process is an "owner" with its own event queue. Replies to its requests go only there; the
+ * events lord-maild broadcasts go to the session (owner 0) and to every owner whose mask allows
+ * them. brokermail.c reads these queues and forwards them over the broker. */
+typedef struct { int used, mask; JBuf ev; } Owner;
+typedef struct { int id, owner; } Route;
+#define MAX_ROUTE 512
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t send_mu = PTHREAD_MUTEX_INITIALIZER;
@@ -56,6 +64,9 @@ static size_t img_bytes;
static uint64_t img_seq;
static int next_handle = 1;
static double last_crash;
+static Owner owners[MAIL_OWNERS + 1]; /* index 1..MAIL_OWNERS; 0 is the session (events) */
+static Route routes[MAX_ROUTE];
+static int owner_wake = -1;
static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; }
@@ -243,20 +254,71 @@ static int allowed_now(const char *host, int port) {
/* ---- events ---- */
-static void ev_push(int id, const char *type, const char *data, size_t dlen) {
- pthread_mutex_lock(&mu);
- if (events.n) jb_raw(&events, ",");
- jb_printf(&events, "{\"id\":%d,\"type\":\"%s\"", id, type);
+static void ev_append(JBuf *dst, int id, const char *type, const char *data, size_t dlen) {
+ if (dst->n) jb_raw(dst, ",");
+ jb_printf(dst, "{\"id\":%d,\"type\":\"%s\"", id, type);
if (data && dlen) {
- jb_raw(&events, ",\"data\":");
+ jb_raw(dst, ",\"data\":");
/* the helper's JSON is re-validated before JS sees it */
JDoc d;
- if (!json_parse(data, dlen, &d, NULL, 0)) { json_free(&d); char *tmp = malloc(dlen + 1); if (tmp) { memcpy(tmp, data, dlen); tmp[dlen] = 0; jb_raw(&events, tmp); free(tmp); } else jb_raw(&events, "null"); }
- else jb_raw(&events, "{\"error\":\"bad-json\"}");
+ if (!json_parse(data, dlen, &d, NULL, 0)) { json_free(&d); char *tmp = malloc(dlen + 1); if (tmp) { memcpy(tmp, data, dlen); tmp[dlen] = 0; jb_raw(dst, tmp); free(tmp); } else jb_raw(dst, "null"); }
+ else jb_raw(dst, "{\"error\":\"bad-json\"}");
+ }
+ jb_raw(dst, "}");
+}
+
+static void owner_signal(void) {
+ if (owner_wake < 0) return;
+ uint64_t one = 1;
+ if (write(owner_wake, &one, sizeof one) < 0) { /* already signalled */ }
+}
+
+/* Which owner sent request `id` (0 = the session); the route is consumed. Called with mu held. */
+static int route_take(int id) {
+ if (id <= 0) return 0;
+ for (int i = 0; i < MAX_ROUTE; i++) if (routes[i].id == id) { int o = routes[i].owner; routes[i].id = 0; return o; }
+ return 0;
+}
+
+/* Events that an owner with MAIL_EV_PIM (Calendar, Contacts, Reminders) may see: no mail
+ * metadata ("new" carries senders and subjects), only that the PIM data changed. */
+static int pim_event(const char *data, size_t dlen) {
+ JDoc d;
+ int ok = 0;
+ if (data && dlen && !json_parse(data, dlen, &d, NULL, 0)) {
+ const char *ev = json_str(d.root, "ev");
+ ok = ev && (!strcmp(ev, "pim-changed") || !strcmp(ev, "ready"));
+ json_free(&d);
}
- jb_raw(&events, "}");
- if (strcmp(type, "evt") && pending > 0) pending--;
+ return ok;
+}
+
+/* owner >= 0: a reply (done/err) for that owner; -1: a broadcast (evt, crash); -2: a reply for
+ * an app process that is gone (dropped). */
+static void ev_push_to(int owner, int id, const char *type, const char *data, size_t dlen) {
+ pthread_mutex_lock(&mu);
+ int sig = 0;
+ if (owner == -2) { /* dropped */ }
+ else if (owner > 0) {
+ if (owner <= MAIL_OWNERS && owners[owner].used) { ev_append(&owners[owner].ev, id, type, data, dlen); sig = 1; }
+ } else {
+ ev_append(&events, id, type, data, dlen);
+ if (owner < 0) {
+ int pim = !strcmp(type, "crash") || pim_event(data, dlen);
+ for (int o = 1; o <= MAIL_OWNERS; o++)
+ if (owners[o].used && (owners[o].mask == MAIL_EV_ALL || pim)) { ev_append(&owners[o].ev, id, type, data, dlen); sig = 1; }
+ }
+ }
+ if (strcmp(type, "evt") && strcmp(type, "crash") && pending > 0) pending--;
pthread_mutex_unlock(&mu);
+ if (sig) owner_signal();
+}
+
+static void ev_push(int id, const char *type, const char *data, size_t dlen) {
+ int bcast = !strcmp(type, "evt") || !strcmp(type, "crash");
+ int owner = -1;
+ if (!bcast) { pthread_mutex_lock(&mu); owner = route_take(id); pthread_mutex_unlock(&mu); }
+ ev_push_to(owner, id, type, data, dlen);
}
char *mail_poll(void) {
@@ -272,11 +334,59 @@ char *mail_poll(void) {
return r;
}
+int mail_owner_open(int mask) {
+ pthread_mutex_lock(&mu);
+ if (owner_wake < 0) owner_wake = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
+ int got = -1;
+ for (int o = 1; o <= MAIL_OWNERS && got < 0; o++) if (!owners[o].used) {
+ jb_init(&owners[o].ev);
+ owners[o].used = 1;
+ owners[o].mask = mask == MAIL_EV_ALL ? MAIL_EV_ALL : MAIL_EV_PIM;
+ got = o;
+ }
+ pthread_mutex_unlock(&mu);
+ return got;
+}
+
+void mail_owner_close(int owner) {
+ if (owner <= 0 || owner > MAIL_OWNERS) return;
+ pthread_mutex_lock(&mu);
+ if (owners[owner].used) { jb_free(&owners[owner].ev); owners[owner].used = 0; }
+ for (int i = 0; i < MAX_ROUTE; i++) if (routes[i].id && routes[i].owner == owner) routes[i].owner = -2; /* its replies are dropped */
+ pthread_mutex_unlock(&mu);
+ /* its decoded images go too */
+ pthread_mutex_lock(&img_mu);
+ for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].owner == owner) {
+ img_bytes -= (size_t)imgs[i].w * (size_t)imgs[i].h * 4;
+ free(imgs[i].px);
+ memset(&imgs[i], 0, sizeof imgs[i]);
+ }
+ pthread_mutex_unlock(&img_mu);
+}
+
+char *mail_poll_owner(int owner) {
+ if (owner <= 0 || owner > MAIL_OWNERS) return NULL;
+ pthread_mutex_lock(&mu);
+ char *r = NULL;
+ Owner *o = &owners[owner];
+ if (o->used && o->ev.n) {
+ size_t n = o->ev.n;
+ r = malloc(n + 3);
+ if (r) { r[0] = '['; memcpy(r + 1, o->ev.p, n); r[n + 1] = ']'; r[n + 2] = 0; }
+ o->ev.n = 0;
+ }
+ pthread_mutex_unlock(&mu);
+ return r;
+}
+
+int mail_owner_pollfd(void) { return owner_wake; }
+void mail_owner_clear_wake(void) { uint64_t v; if (owner_wake >= 0 && read(owner_wake, &v, sizeof v) < 0) { /* nothing pending */ } }
+
int mail_pending(void) { pthread_mutex_lock(&mu); int p = pending; pthread_mutex_unlock(&mu); return p; }
/* ---- images ---- */
-static int img_store(int w, int h, int fd) {
+static int img_store(int w, int h, int fd, int owner) {
size_t bytes = (size_t)w * (size_t)h * 4;
void *m = mmap(NULL, bytes, PROT_READ, MAP_SHARED, fd, 0);
if (m == MAP_FAILED) return -1;
@@ -302,7 +412,7 @@ static int img_store(int w, int h, int fd) {
img_bytes -= (size_t)imgs[slot].w * (size_t)imgs[slot].h * 4;
free(imgs[slot].px);
}
- imgs[slot] = (Img){ next_handle++, w, h, px, ++img_seq };
+ imgs[slot] = (Img){ .handle = next_handle++, .w = w, .h = h, .owner = owner, .px = px, .seq = ++img_seq };
img_bytes += bytes;
int handle = imgs[slot].handle;
pthread_mutex_unlock(&img_mu);
@@ -311,13 +421,15 @@ static int img_store(int w, int h, int fd) {
const uint32_t *mail_image_lock(int handle, int *w, int *h) {
pthread_mutex_lock(&img_mu);
- for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].handle == handle) { *w = imgs[i].w; *h = imgs[i].h; imgs[i].seq = ++img_seq; return imgs[i].px; }
+ for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].handle == handle && imgs[i].owner == 0) { *w = imgs[i].w; *h = imgs[i].h; imgs[i].seq = ++img_seq; return imgs[i].px; }
return NULL;
}
void mail_image_unlock(void) { pthread_mutex_unlock(&img_mu); }
-void mail_image_release(int handle) {
+void mail_image_release(int handle) { mail_image_release_as(0, handle); }
+
+void mail_image_release_as(int owner, int handle) {
pthread_mutex_lock(&img_mu);
- for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].handle == handle) {
+ for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].handle == handle && imgs[i].owner == owner) {
img_bytes -= (size_t)imgs[i].w * (size_t)imgs[i].h * 4;
free(imgs[i].px);
memset(&imgs[i], 0, sizeof imgs[i]);
@@ -325,6 +437,27 @@ void mail_image_release(int handle) {
pthread_mutex_unlock(&img_mu);
}
+/* A copy of an owner's decoded image in a sealed memfd (for the app process to map read-only). */
+int mail_image_fd(int owner, int handle, int *w, int *h) {
+ int fd = -1;
+ pthread_mutex_lock(&img_mu);
+ for (int i = 0; i < MAX_IMG; i++) if (imgs[i].px && imgs[i].handle == handle && imgs[i].owner == owner && owner > 0) {
+ size_t bytes = (size_t)imgs[i].w * (size_t)imgs[i].h * 4;
+ fd = memfd_create("lordos-mail-img", MFD_CLOEXEC | MFD_ALLOW_SEALING);
+ if (fd >= 0) {
+ size_t off = 0;
+ while (off < bytes) { ssize_t r = write(fd, (const char *)imgs[i].px + off, bytes - off); if (r <= 0) break; off += (size_t)r; }
+ if (off != bytes || fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL)) { close(fd); fd = -1; }
+ }
+ *w = imgs[i].w;
+ *h = imgs[i].h;
+ imgs[i].seq = ++img_seq;
+ break;
+ }
+ pthread_mutex_unlock(&img_mu);
+ return fd;
+}
+
/* ---- connector ---- */
static int v4_public(uint32_t a) { /* host byte order */
@@ -470,7 +603,10 @@ static void *loop(void *arg) {
running = 0;
pthread_mutex_unlock(&mu);
(void)np;
- ev_push(0, "crash", NULL, 0);
+ pthread_mutex_lock(&mu);
+ memset(routes, 0, sizeof routes); /* every pending request failed */
+ pthread_mutex_unlock(&mu);
+ ev_push_to(-1, 0, "crash", NULL, 0);
last_crash = now_ms();
break;
}
@@ -484,12 +620,15 @@ static void *loop(void *arg) {
int w = 0, h = 0;
if (m.json && !json_parse(m.json, m.len, &d, NULL, 0)) { w = (int)json_num(d.root, "w", 0); h = (int)json_num(d.root, "h", 0); json_free(&d); }
int handle = -1;
- if (m.nfds == 1 && w > 0 && h > 0 && w <= 8192 && h <= 8192 && doc_check_sealed(m.fds[0], (size_t)w * (size_t)h * 4) >= 0)
- handle = img_store(w, h, m.fds[0]);
+ pthread_mutex_lock(&mu);
+ int owner = route_take((int)m.h.id);
+ pthread_mutex_unlock(&mu);
+ if (owner >= 0 && m.nfds == 1 && w > 0 && h > 0 && w <= 8192 && h <= 8192 && doc_check_sealed(m.fds[0], (size_t)w * (size_t)h * 4) >= 0)
+ handle = img_store(w, h, m.fds[0], owner);
char j[96];
if (handle > 0) snprintf(j, sizeof j, "{\"image\":%d,\"w\":%d,\"h\":%d}", handle, w, h);
else snprintf(j, sizeof j, "{\"error\":\"image\"}");
- ev_push((int)m.h.id, handle > 0 ? "done" : "err", j, strlen(j));
+ ev_push_to(owner, (int)m.h.id, handle > 0 ? "done" : "err", j, strlen(j));
break;
}
default: break;
@@ -588,9 +727,17 @@ int mail_start(void) {
return 0;
}
-int mail_request(const char *json, size_t len, int *fds, int nfds) {
- if (mail_start()) { for (int i = 0; i < nfds; i++) close(fds[i]); return -1; }
+int mail_request(const char *json, size_t len, int *fds, int nfds) { return mail_request_as(0, json, len, fds, nfds); }
+
+int mail_request_as(int owner, const char *json, size_t len, int *fds, int nfds) {
+ if (owner < 0 || owner > MAIL_OWNERS || mail_start()) { for (int i = 0; i < nfds; i++) close(fds[i]); return -1; }
pthread_mutex_lock(&mu);
+ if (owner > 0) {
+ int slot = -1;
+ for (int i = 0; i < MAX_ROUTE && slot < 0; i++) if (!routes[i].id) slot = i;
+ if (!owners[owner].used || slot < 0) { pthread_mutex_unlock(&mu); for (int i = 0; i < nfds; i++) close(fds[i]); return -1; }
+ routes[slot] = (Route){ next_id, owner };
+ }
int id = next_id++;
if (next_id > 1 << 30) next_id = 1;
pending++;
@@ -599,10 +746,37 @@ int mail_request(const char *json, size_t len, int *fds, int nfds) {
int r = sock >= 0 ? doc_send(sock, MQ_REQ, (uint32_t)id, json, len, nfds ? fds : NULL, nfds) : -1;
pthread_mutex_unlock(&send_mu);
for (int i = 0; i < nfds; i++) close(fds[i]);
- if (r) { pthread_mutex_lock(&mu); pending--; pthread_mutex_unlock(&mu); return -1; }
+ if (r) { pthread_mutex_lock(&mu); pending--; route_take(id); pthread_mutex_unlock(&mu); return -1; }
return id;
}
+int mail_save_config(const char *j, size_t len) {
+ JDoc d;
+ int bad = len > MAIL_CONFIG_MAX || json_parse(j, len, &d, NULL, 0);
+ if (!bad) {
+ const JVal *acc = json_get(d.root, "accounts");
+ bad = d.root->type != J_OBJ || (acc && (acc->type != J_ARR || acc->len > MAIL_MAX_ACCOUNTS));
+ /* no secrets in this file */
+ for (const JVal *a = acc ? acc->kid : NULL; !bad && a; a = a->next) if (json_get(a, "password") || json_get(a, "secret")) bad = 1;
+ json_free(&d);
+ }
+ if (bad) return 1;
+ paths();
+ char dir[PATH_MAX], tmp[PATH_MAX + 16];
+ snprintf(dir, sizeof dir, "%s", cfg_path);
+ char *slash = strrchr(dir, '/');
+ if (slash) *slash = 0;
+ if (mkdirs(dir, 0700)) return 2;
+ snprintf(tmp, sizeof tmp, "%s.tmp", cfg_path);
+ int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);
+ int ok = fd >= 0 && write(fd, j, len) == (ssize_t)len && fsync(fd) == 0;
+ if (fd >= 0) close(fd);
+ ok = ok && rename(tmp, cfg_path) == 0;
+ if (!ok) { unlink(tmp); return 2; }
+ mail_reload_config();
+ return 0;
+}
+
void mail_reload_config(void) {
size_t clen;
char *cfg = read_config(&clen);
diff --git a/server/src/mail/mailc.h b/server/src/mail/mailc.h
index fe6e550..6490165 100644
--- a/server/src/mail/mailc.h
+++ b/server/src/mail/mailc.h
@@ -22,6 +22,9 @@ char *mail_poll(void); /* JSON array of events (malloc) or
int mail_pending(void);
/* Re-reads the accounts file, rebuilds the allowed endpoints and tells lord-maild. */
void mail_reload_config(void);
+/* Validates (JSON object, ≤ MAIL_CONFIG_MAX, no "password"/"secret" in an account) and writes the
+ * accounts file (0600, atomic), then reloads it. 0, 1 if refused, 2 if it could not be written. */
+int mail_save_config(const char *json, size_t len);
/* Remote images of one message: allow these http(s) hosts for a while. */
void mail_allow_hosts(const char *const *urls, int n, int seconds);
const char *mail_config_path(void); /* ~/.config/lordos/mail/accounts.json */
@@ -32,6 +35,23 @@ const uint32_t *mail_image_lock(int handle, int *w, int *h);
void mail_image_unlock(void);
void mail_image_release(int handle);
+/* ---- isolated system apps (Mail, Calendar, Contacts, Reminders in their own process) ----
+ * Each app process that uses lord-maild through the broker (sec/brokermail.c) is an "owner":
+ * replies to its requests and its decoded images belong to it alone, and broadcast events reach it
+ * according to its mask: MAIL_EV_ALL (Mail) or MAIL_EV_PIM (only pim-changed/ready; no senders or
+ * subjects for Calendar, Contacts and Reminders). Owner 0 is the session's JavaScript. */
+#define MAIL_OWNERS 8
+enum { MAIL_EV_ALL = 1, MAIL_EV_PIM = 2 };
+int mail_owner_open(int mask); /* → 1..MAIL_OWNERS, or -1 */
+void mail_owner_close(int owner); /* drops its queue, its images and its pending replies */
+int mail_request_as(int owner, const char *json, size_t len, int *fds, int nfds);
+char *mail_poll_owner(int owner); /* JSON array (malloc) or NULL */
+int mail_owner_pollfd(void); /* eventfd: some owner queue got data (-1 before the first owner) */
+void mail_owner_clear_wake(void);
+/* Sealed memfd with a copy of one of the owner's images (ARGB32, w*h*4 bytes), or -1. */
+int mail_image_fd(int owner, int handle, int *w, int *h);
+void mail_image_release_as(int owner, int handle);
+
/* Pure check used by the connector and its test: is host:port allowed by this config JSON? */
int mail_endpoint_allowed(const char *config_json, size_t len, const char *host, int port);
diff --git a/server/src/main.c b/server/src/main.c
index cb1502f..ecc22ef 100644
--- a/server/src/main.c
+++ b/server/src/main.c
@@ -39,6 +39,7 @@
#include "wl/wl_input.h"
#include "media/media.h"
#include "app/app.h"
+#include "app/apphost_bc.h"
#include "sec/broker.h"
#include "cursor.h"
#include "ui/grab.h"
@@ -1507,6 +1508,11 @@ int main(int argc, char **argv) {
snprintf(path, sizeof path, "%s", theme);
ok = js_init(path) == 0;
}
+ if (ok && !s.greeter) { /* the app host as bytecode for isolated apps (app/apphost_bc.c) */
+ char host[1200];
+ snprintf(host, sizeof host, "%s/app-host.bundle.js", js_sys_assets());
+ apphost_bc_start(host);
+ }
if (!ok) {
input_close(&s.input);
if (!s.headless) kms_close(K0(&s));
diff --git a/server/src/sec/broker.h b/server/src/sec/broker.h
index 1d1cec7..e84358d 100644
--- a/server/src/sec/broker.h
+++ b/server/src/sec/broker.h
@@ -42,6 +42,11 @@ enum BrokerOp {
BOP_KEYRING, /* payload "op\0service\0account\0label\0secret" (op: get | set | delete | list) → the
* app's own session-keyring items, owner = the verified app id (brokerkr.c,
* docs/PASSWORDS.md). Error replies carry an error code line (keyring.*) */
+ BOP_MAIL, /* (system Mail, Calendar, Contacts, Reminders only) lord-maild through lord-server:
+ * payload "verb\0rest", fds via SCM_RIGHTS for "req"/"reqm". Replies and events
+ * come back as "mail" events, in chunks. See brokermail.c, docs/PRIVACY.md */
+ BOP_SYS_OPEN, /* (those same system apps only) payload "app\0new\0json": open another of them
+ * with these args (Mail → Calendar for an invitation, Contacts → a new message) */
BOP_EVENT = 100, /* server → app, unrequested (reqid 0): payload "type\0json" */
};
@@ -73,6 +78,12 @@ int brokersrv_count(void);
/* The app on broker fd `fd` was spawned with a channel to lord-vault (system Passwords app): it may
* use BOP_VAULT_FIDO. */
void brokersrv_set_vault(int fd);
+/* The app on broker fd `fd` is a system package (assets/sysapps, verified by app_package_dir): it
+ * keeps the keyring owner and lord-maild access it had in-process. */
+void brokersrv_set_system(int fd);
+/* Args for an isolated app (wm.open(id, { args }) in the session): sent now if it is running, or
+ * kept and sent when it starts. `json` is a JSON object (≤ 16 KiB). 0 if sent or kept. */
+int brokersrv_open_args(const char *id, const char *json, size_t len, int new_window);
/* The app <id> is running: ask it for a new window. 0 if sent, -1 if it is not running. */
int brokersrv_new_window(const char *id);
/* Quit app <id> (❖Q, Dock → Quit): the app host closes all its windows, its close guards still
diff --git a/server/src/sec/broker_int.h b/server/src/sec/broker_int.h
index fddf480..d4c30b1 100644
--- a/server/src/sec/broker_int.h
+++ b/server/src/sec/broker_int.h
@@ -26,6 +26,20 @@ void brokerkr_conn_closed(int conn);
void brokerkr_tick(void);
int brokerkr_pollfd(void); /* lord-vault replies waiting, or -1 */
+/* Is broker connection `conn` a system package? */
+int brokersrv_conn_system(int conn);
+/* Event for the session's JS (privacy.js __lordBroker): kind, preformatted JSON (≤ 4 KiB). */
+void brokersrv_shell_event(const char *kind, const char *json);
+
+/* ---- brokermail.c: lord-maild for the isolated system Mail, Calendar, Contacts and Reminders ---- */
+/* fds: received with the request; the handler closes or keeps every one of them. */
+void brokermail_handle(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len, int *fds, int nfds);
+void brokermail_sys_open(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len);
+void brokermail_conn_closed(int conn);
+void brokermail_tick(void);
+int brokermail_pollfd(void); /* lord-maild replies waiting, or -1 */
+int brokermail_wants_write(int conn); /* output queued for that app */
+
/* ---- brokercam.c: the camera of isolated apps ---- */
void brokercam_handle(int conn, int fd, uint32_t reqid, const char *payload, uint32_t len);
int brokercam_pick_result(uint32_t reqid, const char *path); /* 1 if it was a camera save */
diff --git a/server/src/sec/brokerkr.c b/server/src/sec/brokerkr.c
index 55d3e8d..ab10a44 100644
--- a/server/src/sec/brokerkr.c
+++ b/server/src/sec/brokerkr.c
@@ -155,7 +155,9 @@ void brokerkr_handle(int conn, int fd, uint32_t reqid, const char *app, char *pa
return;
}
*r = (KrReq){ .st = ST_REQ, .conn = conn, .fd = fd, .reqid = reqid, .op = o };
- snprintf(r->owner, sizeof r->owner, "app.%s", app);
+ /* a system app (assets/sysapps) keeps the owner it had in the session (Mail's account passwords
+ * stay "mail", where the session's need-auth handler reads them); a user package is "app.<id>" */
+ snprintf(r->owner, sizeof r->owner, brokersrv_conn_system(conn) ? "%s" : "app.%s", app);
snprintf(r->service, sizeof r->service, "%s", service);
snprintf(r->account, sizeof r->account, "%s", account);
int sent = o == 's' ? send_vault(r, "kr-set", label, secret, NULL)
@@ -192,7 +194,7 @@ static void on_reply(KrReq *r, char *rep, size_t len) {
* app is shown by its plain id ("app.notes" → "notes"). */
char qa[64], qw[96], ev[256]; /* ids are short: [a-z0-9._-], at most 71 bytes */
json_quote(qw, sizeof qw, !strncmp(other, "app.", 4) ? other + 4 : other);
- json_quote(qa, sizeof qa, r->owner + 4);
+ json_quote(qa, sizeof qa, !strncmp(r->owner, "app.", 4) ? r->owner + 4 : r->owner);
snprintf(r->item, sizeof r->item, "%s", item);
r->prompt = KR_PROMPT_TAG | (++prompt_seq & 0x3fffffff);
r->st = ST_PROMPT;
diff --git a/server/src/sec/brokermail.c b/server/src/sec/brokermail.c
new file mode 100644
index 0000000..dc1e2cf
--- /dev/null
+++ b/server/src/sec/brokermail.c
@@ -0,0 +1,332 @@
+/* brokermail.c — lord-maild for the isolated system apps (BOP_MAIL, BOP_SYS_OPEN).
+ *
+ * Mail, Calendar, Contacts and Reminders run as their own sandboxed process
+ * (`lord-server --app <id>`, the system package in assets/sysapps). Their process has no network
+ * and cannot read the mail cache or the accounts file; it reaches lord-maild only through here, and
+ * lord-server keeps every rule it applied when these apps ran in-process (js_mail.c):
+ *
+ * - only a system package (brokersrv_conn_system) named mail, calendar, contacts or reminders;
+ * - each app may send only its own requests: Mail all of them, Calendar `cal-*`/`ev-*`/`todo-*`,
+ * Reminders `cal-*`/`todo-*`, Contacts `book-*`/`contact-*`/`autocomplete` (so a compromised
+ * Calendar cannot read mail);
+ * - files reach lord-maild only as fds the app already holds (from the system file dialog), and
+ * only regular files of at most 64 MB, only for the requests that take files;
+ * - replies, decoded images and events belong to that app's owner queue in mailc.c; Calendar,
+ * Contacts and Reminders get only the PIM events (no senders or subjects);
+ * - the accounts file (which servers lord-maild may reach) and remote-image grants: Mail only,
+ * with the same validation as lord.mail.saveConfig / allowImages;
+ * - attachments: Mail gets a read-only fd of one cached attachment (to save it through the
+ * system dialog) or asks the session to open it (the session opens it with the user's apps).
+ *
+ * Replies and events go back as "mail" events in chunks of at most CHUNK bytes ('C' = more follow,
+ * 'F' = last), queued per app and sent without ever blocking the compositor. */
+#include "broker_int.h"
+#include "json.h"
+#include "../mail/mailc.h"
+#include "../mail/proto.h"
+#include "../errcode.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#define MAX_CONN 32 /* brokersrv.c MAX_APPS */
+#define CHUNK (60 * 1024) /* below the default SEQPACKET send buffer */
+#define REQ_MAX (24u << 20) /* js_mail.c MAIL_REQ_MAX */
+#define FILE_MAX ((off_t)64 << 20)
+
+enum { ROLE_NONE = 0, ROLE_MAIL, ROLE_CALENDAR, ROLE_REMINDERS, ROLE_CONTACTS };
+
+typedef struct {
+ int owner; /* mailc owner, 0 = not opened yet */
+ int fd; /* broker socket (to send events) */
+ char *out; /* the batch being sent */
+ size_t len, off;
+} MailConn;
+static MailConn mc[MAX_CONN];
+
+static int role_of(int conn, const char *app) {
+ if (!brokersrv_conn_system(conn) || !app) return ROLE_NONE;
+ if (!strcmp(app, "mail")) return ROLE_MAIL;
+ if (!strcmp(app, "calendar")) return ROLE_CALENDAR;
+ if (!strcmp(app, "reminders")) return ROLE_REMINDERS;
+ if (!strcmp(app, "contacts")) return ROLE_CONTACTS;
+ return ROLE_NONE;
+}
+
+static int prefix(const char *s, const char *p) { return !strncmp(s, p, strlen(p)); }
+
+/* May `role` send request `op`? */
+static int op_allowed(int role, const char *op) {
+ if (!strcmp(op, "ping") || !strcmp(op, "status")) return 1;
+ switch (role) {
+ case ROLE_MAIL: return 1;
+ case ROLE_CALENDAR: return prefix(op, "cal-") || prefix(op, "ev-") || prefix(op, "todo-") || !strcmp(op, "alarms");
+ case ROLE_REMINDERS: return prefix(op, "cal-") || prefix(op, "todo-") || !strcmp(op, "alarms");
+ case ROLE_CONTACTS: return prefix(op, "book-") || prefix(op, "contact-") || !strcmp(op, "autocomplete");
+ default: return 0;
+ }
+}
+
+/* Requests that take files (attachments, a contact photo, an .ics/.vcf to import). */
+static int op_takes_files(const char *op) {
+ return !strcmp(op, "send") || !strcmp(op, "draft") || !strcmp(op, "contact-save") || !strcmp(op, "contact-import") || !strcmp(op, "ev-import");
+}
+
+static void reply(int fd, uint32_t reqid, int st, const char *s) { brokersrv_reply(fd, reqid, st, s, s ? (uint32_t)strlen(s) : 0, -1); }
+static void reply_code(int fd, uint32_t reqid, const char *code) { reply(fd, reqid, BST_ERROR, code); }
+
+static void close_fds(int *fds, int n) { for (int i = 0; i < n; i++) if (fds[i] >= 0) { close(fds[i]); fds[i] = -1; } }
+
+/* A file the app passes on: a readable regular file of at most 64 MB, read from the start. */
+static int file_ok(int fd) {
+ struct stat st;
+ int fl = fcntl(fd, F_GETFL);
+ if (fl < 0 || (fl & O_ACCMODE) == O_WRONLY || fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size > FILE_MAX) return 0;
+ lseek(fd, 0, SEEK_SET);
+ return 1;
+}
+
+static int ensure_owner(int conn, int fd, int role) {
+ if (conn < 0 || conn >= MAX_CONN) return -1;
+ if (mc[conn].owner > 0) return mc[conn].owner;
+ int o = mail_owner_open(role == ROLE_MAIL ? MAIL_EV_ALL : MAIL_EV_PIM);
+ if (o > 0) { mc[conn].owner = o; mc[conn].fd = fd; }
+ return o;
+}
+
+/* "verb\0rest": rest (may hold NULs) and its length */
+static const char *rest_of(const char *payload, uint32_t len, uint32_t *rl) {
+ const char *nul = memchr(payload, 0, len);
+ if (!nul) { *rl = 0; return payload + len; }
+ *rl = len - (uint32_t)(nul + 1 - payload);
+ return nul + 1;
+}
+
+/* JSON with a short "op" (as js_mail.c f_request); op copied out. 0 if valid. */
+static int check_request(const char *j, size_t len, char *op, size_t on) {
+ JDoc d;
+ if (!len || len > REQ_MAX || json_parse(j, len, &d, NULL, 0)) return -1;
+ const char *o = d.root && d.root->type == J_OBJ ? json_str(d.root, "op") : NULL;
+ int ok = o && o[0] && strlen(o) <= 32;
+ if (ok) snprintf(op, on, "%s", o);
+ json_free(&d);
+ return ok ? 0 : -1;
+}
+
+static char *read_all(int fd, size_t max, size_t *out) {
+ struct stat st;
+ if (fstat(fd, &st) || !S_ISREG(st.st_mode) || st.st_size <= 0 || (size_t)st.st_size > max) return NULL;
+ char *b = malloc((size_t)st.st_size + 1);
+ if (!b) return NULL;
+ size_t got = 0;
+ while (got < (size_t)st.st_size) {
+ ssize_t r = pread(fd, b + got, (size_t)st.st_size - got, (off_t)got);
+ if (r < 0 && errno == EINTR) continue;
+ if (r <= 0) break;
+ got += (size_t)r;
+ }
+ if (got != (size_t)st.st_size) { free(b); return NULL; }
+ b[got] = 0;
+ *out = got;
+ return b;
+}
+
+/* A cached attachment: "att/<acct>/<uid>-<idx>/<name>" inside the mail cache, no "..", no links
+ * out of it. Writes the real path. 0 if valid. */
+static int attachment_path(const char *rel, size_t rl, char *real, size_t n) {
+ if (rl < 5 || rl > 1024 || memchr(rel, 0, rl) || strncmp(rel, "att/", 4) || strstr(rel, "..") || strstr(rel, "//")) return -1;
+ char full[PATH_MAX * 2], base[PATH_MAX], cache[PATH_MAX];
+ if (!realpath(mail_cache_path(), cache)) return -1;
+ if ((size_t)snprintf(base, sizeof base, "%s/att/", cache) >= sizeof base) return -1;
+ if ((size_t)snprintf(full, sizeof full, "%s/%.*s", cache, (int)rl, rel) >= sizeof full) return -1;
+ char tmp[PATH_MAX];
+ if (!realpath(full, tmp) || strncmp(tmp, base, strlen(base))) return -1;
+ if ((size_t)snprintf(real, n, "%s", tmp) >= n) return -1;
+ return 0;
+}
+
+void brokermail_handle(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len, int *fds, int nfds) {
+ int role = role_of(conn, app);
+ if (role == ROLE_NONE) { close_fds(fds, nfds); reply(fd, reqid, BST_DENIED, NULL); return; }
+ uint32_t rl = 0;
+ const char *verb = payload, *rest = rest_of(payload, len, &rl);
+
+ if (!strcmp(verb, "req") || !strcmp(verb, "reqm")) {
+ int first = 0;
+ char *mem = NULL;
+ const char *j = rest;
+ size_t jl = rl;
+ if (!strcmp(verb, "reqm")) { /* a large request: its JSON in a memfd (the first fd) */
+ if (nfds < 1 || !(mem = read_all(fds[0], REQ_MAX, &jl))) { close_fds(fds, nfds); reply_code(fd, reqid, "mail.requestTooLarge"); return; }
+ close(fds[0]);
+ fds[0] = -1;
+ j = mem;
+ first = 1;
+ }
+ char op[40];
+ if (check_request(j, jl, op, sizeof op)) { free(mem); close_fds(fds, nfds); reply_code(fd, reqid, "sys.badArgument"); return; }
+ if (!op_allowed(role, op)) {
+ fprintf(stderr, "broker[%s]: mail request '%s' refused (not this app's)\n", app, op);
+ free(mem); close_fds(fds, nfds); reply(fd, reqid, BST_DENIED, NULL); return;
+ }
+ int files[15], nf = 0;
+ for (int i = first; i < nfds; i++) {
+ if (fds[i] < 0) continue;
+ if (nf >= 15 || !op_takes_files(op) || !file_ok(fds[i])) {
+ free(mem); close_fds(fds, nfds);
+ for (int k = 0; k < nf; k++) close(files[k]);
+ reply_code(fd, reqid, "fs.outsideHome");
+ return;
+ }
+ files[nf++] = fds[i];
+ fds[i] = -1;
+ }
+ int owner = ensure_owner(conn, fd, role);
+ int id = owner > 0 ? mail_request_as(owner, j, jl, files, nf) : -1; /* takes the files */
+ if (owner <= 0) for (int k = 0; k < nf; k++) close(files[k]);
+ free(mem);
+ char s[16];
+ snprintf(s, sizeof s, "%d", id);
+ reply(fd, reqid, id > 0 ? BST_OK : BST_ERROR, s);
+ return;
+ }
+ /* the other verbs take no files */
+ close_fds(fds, nfds);
+ if (!strcmp(verb, "available")) { reply(fd, reqid, BST_OK, mail_available() == 0 ? "1" : "0"); return; }
+ if (!strcmp(verb, "start")) { ensure_owner(conn, fd, role); reply(fd, reqid, BST_OK, mail_start() == 0 ? "1" : "0"); return; }
+ if (!strcmp(verb, "img")) {
+ int w = 0, h = 0, f = mc[conn].owner > 0 ? mail_image_fd(mc[conn].owner, atoi(rest), &w, &h) : -1;
+ if (f < 0) { reply(fd, reqid, BST_ERROR, NULL); return; }
+ char s[32];
+ snprintf(s, sizeof s, "%d %d", w, h);
+ brokersrv_reply(fd, reqid, BST_OK, s, (uint32_t)strlen(s), f);
+ close(f);
+ return;
+ }
+ if (!strcmp(verb, "release")) { if (mc[conn].owner > 0) mail_image_release_as(mc[conn].owner, atoi(rest)); reply(fd, reqid, BST_OK, NULL); return; }
+ /* ---- Mail only from here ---- */
+ if (role != ROLE_MAIL) { reply(fd, reqid, BST_DENIED, NULL); return; }
+ if (!strcmp(verb, "config")) {
+ size_t n = 0;
+ int f = open(mail_config_path(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ char *b = f >= 0 ? read_all(f, MAIL_CONFIG_MAX, &n) : NULL;
+ if (f >= 0) close(f);
+ brokersrv_reply(fd, reqid, BST_OK, b ? b : "", b ? (uint32_t)n : 0, -1);
+ free(b);
+ return;
+ }
+ if (!strcmp(verb, "save")) {
+ int r = rl ? mail_save_config(rest, rl) : 1;
+ if (!r) { reply(fd, reqid, BST_OK, NULL); return; }
+ char line[PATH_MAX + 64];
+ if (r == 1) lerr_set(line, sizeof line, "mail.badAccounts", NULL);
+ else lerr_set(line, sizeof line, "sys.writeFailed", "path", mail_config_path(), NULL);
+ reply_code(fd, reqid, line);
+ return;
+ }
+ if (!strcmp(verb, "images")) { /* "url\0url\0…": the remote images of one message */
+ const char *urls[200];
+ int n = 0;
+ const char *end = rest + rl;
+ for (const char *p = rest; p < end && n < 200;) {
+ size_t l = strnlen(p, (size_t)(end - p));
+ if (p + l == end) break; /* each one NUL-terminated */
+ if (l && l < 2048) urls[n++] = p;
+ p += l + 1;
+ }
+ mail_allow_hosts(urls, n, 600);
+ reply(fd, reqid, BST_OK, NULL);
+ return;
+ }
+ if (!strcmp(verb, "att") || !strcmp(verb, "open")) {
+ /* "att": rest = relative path → read-only fd. "open": rest = "path\0name" → the session opens it */
+ size_t pl = strnlen(rest, rl);
+ char real[PATH_MAX];
+ if (attachment_path(rest, pl, real, sizeof real)) { reply(fd, reqid, BST_DENIED, NULL); return; }
+ if (!strcmp(verb, "att")) {
+ int f = open(real, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+ struct stat st;
+ if (f < 0 || fstat(f, &st) || !S_ISREG(st.st_mode)) { if (f >= 0) close(f); reply(fd, reqid, BST_ERROR, NULL); return; }
+ brokersrv_reply(fd, reqid, BST_OK, NULL, 0, f);
+ close(f);
+ return;
+ }
+ const char *name = pl < rl ? rest + pl + 1 : "";
+ char qp[PATH_MAX * 2 + 2], qn[600], ev[PATH_MAX * 2 + 700];
+ char nm[256];
+ snprintf(nm, sizeof nm, "%.*s", (int)strnlen(name, rl - (pl < rl ? pl + 1 : rl)), name);
+ json_quote(qp, sizeof qp, real);
+ json_quote(qn, sizeof qn, nm);
+ snprintf(ev, sizeof ev, "{\"app\":\"mail\",\"path\":%s,\"name\":%s}", qp, qn);
+ brokersrv_shell_event("mailopen", ev);
+ reply(fd, reqid, BST_OK, NULL);
+ return;
+ }
+ reply(fd, reqid, BST_ERROR, NULL);
+}
+
+/* "app\0new\0json": Mail, Calendar, Contacts and Reminders may open one another with args. */
+void brokermail_sys_open(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len) {
+ if (role_of(conn, app) == ROLE_NONE) { reply(fd, reqid, BST_DENIED, NULL); return; }
+ const char *target = payload;
+ uint32_t rl = 0;
+ const char *nw = rest_of(payload, len, &rl);
+ uint32_t jl = 0;
+ const char *json = rest_of(nw, rl, &jl);
+ int ok = (!strcmp(target, "mail") || !strcmp(target, "calendar") || !strcmp(target, "contacts") || !strcmp(target, "reminders"));
+ JDoc d;
+ /* args only: a small JSON object, never a path (these apps never open files by path) */
+ ok = ok && jl > 0 && jl <= 1500 && !memchr(json, 0, jl) && !json_parse(json, jl, &d, NULL, 0);
+ if (ok) { ok = d.root && d.root->type == J_OBJ && !json_get(d.root, "path") && !json_get(d.root, "paths"); json_free(&d); }
+ if (!ok) { reply(fd, reqid, BST_DENIED, NULL); return; }
+ char ev[1700];
+ snprintf(ev, sizeof ev, "{\"app\":\"%s\",\"new\":%s,\"args\":%.*s}", target, nw[0] == '1' ? "true" : "false", (int)jl, json);
+ brokersrv_shell_event("launch", ev);
+ reply(fd, reqid, BST_OK, NULL);
+}
+
+void brokermail_conn_closed(int conn) {
+ if (conn < 0 || conn >= MAX_CONN) return;
+ if (mc[conn].owner > 0) mail_owner_close(mc[conn].owner);
+ free(mc[conn].out);
+ memset(&mc[conn], 0, sizeof mc[conn]);
+}
+
+int brokermail_pollfd(void) { return mail_owner_pollfd(); }
+int brokermail_wants_write(int conn) { return conn >= 0 && conn < MAX_CONN && mc[conn].out != NULL; }
+
+/* Sends what it can of every app's queue; never blocks. */
+void brokermail_tick(void) {
+ mail_owner_clear_wake();
+ for (int i = 0; i < MAX_CONN; i++) {
+ MailConn *m = &mc[i];
+ if (m->owner <= 0 || !brokersrv_conn_app(i)) continue;
+ for (;;) {
+ if (!m->out) {
+ m->out = mail_poll_owner(m->owner);
+ if (!m->out) break;
+ m->len = strlen(m->out);
+ m->off = 0;
+ }
+ size_t n = m->len - m->off;
+ int last = n <= CHUNK;
+ if (!last) n = CHUNK;
+ char *buf = malloc(n + 1);
+ if (!buf) break;
+ buf[0] = last ? 'F' : 'C';
+ memcpy(buf + 1, m->out + m->off, n);
+ int r = brokersrv_conn_event(i, "mail", buf, n + 1);
+ free(buf);
+ if (r) break; /* the socket is full: the rest goes on a later tick */
+ m->off += n;
+ if (last) { free(m->out); m->out = NULL; }
+ }
+ }
+}
diff --git a/server/src/sec/brokersrv.c b/server/src/sec/brokersrv.c
index 4c8a404..f92e055 100644
--- a/server/src/sec/brokersrv.c
+++ b/server/src/sec/brokersrv.c
@@ -32,7 +32,7 @@
#define MAX_APPS 32
#define MAX_PENDING 32
-typedef struct { int fd, pid, used, resync; char id[48]; MAudio *mic; int mic_ringfd; int vault; } AppConn;
+typedef struct { int fd, pid, used, resync; char id[48]; MAudio *mic; int mic_ringfd; int vault, sys; } AppConn;
static AppConn apps[MAX_APPS];
/* prompts waiting for the user's answer (ui id → app + fd + permission + the app's reqid) */
@@ -47,7 +47,7 @@ static uint32_t ui_seq;
static uint32_t next_ui_id(void) { ui_seq = (ui_seq % 0x3fffffffu) + 1; return ui_seq; }
/* cola de eventos para JS (prompts a mostrar, cambios de indicador) */
-typedef struct { char kind[16]; char json[256]; } Evt;
+typedef struct { char kind[16]; char json[4096]; } Evt;
static Evt evq[64];
static int nevt;
@@ -105,6 +105,7 @@ int brokersrv_publish(const char *kind, const char *json, size_t len) {
static int send_reply_fd(int fd, uint32_t reqid, int status, const void *data, uint32_t len, int passfd);
static void clip_secret_tick(void);
+static double mono_s(void);
static int send_reply(int fd, uint32_t reqid, int status, const void *data, uint32_t len);
/* picker (powerbox): avisos pendientes de que el usuario elija un archivo */
@@ -157,6 +158,7 @@ void brokersrv_revoke(const char *app, const char *perm) {
void brokersrv_tick(void) {
brokercam_tick();
brokerkr_tick();
+ brokermail_tick();
clip_secret_tick();
char kb[512];
keyboard_json(kb, sizeof kb);
@@ -174,15 +176,59 @@ void brokersrv_tick(void) {
}
}
+/* Args waiting for an isolated app that is starting (brokersrv_open_args). */
+#define OPEN_ARGS_MAX (16 * 1024)
+static struct { char id[48]; char *json; double at; } open_wait[8];
+
+static void send_open(AppConn *a, const char *json, size_t len, int new_window) {
+ char *ev = malloc(len + 40);
+ if (!ev) return;
+ int n = snprintf(ev, len + 40, "{\"new\":%s,\"args\":%.*s}", new_window ? "true" : "false", (int)len, json);
+ if (n > 0) send_event(a, "open", ev, (size_t)n);
+ free(ev);
+}
+
+int brokersrv_open_args(const char *id, const char *json, size_t len, int new_window) {
+ if (!id || !lpk_valid_id(id) || !json || !len || len > OPEN_ARGS_MAX) return -1;
+ JDoc d;
+ if (json_parse(json, len, &d, NULL, 0)) return -1;
+ int obj = d.root && d.root->type == J_OBJ;
+ json_free(&d);
+ if (!obj) return -1;
+ for (int i = 0; i < MAX_APPS; i++) if (apps[i].used && !strcmp(apps[i].id, id)) { send_open(&apps[i], json, len, new_window); return 0; }
+ /* not running yet (it is being launched): keep it for a few seconds */
+ int slot = 0;
+ for (int i = 0; i < 8; i++) if (!open_wait[i].json || !strcmp(open_wait[i].id, id)) { slot = i; break; }
+ free(open_wait[slot].json);
+ open_wait[slot].json = malloc(len + 2);
+ if (!open_wait[slot].json) return -1;
+ open_wait[slot].json[0] = new_window ? '1' : '0';
+ memcpy(open_wait[slot].json + 1, json, len);
+ open_wait[slot].json[len + 1] = 0;
+ snprintf(open_wait[slot].id, sizeof open_wait[slot].id, "%s", id);
+ open_wait[slot].at = mono_s();
+ return 0;
+}
+
int brokersrv_add(int fd, const char *id, int pid) {
for (int i = 0; i < MAX_APPS; i++) if (!apps[i].used) {
apps[i] = (AppConn){ .fd = fd, .pid = pid, .used = 1 };
snprintf(apps[i].id, sizeof apps[i].id, "%s", id);
+ for (int k = 0; k < 8; k++) if (open_wait[k].json && !strcmp(open_wait[k].id, id)) {
+ if (mono_s() - open_wait[k].at < 10)
+ send_open(&apps[i], open_wait[k].json + 1, strlen(open_wait[k].json + 1), open_wait[k].json[0] == '1');
+ free(open_wait[k].json);
+ open_wait[k].json = NULL;
+ }
return 0;
}
return -1;
}
+void brokersrv_set_system(int fd) { for (int i = 0; i < MAX_APPS; i++) if (apps[i].used && apps[i].fd == fd) apps[i].sys = 1; }
+int brokersrv_conn_system(int conn) { return conn >= 0 && conn < MAX_APPS && apps[conn].used && apps[conn].sys; }
+void brokersrv_shell_event(const char *kind, const char *json) { queue_evt(kind, "%s", json); }
+
/* The app is already running: ask its process for another window (Dock → «New window»). */
int brokersrv_new_window(const char *id) {
static const char json[] = "{\"new\":true}";
@@ -228,6 +274,7 @@ int brokersrv_count(void) { int n = 0; for (int i = 0; i < MAX_APPS; i++) n += a
static void drop(AppConn *a) {
brokercam_conn_closed((int)(a - apps));
brokerkr_conn_closed((int)(a - apps));
+ brokermail_conn_closed((int)(a - apps));
/* its open prompts and pickers die with it: their fd may be reused by another app */
for (int i = 0; i < MAX_PENDING; i++) {
if (pend[i].used && pend[i].fd == a->fd) pend[i].used = 0;
@@ -288,9 +335,14 @@ static int deny_restricted(int fd, uint32_t reqid, const char *id, uint32_t flag
return 1;
}
-static void handle(AppConn *a, BrokerHdr *h, char *payload) {
+static void handle(AppConn *a, BrokerHdr *h, char *payload, int *fds, int nfds) {
int fd = a->fd;
+ if (h->op == BOP_MAIL) { brokermail_handle((int)(a - apps), fd, h->reqid, a->id, payload, h->len, fds, nfds); return; }
+ for (int i = 0; i < nfds; i++) if (fds[i] >= 0) { close(fds[i]); fds[i] = -1; } /* no other request carries fds */
switch (h->op) {
+ case BOP_SYS_OPEN:
+ brokermail_sys_open((int)(a - apps), fd, h->reqid, a->id, payload, h->len);
+ break;
case BOP_FS_HOME: {
char p[PATH_MAX];
snprintf(p, sizeof p, "%s/.local/share/lordos/appdata/%s", getenv("HOME"), a->id);
@@ -509,7 +561,14 @@ void brokersrv_resolve(uint32_t ui, int allow) {
int brokersrv_pollfds(struct pollfd *pfd, int max) {
int n = 0;
- for (int i = 0; i < MAX_APPS && n < max; i++) if (apps[i].used) { pfd[n].fd = apps[i].fd; pfd[n].events = POLLIN; pfd[n].revents = 0; n++; }
+ for (int i = 0; i < MAX_APPS && n < max; i++) if (apps[i].used) {
+ pfd[n].fd = apps[i].fd;
+ pfd[n].events = POLLIN | (brokermail_wants_write(i) ? POLLOUT : 0); /* mail replies still to send */
+ pfd[n].revents = 0;
+ n++;
+ }
+ int mf = brokermail_pollfd(); /* lord-maild answered an isolated app */
+ if (mf >= 0 && n < max) { pfd[n].fd = mf; pfd[n].events = POLLIN; pfd[n].revents = 0; n++; }
/* last: wakes the loop when lord-vault answers a keyring request (brokersrv_tick reads it) */
int kf = brokerkr_pollfd();
if (kf >= 0 && n < max) { pfd[n].fd = kf; pfd[n].events = POLLIN; pfd[n].revents = 0; n++; }
@@ -526,13 +585,26 @@ void brokersrv_dispatch(struct pollfd *pfd, int n) {
char *buf = malloc(BROKER_MAX_MSG + 1);
if (!buf) continue;
struct iovec iov[2] = { { &h, sizeof h }, { buf, BROKER_MAX_MSG } };
- struct msghdr m = { .msg_iov = iov, .msg_iovlen = 2 };
- ssize_t r = recvmsg(apps[i].fd, &m, 0);
- if (r < (ssize_t)sizeof h) { free(buf); drop(&apps[i]); continue; }
+ /* up to 16 fds (files for lord-maild, BOP_MAIL only; closed for anything else) */
+ char cbuf[CMSG_SPACE(16 * sizeof(int))];
+ struct msghdr m = { .msg_iov = iov, .msg_iovlen = 2, .msg_control = cbuf, .msg_controllen = sizeof cbuf };
+ ssize_t r = recvmsg(apps[i].fd, &m, MSG_CMSG_CLOEXEC);
+ int fds[16], nfds = 0;
+ for (struct cmsghdr *c = CMSG_FIRSTHDR(&m); c; c = CMSG_NXTHDR(&m, c))
+ if (c->cmsg_level == SOL_SOCKET && c->cmsg_type == SCM_RIGHTS) {
+ int k = (int)((c->cmsg_len - CMSG_LEN(0)) / sizeof(int));
+ for (int j = 0; j < k; j++) {
+ int f;
+ memcpy(&f, CMSG_DATA(c) + j * sizeof(int), sizeof f);
+ if (nfds < 16) fds[nfds++] = f; else close(f);
+ }
+ }
+ if (r < (ssize_t)sizeof h || (m.msg_flags & MSG_CTRUNC)) { for (int j = 0; j < nfds; j++) close(fds[j]); free(buf); drop(&apps[i]); continue; }
uint32_t len = (uint32_t)r - sizeof h;
- if (h.len != len || len > BROKER_MAX_MSG) { free(buf); drop(&apps[i]); continue; }
+ if (h.len != len || len > BROKER_MAX_MSG) { for (int j = 0; j < nfds; j++) close(fds[j]); free(buf); drop(&apps[i]); continue; }
buf[len] = 0;
- handle(&apps[i], &h, buf);
+ handle(&apps[i], &h, buf, fds, nfds);
+ for (int j = 0; j < nfds; j++) if (fds[j] >= 0) close(fds[j]);
free(buf);
}
}
diff --git a/server/src/ui/js.c b/server/src/ui/js.c
index dc71889..b829c8a 100644
--- a/server/src/ui/js.c
+++ b/server/src/ui/js.c
@@ -1,5 +1,7 @@
/* js.c — embedded QuickJS. Exposes the global `lord` object (create/modify nodes) and
* provides setTimeout, requestAnimationFrame, console and performance, which React needs. */
+#include "../app/apphost_bc.h"
+#include <unistd.h>
#include "js.h"
#include "../ime.h"
#include "../wl/wl.h"
@@ -473,8 +475,18 @@ int js_init_app(const char *host_bundle, const char *app_id) {
double t0 = now_ms();
int r = eval(prelude, sizeof prelude - 1, "<prelude>");
- if (!r) r = eval(src, (size_t)len, host_bundle);
- fprintf(stderr, "js: app %s loaded in %.1f ms\n", app_id, now_ms() - t0);
+ /* the app host as bytecode lord-server compiled for this session (app/apphost_bc.c), else the source */
+ const char *bcs = getenv(APPHOST_BC_ENV);
+ int bcfd = bcs ? atoi(bcs) : -1, bcok = 0, how = -1;
+ unsetenv(APPHOST_BC_ENV);
+ if (!r && bcfd > 2) {
+ how = apphost_bc_eval(ctx, host_bundle, bcfd, &bcok);
+ if (how == 1) { dump_exception(ctx); r = -1; }
+ drain_jobs();
+ }
+ if (bcfd > 2) close(bcfd);
+ if (!r && how < 0) r = eval(src, (size_t)len, host_bundle);
+ fprintf(stderr, "js: app %s loaded in %.1f ms%s\n", app_id, now_ms() - t0, how == 0 ? " (bytecode)" : "");
free(src);
return r;
}
diff --git a/server/src/ui/js_broker.c b/server/src/ui/js_broker.c
index 484ee0f..209e4bc 100644
--- a/server/src/ui/js_broker.c
+++ b/server/src/ui/js_broker.c
@@ -22,6 +22,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
+#include <sys/stat.h>
#include <math.h>
#include <stdatomic.h>
#include <unistd.h>
@@ -39,6 +40,8 @@ static char *pkg_read(const char *rel, size_t max, size_t *len);
static struct { char *buf; size_t len; } queued[32];
static int nqueued;
static void queue_event(const char *p, size_t n) {
+ /* lord-maild replies (js_brokermail.c) are taken at once: never dropped while an RPC waits */
+ if (n > 5 && !memcmp(p, "mail", 5)) { js_brokermail_chunk(p + 5, n - 5); return; }
if (nqueued >= 32) return;
char *b = malloc(n + 1);
if (!b) return;
@@ -57,11 +60,22 @@ int js_broker_fd(void) { return broker_fd; }
/* RPC síncrono: manda el pedido y espera la respuesta. status recibe BrokerStatus; out/outlen el
* payload (malloc; el llamador libera). 0 si llegó respuesta. */
-static int rpc(int op, const void *payload, uint32_t len, int *status, char **out, uint32_t *outlen) {
- if (broker_fd < 0) { if (status) *status = BST_ERROR; return -1; }
+static int rpc_fds(int op, const void *payload, uint32_t len, const int *fds, int nfds, int *status, char **out, uint32_t *outlen) {
+ if (broker_fd < 0 || nfds < 0 || nfds > 16) { if (status) *status = BST_ERROR; return -1; }
BrokerHdr h = { .reqid = next_req++, .op = (uint16_t)op, .status = BROKER_REQ, .len = len };
struct iovec iov[2] = { { &h, sizeof h }, { (void *)payload, len } };
struct msghdr m = { .msg_iov = iov, .msg_iovlen = len ? 2 : 1 };
+ char cbuf[CMSG_SPACE(16 * sizeof(int))];
+ if (nfds) { /* files for lord-maild (BOP_MAIL) */
+ memset(cbuf, 0, sizeof cbuf);
+ m.msg_control = cbuf;
+ m.msg_controllen = CMSG_SPACE((size_t)nfds * sizeof(int));
+ struct cmsghdr *c = CMSG_FIRSTHDR(&m);
+ c->cmsg_level = SOL_SOCKET;
+ c->cmsg_type = SCM_RIGHTS;
+ c->cmsg_len = CMSG_LEN((size_t)nfds * sizeof(int));
+ memcpy(CMSG_DATA(c), fds, (size_t)nfds * sizeof(int));
+ }
if (sendmsg(broker_fd, &m, MSG_NOSIGNAL) < 0) { if (status) *status = BST_ERROR; return -1; }
for (;;) {
BrokerHdr r;
@@ -83,6 +97,9 @@ static int rpc(int op, const void *payload, uint32_t len, int *status, char **ou
return 0;
}
}
+static int rpc(int op, const void *payload, uint32_t len, int *status, char **out, uint32_t *outlen) {
+ return rpc_fds(op, payload, len, NULL, 0, status, out, outlen);
+}
/* Un evento: "tipo\0json". El teclado se aplica acá (keyboard.c); el resto va a JS
* (__lordBrokerEvent: tokens del tema, idioma, estado completo). */
@@ -106,6 +123,7 @@ static void dispatch_event(const char *buf, size_t n) {
const char *kind = buf, *json = nul + 1;
size_t jl = n - (size_t)(json - buf);
if (!strcmp(kind, "cam")) { js_brokercam_event(json, jl); return; } /* camera frames (js_brokercam.c) */
+ if (!strcmp(kind, "mail")) { js_brokermail_chunk(json, jl); return; } /* lord-maild replies (js_brokermail.c) */
if (!strcmp(kind, "keyboard")) { apply_keyboard(json, jl); return; }
if (!strcmp(kind, "state")) { /* resincronizar: teclado acá, el resto a JS */
JDoc d;
@@ -292,15 +310,22 @@ static int rpc_fd(int op, const void *payload, uint32_t len, char *name, size_t
struct iovec iov[2] = { { &h, sizeof h }, { (void *)payload, len } };
struct msghdr m = { .msg_iov = iov, .msg_iovlen = len ? 2 : 1 };
if (sendmsg(broker_fd, &m, MSG_NOSIGNAL) < 0) return -1;
+ /* events that arrive meanwhile can be large (mail chunks): a full-size buffer */
+ static char *buf;
+ if (!buf && !(buf = malloc(BROKER_MAX_MSG + 1))) return -1;
for (;;) {
BrokerHdr r;
- char buf[1024];
char cmsg[CMSG_SPACE(sizeof(int))];
- struct iovec riov[2] = { { &r, sizeof r }, { buf, sizeof buf - 1 } };
+ struct iovec riov[2] = { { &r, sizeof r }, { buf, BROKER_MAX_MSG } };
struct msghdr rm = { .msg_iov = riov, .msg_iovlen = 2, .msg_control = cmsg, .msg_controllen = sizeof cmsg };
- ssize_t n = recvmsg(broker_fd, &rm, 0);
+ ssize_t n = recvmsg(broker_fd, &rm, MSG_CMSG_CLOEXEC);
if (n < (ssize_t)sizeof r) return -1;
- if (r.reqid != h.reqid) { if (r.op == BOP_EVENT) queue_event(buf, (uint32_t)n - sizeof r); continue; }
+ if (r.reqid != h.reqid) {
+ for (struct cmsghdr *cm = CMSG_FIRSTHDR(&rm); cm; cm = CMSG_NXTHDR(&rm, cm)) /* never keep an fd nobody asked for */
+ if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS) { int f; memcpy(&f, CMSG_DATA(cm), sizeof f); close(f); }
+ if (r.op == BOP_EVENT) queue_event(buf, (uint32_t)n - sizeof r);
+ continue;
+ }
int fd = -1;
for (struct cmsghdr *cm = CMSG_FIRSTHDR(&rm); cm; cm = CMSG_NXTHDR(&rm, cm))
if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS) memcpy(&fd, CMSG_DATA(cm), sizeof fd);
@@ -318,6 +343,9 @@ static int rpc_fd(int op, const void *payload, uint32_t len, char *name, size_t
/* For js_brokercam.c (js_broker.h): the same RPCs, plus a send that does not wait for a reply. */
int js_broker_rpc(int op, const void *payload, uint32_t len, int *status, char **out, uint32_t *outlen) { return rpc(op, payload, len, status, out, outlen); }
+int js_broker_rpc_fds(int op, const void *payload, uint32_t len, const int *fds, int nfds, int *status, char **out, uint32_t *outlen) {
+ return rpc_fds(op, payload, len, fds, nfds, status, out, outlen);
+}
int js_broker_rpc_fd(int op, const void *payload, uint32_t len, char *info, size_t n) { return rpc_fd(op, payload, len, info, n); }
int js_broker_send(int op, const void *payload, uint32_t len) {
if (broker_fd < 0) return -1;
@@ -376,6 +404,15 @@ static JSValue f_fd_write(JSContext *c, JSValueConst t, int argc, JSValueConst *
if (dyn) JS_FreeCString(c, dyn);
return JS_NewBool(c, data && w == len);
}
+/* lord.broker.fdSize(fd) → bytes of a file the app holds (from the system file dialog), or -1 */
+static JSValue f_fd_size(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int32_t fd = -1;
+ if (argc > 0) JS_ToInt32(c, &fd, argv[0]);
+ struct stat st;
+ if (fd < 0 || fstat(fd, &st) || !S_ISREG(st.st_mode)) return JS_NewInt32(c, -1);
+ return JS_NewFloat64(c, (double)st.st_size);
+}
static JSValue f_fd_close(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
(void)t; (void)argc;
int32_t fd = -1;
@@ -444,6 +481,30 @@ static JSValue f_mic_level(JSContext *c, JSValueConst t, int argc, JSValueConst
return JS_NewFloat64(c, rms);
}
+/* lord.broker.openApp(app, json, newWindow) → true: a system app opens another one with args
+ * (Mail → Calendar, Contacts → a new message). lord-server allows it only between Mail, Calendar,
+ * Contacts and Reminders, and only small args without paths (sec/brokermail.c). */
+static JSValue f_broker_open_app(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *app = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(c, argv[0]) : NULL;
+ size_t jl = 0;
+ const char *json = argc > 1 && JS_IsString(argv[1]) ? JS_ToCStringLen(c, &jl, argv[1]) : NULL;
+ int ok = 0;
+ if (app && json && strlen(app) < 48 && jl <= 1500) {
+ char pl[1600];
+ int n = snprintf(pl, sizeof pl, "%s", app) + 1;
+ pl[n++] = argc > 2 && JS_ToBool(c, argv[2]) ? '1' : '0';
+ pl[n++] = 0;
+ memcpy(pl + n, json, jl);
+ n += (int)jl;
+ int st = BST_ERROR;
+ ok = !rpc(BOP_SYS_OPEN, pl, (uint32_t)n, &st, NULL, NULL) && st == BST_OK;
+ }
+ if (app) JS_FreeCString(c, app);
+ if (json) JS_FreeCString(c, json);
+ return JS_NewBool(c, ok);
+}
+
static JSValue f_broker_menus(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
(void)t; (void)argc;
size_t len = 0;
@@ -638,8 +699,8 @@ static const JSCFunctionListEntry fs_funcs[] = {
static const JSCFunctionListEntry clip_funcs[] = { JS_CFUNC_DEF("get", 0, f_clip_get), JS_CFUNC_DEF("set", 1, f_clip_set) };
static const JSCFunctionListEntry broker_funcs[] = {
JS_CFUNC_DEF("request", 1, f_broker_request), JS_CFUNC_DEF("device", 2, f_broker_device), JS_CFUNC_DEF("state", 0, f_broker_state),
- JS_CFUNC_DEF("pick", 2, f_broker_pick), JS_CFUNC_DEF("fdRead", 1, f_fd_read), JS_CFUNC_DEF("fdWrite", 2, f_fd_write), JS_CFUNC_DEF("fdClose", 1, f_fd_close),
- JS_CFUNC_DEF("menus", 1, f_broker_menus),
+ JS_CFUNC_DEF("pick", 2, f_broker_pick), JS_CFUNC_DEF("fdRead", 1, f_fd_read), JS_CFUNC_DEF("fdWrite", 2, f_fd_write), JS_CFUNC_DEF("fdClose", 1, f_fd_close), JS_CFUNC_DEF("fdSize", 1, f_fd_size),
+ JS_CFUNC_DEF("menus", 1, f_broker_menus), JS_CFUNC_DEF("openApp", 3, f_broker_open_app),
JS_CFUNC_DEF("micStart", 0, f_mic_start), JS_CFUNC_DEF("micStop", 0, f_mic_stop), JS_CFUNC_DEF("micLevel", 0, f_mic_level),
};
static const JSCFunctionListEntry locale_funcs[] = {
@@ -669,4 +730,5 @@ void js_broker_register(JSContext *c, JSValue lord, const char *id) {
JS_SetPropertyStr(c, lord, "loadApp", JS_NewCFunction(c, f_load_app, "loadApp", 0));
app_windows_register(c, lord); /* several windows per isolated app */
js_brokercam_register(c, lord); /* lord.media: the camera through lord-server (js_brokercam.c) */
+ js_brokermail_register(c, lord, id); /* lord.mail: system Mail, Calendar, Contacts, Reminders (js_brokermail.c) */
}
diff --git a/server/src/ui/js_broker.h b/server/src/ui/js_broker.h
index ad04725..f2df796 100644
--- a/server/src/ui/js_broker.h
+++ b/server/src/ui/js_broker.h
@@ -22,6 +22,11 @@ void app_windows_register(JSContext *c, JSValue lord);
int js_broker_rpc(int op, const void *payload, uint32_t len, int *status, char **out, uint32_t *outlen);
int js_broker_rpc_fd(int op, const void *payload, uint32_t len, char *info, size_t n);
int js_broker_send(int op, const void *payload, uint32_t len);
+/* the same RPC passing fds (SCM_RIGHTS, at most 16) with the request: files for lord-maild */
+int js_broker_rpc_fds(int op, const void *payload, uint32_t len, const int *fds, int nfds, int *status, char **out, uint32_t *outlen);
+/* lord.mail of the isolated system Mail, Calendar, Contacts and Reminders (js_brokermail.c) */
+void js_brokermail_register(JSContext *c, JSValue lord, const char *app_id);
+void js_brokermail_chunk(const char *data, size_t len);
/* lord.media of an isolated app: the camera (js_brokercam.c) */
void js_brokercam_register(JSContext *c, JSValue lord);
void js_brokercam_event(const char *data, size_t len);
diff --git a/server/src/ui/js_brokermail.c b/server/src/ui/js_brokermail.c
new file mode 100644
index 0000000..5e737b4
--- /dev/null
+++ b/server/src/ui/js_brokermail.c
@@ -0,0 +1,288 @@
+/* js_brokermail.c — lord.mail inside the process of the isolated system Mail, Calendar, Contacts
+ * and Reminders (`lord-server --app <id>`). The same API as the session's lord.mail (js_mail.c), so
+ * sdk/mail.js, sdk/calendar.js and sdk/contacts.js work unchanged, but every call goes over the
+ * broker (BOP_MAIL, sec/brokermail.c) and lord-server checks it:
+ *
+ * request(json, [fds]) → id; files are fds the app holds (from the system file dialog)
+ * poll() / pending() results and events, which lord-server pushes as "mail" events in chunks
+ * available() / start()
+ * config() / saveConfig(json) / allowImages([urls]) Mail only
+ * bind(node, image) / release(image) lord-server hands a sealed memfd with the pixels
+ * attachmentFd(rel) → read-only fd of a cached attachment (Mail; to save it), or -1
+ * openAttachment(rel, name) the session opens it with the user's apps (Mail)
+ * cacheDir() "" (this process cannot read the cache)
+ * appMode true
+ *
+ * The process has no network and no access to ~/.local/share/lordos/mail or the accounts file. */
+#include "js_broker.h"
+#include "js_err.h"
+#include "ui.h"
+#include "../sec/broker.h"
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+#define BIG_REQ (120 * 1024) /* larger requests go in a memfd ("reqm") */
+
+/* the batch being received ('C' chunks until 'F') and the complete items waiting for poll() */
+static char *part, *ready;
+static size_t part_n, part_cap, ready_n, ready_cap;
+
+static int append(char **b, size_t *n, size_t *cap, const char *s, size_t len) {
+ if (*n + len + 1 > *cap) {
+ size_t nc = *cap ? *cap : 4096;
+ while (nc < *n + len + 1) nc *= 2;
+ if (nc > (64u << 20)) return -1;
+ char *nb = realloc(*b, nc);
+ if (!nb) return -1;
+ *b = nb;
+ *cap = nc;
+ }
+ memcpy(*b + *n, s, len);
+ *n += len;
+ (*b)[*n] = 0;
+ return 0;
+}
+
+void js_brokermail_chunk(const char *data, size_t len) {
+ if (!len || (data[0] != 'C' && data[0] != 'F')) return;
+ if (append(&part, &part_n, &part_cap, data + 1, len - 1)) { part_n = 0; return; }
+ if (data[0] == 'C') return;
+ /* a whole batch: "[item,item…]" → the items join the ready list */
+ if (part_n >= 2 && part[0] == '[' && part[part_n - 1] == ']' && part_n > 2) {
+ if (ready_n) append(&ready, &ready_n, &ready_cap, ",", 1);
+ append(&ready, &ready_n, &ready_cap, part + 1, part_n - 2);
+ }
+ part_n = 0;
+}
+
+static int verb_rpc(const char *verb, const char *rest, size_t rl, const int *fds, int nfds, int *st, char **out, uint32_t *ol) {
+ size_t vl = strlen(verb);
+ char *p = malloc(vl + 1 + rl + 1);
+ if (!p) return -1;
+ memcpy(p, verb, vl + 1);
+ if (rl) memcpy(p + vl + 1, rest, rl);
+ p[vl + 1 + rl] = 0;
+ int r = js_broker_rpc_fds(BOP_MAIL, p, (uint32_t)(vl + 1 + rl), fds, nfds, st, out, ol);
+ free(p);
+ return r;
+}
+
+static int simple(const char *verb, const char *rest) {
+ int st = BST_ERROR;
+ char *out = NULL;
+ uint32_t ol = 0;
+ int r = verb_rpc(verb, rest, rest ? strlen(rest) : 0, NULL, 0, &st, &out, &ol);
+ int ok = !r && st == BST_OK && out && ol && out[0] == '1';
+ free(out);
+ return ok;
+}
+
+static JSValue f_available(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; (void)argc; (void)argv; return JS_NewBool(c, simple("available", NULL)); }
+static JSValue f_start(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; (void)argc; (void)argv; return JS_NewBool(c, simple("start", NULL)); }
+
+static JSValue f_request(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ size_t len = 0;
+ const char *j = argc > 0 && JS_IsString(argv[0]) ? JS_ToCStringLen(c, &len, argv[0]) : NULL;
+ if (!j) return js_throw_code(c, "sys.badArgument", NULL);
+ int fds[16], nfds = 0;
+ if (argc > 1 && JS_IsArray(c, argv[1])) {
+ JSValue lv = JS_GetPropertyStr(c, argv[1], "length");
+ int32_t n = 0;
+ JS_ToInt32(c, &n, lv);
+ JS_FreeValue(c, lv);
+ if (n < 0 || n > 15) { JS_FreeCString(c, j); return js_throw_code(c, "mail.tooManyFiles", "max", "15", NULL); }
+ for (int i = 0; i < n; i++) {
+ JSValue v = JS_GetPropertyUint32(c, argv[1], (uint32_t)i);
+ int32_t fd = -1;
+ if (JS_IsNumber(v)) JS_ToInt32(c, &fd, v);
+ JS_FreeValue(c, v);
+ if (fd < 0) { JS_FreeCString(c, j); return js_throw_code(c, "fs.outsideHome", NULL); } /* paths mean nothing here */
+ fds[nfds++] = fd;
+ }
+ }
+ int st = BST_ERROR, r;
+ char *out = NULL;
+ uint32_t ol = 0;
+ if (len > BIG_REQ) {
+ int m = memfd_create("lordos-mail-req", MFD_CLOEXEC);
+ size_t w = 0;
+ while (m >= 0 && w < len) { ssize_t k = write(m, j + w, len - w); if (k <= 0) break; w += (size_t)k; }
+ if (m < 0 || w != len) { if (m >= 0) close(m); JS_FreeCString(c, j); return js_throw_code(c, "mail.requestTooLarge", NULL); }
+ int all[16];
+ all[0] = m;
+ memcpy(all + 1, fds, (size_t)nfds * sizeof(int));
+ r = verb_rpc("reqm", NULL, 0, all, nfds + 1, &st, &out, &ol);
+ close(m);
+ } else r = verb_rpc("req", j, len, fds, nfds, &st, &out, &ol);
+ JS_FreeCString(c, j);
+ int id = !r && st == BST_OK && out ? atoi(out) : -1;
+ JSValue err = JS_UNDEFINED;
+ if (!r && st != BST_OK) err = out && ol && lerr_is(out) ? js_throw_line(c, out) : js_throw_code(c, st == BST_DENIED ? "mail.denied" : "sys.badArgument", NULL);
+ free(out);
+ if (!JS_IsUndefined(err)) return err;
+ return JS_NewInt32(c, id);
+}
+
+static JSValue f_poll(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ if (!ready_n) return JS_NULL;
+ char *s = malloc(ready_n + 3);
+ if (!s) return JS_NULL;
+ s[0] = '[';
+ memcpy(s + 1, ready, ready_n);
+ s[ready_n + 1] = ']';
+ s[ready_n + 2] = 0;
+ size_t n = ready_n + 2;
+ ready_n = 0;
+ JSValue v = JS_ParseJSON(c, s, n, "<mail>");
+ free(s);
+ if (JS_IsException(v)) { JS_FreeValue(c, JS_GetException(c)); return JS_NULL; }
+ return v;
+}
+
+static JSValue f_pending(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; (void)argc; (void)argv; return JS_NewInt32(c, 0); }
+
+static JSValue f_config(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t; (void)argc; (void)argv;
+ int st = BST_ERROR;
+ char *out = NULL;
+ uint32_t ol = 0;
+ int r = verb_rpc("config", NULL, 0, NULL, 0, &st, &out, &ol);
+ JSValue v = !r && st == BST_OK && out ? JS_NewStringLen(c, out, ol) : JS_NewString(c, "");
+ free(out);
+ return v;
+}
+
+static JSValue f_save_config(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ size_t len = 0;
+ const char *j = argc > 0 && JS_IsString(argv[0]) ? JS_ToCStringLen(c, &len, argv[0]) : NULL;
+ if (!j) return js_throw_code(c, "sys.badArgument", NULL);
+ int st = BST_ERROR;
+ char *out = NULL;
+ uint32_t ol = 0;
+ int r = verb_rpc("save", j, len, NULL, 0, &st, &out, &ol);
+ JS_FreeCString(c, j);
+ JSValue v = JS_TRUE;
+ if (r || st != BST_OK) v = out && ol && lerr_is(out) ? js_throw_line(c, out) : js_throw_code(c, "mail.badAccounts", NULL);
+ free(out);
+ return v;
+}
+
+static JSValue f_allow_images(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ if (argc < 1 || !JS_IsArray(c, argv[0])) return js_throw_code(c, "sys.badArgument", NULL);
+ JSValue lv = JS_GetPropertyStr(c, argv[0], "length");
+ int32_t n = 0;
+ JS_ToInt32(c, &n, lv);
+ JS_FreeValue(c, lv);
+ if (n > 200) n = 200;
+ char *buf = NULL;
+ size_t bn = 0, bc = 0;
+ for (int i = 0; i < n; i++) {
+ JSValue v = JS_GetPropertyUint32(c, argv[0], (uint32_t)i);
+ if (JS_IsString(v)) {
+ size_t l = 0;
+ const char *s = JS_ToCStringLen(c, &l, v);
+ if (s && l && l < 2048 && !memchr(s, 0, l)) { append(&buf, &bn, &bc, s, l); append(&buf, &bn, &bc, "", 1); }
+ if (s) JS_FreeCString(c, s);
+ }
+ JS_FreeValue(c, v);
+ }
+ int st;
+ if (bn) verb_rpc("images", buf, bn, NULL, 0, &st, NULL, NULL);
+ free(buf);
+ return JS_UNDEFINED;
+}
+
+/* lord.mail.bind(node, image): the pixels come in a sealed memfd from lord-server */
+static JSValue f_bind(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int32_t nid = -1, handle = 0;
+ if (argc > 0) JS_ToInt32(c, &nid, argv[0]);
+ if (argc > 1) JS_ToInt32(c, &handle, argv[1]);
+ Node *n = node_get(nid);
+ if (!n || n->type != NODE_IMAGE) return JS_FALSE;
+ if (handle <= 0) { image_release(n->img); n->img = NULL; node_invalidate(n); return JS_TRUE; }
+ char req[24], info[64] = "";
+ int k = snprintf(req, sizeof req, "img%c%d", 0, (int)handle);
+ int fd = js_broker_rpc_fd(BOP_MAIL, req, (uint32_t)k, info, sizeof info);
+ if (fd < 0) return JS_FALSE;
+ int w = 0, h = 0;
+ sscanf(info, "%d %d", &w, &h);
+ JSValue ok = JS_FALSE;
+ off_t size = lseek(fd, 0, SEEK_END);
+ if (w > 0 && h > 0 && w <= 8192 && h <= 8192 && size >= (off_t)w * h * 4) {
+ void *px = mmap(NULL, (size_t)w * h * 4, PROT_READ, MAP_SHARED, fd, 0);
+ if (px != MAP_FAILED) {
+ Image *img = image_argb(n->img, w, h, px);
+ munmap(px, (size_t)w * h * 4);
+ if (img) { n->img = img; node_invalidate(n); ok = JS_TRUE; }
+ }
+ }
+ close(fd);
+ return ok;
+}
+
+static JSValue f_release(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ int32_t handle = 0;
+ if (argc > 0) JS_ToInt32(c, &handle, argv[0]);
+ char req[24];
+ int k = snprintf(req, sizeof req, "release%c%d", 0, (int)handle);
+ if (handle > 0) js_broker_send(BOP_MAIL, req, (uint32_t)k); /* its reply is dropped by js_broker_poll */
+ return JS_UNDEFINED;
+}
+
+static JSValue f_cache_dir(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) { (void)t; (void)argc; (void)argv; return JS_NewString(c, ""); }
+
+static JSValue f_attachment_fd(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *rel = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(c, argv[0]) : NULL;
+ if (!rel) return JS_NewInt32(c, -1);
+ char req[1100];
+ int k = snprintf(req, sizeof req, "att%c%s", 0, rel);
+ JS_FreeCString(c, rel);
+ if (k <= 0 || (size_t)k >= sizeof req) return JS_NewInt32(c, -1);
+ return JS_NewInt32(c, js_broker_rpc_fd(BOP_MAIL, req, (uint32_t)k, NULL, 0));
+}
+
+static JSValue f_open_attachment(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *rel = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(c, argv[0]) : NULL;
+ const char *name = argc > 1 && JS_IsString(argv[1]) ? JS_ToCString(c, argv[1]) : NULL;
+ int ok = 0;
+ if (rel) {
+ char req[1400];
+ int k = snprintf(req, sizeof req, "open%c%s%c%.255s", 0, rel, 0, name ? name : "");
+ int st = BST_ERROR;
+ if (k > 0 && (size_t)k < sizeof req) ok = !js_broker_rpc(BOP_MAIL, req, (uint32_t)k, &st, NULL, NULL) && st == BST_OK;
+ }
+ if (rel) JS_FreeCString(c, rel);
+ if (name) JS_FreeCString(c, name);
+ return JS_NewBool(c, ok);
+}
+
+static const JSCFunctionListEntry mail_funcs[] = {
+ JS_CFUNC_DEF("available", 0, f_available), JS_CFUNC_DEF("start", 0, f_start),
+ JS_CFUNC_DEF("request", 2, f_request), JS_CFUNC_DEF("poll", 0, f_poll), JS_CFUNC_DEF("pending", 0, f_pending),
+ JS_CFUNC_DEF("config", 0, f_config), JS_CFUNC_DEF("saveConfig", 1, f_save_config),
+ JS_CFUNC_DEF("allowImages", 1, f_allow_images), JS_CFUNC_DEF("bind", 2, f_bind), JS_CFUNC_DEF("release", 1, f_release),
+ JS_CFUNC_DEF("cacheDir", 0, f_cache_dir), JS_CFUNC_DEF("attachmentFd", 1, f_attachment_fd),
+ JS_CFUNC_DEF("openAttachment", 2, f_open_attachment),
+};
+
+void js_brokermail_register(JSContext *c, JSValue lord, const char *app_id) {
+ /* only the system apps that use lord-maild (lord-server refuses everyone else anyway) */
+ if (!app_id || (strcmp(app_id, "mail") && strcmp(app_id, "calendar") && strcmp(app_id, "contacts") && strcmp(app_id, "reminders"))) return;
+ JSValue o = JS_NewObject(c);
+ JS_SetPropertyFunctionList(c, o, mail_funcs, sizeof mail_funcs / sizeof mail_funcs[0]);
+ JS_SetPropertyStr(c, o, "appMode", JS_TRUE);
+ JS_SetPropertyStr(c, lord, "mail", o);
+}
diff --git a/server/src/ui/js_mail.c b/server/src/ui/js_mail.c
index 9ff6aaf..1e7e1f8 100644
--- a/server/src/ui/js_mail.c
+++ b/server/src/ui/js_mail.c
@@ -143,44 +143,18 @@ static JSValue f_config(JSContext *c, JSValueConst t, int argc, JSValueConst *ar
return v;
}
-static int mkdirs(const char *p) {
- char tmp[PATH_MAX];
- snprintf(tmp, sizeof tmp, "%s", p);
- for (char *s = tmp + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(tmp, 0700); *s = '/'; }
- return mkdir(tmp, 0700) && errno != EEXIST ? -1 : 0;
-}
-
/* The accounts file holds security decisions (which servers lord-maild may reach, trusted
- * certificate fingerprints): JS cannot write it through lord.fs (fsops_protected), only here. */
+ * certificate fingerprints): JS cannot write it through lord.fs (fsops_protected), only here and,
+ * for the isolated Mail app, through the broker (sec/brokermail.c). Both use mail_save_config. */
static JSValue f_save_config(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
(void)t;
size_t len = 0;
const char *j = arg_str(c, argc, argv, 0, &len);
if (!j) return js_throw_code(c, "sys.badArgument", NULL);
- JDoc d;
- int bad = len > MAIL_CONFIG_MAX || json_parse(j, len, &d, NULL, 0);
- if (!bad) {
- const JVal *acc = json_get(d.root, "accounts");
- bad = d.root->type != J_OBJ || (acc && (acc->type != J_ARR || acc->len > MAIL_MAX_ACCOUNTS));
- /* no secrets in this file */
- for (const JVal *a = acc ? acc->kid : NULL; !bad && a; a = a->next) if (json_get(a, "password") || json_get(a, "secret")) bad = 1;
- json_free(&d);
- }
- if (bad) { JS_FreeCString(c, j); return js_throw_code(c, "mail.badAccounts", NULL); }
- char dir[PATH_MAX], tmp[PATH_MAX + 16];
- snprintf(dir, sizeof dir, "%s", mail_config_path());
- char *slash = strrchr(dir, '/');
- if (slash) *slash = 0;
- if (mkdirs(dir)) { JS_FreeCString(c, j); return js_throw_code(c, "sys.writeFailed", "path", dir, NULL); }
- snprintf(tmp, sizeof tmp, "%s.tmp", mail_config_path());
- int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);
- int ok = fd >= 0 && write(fd, j, len) == (ssize_t)len && fsync(fd) == 0;
- if (fd >= 0) close(fd);
- ok = ok && rename(tmp, mail_config_path()) == 0;
- if (!ok) unlink(tmp);
+ int r = mail_save_config(j, len);
JS_FreeCString(c, j);
- if (!ok) return js_throw_code(c, "sys.writeFailed", "path", mail_config_path(), NULL);
- mail_reload_config();
+ if (r == 1) return js_throw_code(c, "mail.badAccounts", NULL);
+ if (r) return js_throw_code(c, "sys.writeFailed", "path", mail_config_path(), NULL);
return JS_TRUE;
}
diff --git a/server/src/ui/js_sec.c b/server/src/ui/js_sec.c
index 6452537..032a128 100644
--- a/server/src/ui/js_sec.c
+++ b/server/src/ui/js_sec.c
@@ -212,7 +212,21 @@ static JSValue f_broker_quit(JSContext *c, JSValueConst t, int argc, JSValueCons
if (app) JS_FreeCString(c, app);
return JS_NewBool(c, ok);
}
+/* lord.broker.openArgs(app, json, newWindow) → true if delivered or kept: args for an isolated app
+ * (wm.open(id, { args }) in the session, e.g. a notification's "Open" or the Dock's "New message").
+ * Sent as an "open" event now if the app runs, or when it starts (sdk/packages.js isolatedApp). */
+static JSValue f_broker_open_args(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {
+ (void)t;
+ const char *app = argc > 0 && JS_IsString(argv[0]) ? JS_ToCString(c, argv[0]) : NULL;
+ size_t len = 0;
+ const char *json = argc > 1 && JS_IsString(argv[1]) ? JS_ToCStringLen(c, &len, argv[1]) : NULL;
+ int ok = app && json && brokersrv_open_args(app, json, len, argc > 2 && JS_ToBool(c, argv[2])) == 0;
+ if (app) JS_FreeCString(c, app);
+ if (json) JS_FreeCString(c, json);
+ return JS_NewBool(c, ok);
+}
static const JSCFunctionListEntry broker_funcs[] = {
+ JS_CFUNC_DEF("openArgs", 3, f_broker_open_args),
JS_CFUNC_DEF("resolve", 2, f_broker_resolve),
JS_CFUNC_DEF("publish", 2, f_broker_publish),
JS_CFUNC_DEF("pickResult", 2, f_broker_pick_result),
diff --git a/server/src/ui/js_sys.c b/server/src/ui/js_sys.c
index 93db63e..9916fd3 100644
--- a/server/src/ui/js_sys.c
+++ b/server/src/ui/js_sys.c
@@ -1985,6 +1985,8 @@ static void add_object(JSContext *c, JSValue parent, const char *name, const JSC
void js_sys_register_app(JSContext *c, JSValue lord) {
add_object(c, lord, "text", text_funcs, sizeof text_funcs / sizeof text_funcs[0]);
add_object(c, lord, "image", image_funcs, sizeof image_funcs / sizeof image_funcs[0]);
+ /* text measuring is local (fonts already loaded): Mail's body editor lays out lines with it */
+ JS_SetPropertyStr(c, lord, "measureText", JS_NewCFunction(c, f_measure_text, "measureText", 3));
}
void js_sys_register(JSContext *c, JSValue lord) {
diff --git a/server/tests/broker_restrict_test.c b/server/tests/broker_restrict_test.c
index 0884582..1730a54 100644
--- a/server/tests/broker_restrict_test.c
+++ b/server/tests/broker_restrict_test.c
@@ -47,6 +47,17 @@ int brokerkr_resolve(uint32_t prompt, int allow) { (void)prompt; (void)allow; re
void brokerkr_conn_closed(int conn) { (void)conn; }
void brokerkr_tick(void) {}
int brokerkr_pollfd(void) { return -1; }
+void brokermail_handle(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len, int *fds, int nfds) {
+ (void)conn; (void)app; (void)payload; (void)len;
+ for (int i = 0; i < nfds; i++) if (fds[i] >= 0) { close(fds[i]); fds[i] = -1; }
+ brokersrv_reply(fd, reqid, BST_DENIED, NULL, 0, -1);
+}
+void brokermail_sys_open(int conn, int fd, uint32_t reqid, const char *app, char *payload, uint32_t len) { (void)conn; (void)app; (void)payload; (void)len; brokersrv_reply(fd, reqid, BST_DENIED, NULL, 0, -1); }
+void brokermail_conn_closed(int conn) { (void)conn; }
+void brokermail_tick(void) {}
+int brokermail_pollfd(void) { return -1; }
+int brokermail_wants_write(int conn) { (void)conn; return 0; }
+int lpk_valid_id(const char *id) { return id && id[0] && strlen(id) < 48; }
struct MAudio { int open; };
static struct MAudio mics[8];
diff --git a/server/tests/brokerkr_e2e.c b/server/tests/brokerkr_e2e.c
index 65635e5..d126fa2 100644
--- a/server/tests/brokerkr_e2e.c
+++ b/server/tests/brokerkr_e2e.c
@@ -30,6 +30,8 @@ int brokersrv_reply(int fd, uint32_t reqid, int status, const void *data, uint32
return sendmsg(fd, &m, MSG_NOSIGNAL) < 0 ? -1 : 0;
}
void brokersrv_prompt_event(const char *json) { snprintf(prompt, sizeof prompt, "%s", json); nprompts++; }
+/* connection 7 stands for a system package (assets/sysapps): its owner is its plain id */
+int brokersrv_conn_system(int conn) { return conn == 7; }
static int app_end, srv_end;
static uint32_t next_req = 1;
@@ -37,6 +39,7 @@ static char got[1 << 16];
static int got_status;
/* the app sends op/service/account/label/secret; waits for the reply (or a prompt) */
+static int call_conn; /* broker connection the request comes from (7 = a system package) */
static int call(const char *app, const char *op, const char *service, const char *account, const char *label, const char *secret, size_t secret_len) {
char p[4096];
size_t o = 0;
@@ -46,7 +49,7 @@ static int call(const char *app, const char *op, const char *service, const char
o += secret_len;
p[o] = 0;
int before = nprompts;
- brokerkr_handle(0, srv_end, next_req++, app, p, (uint32_t)o);
+ brokerkr_handle(call_conn, srv_end, next_req++, app, p, (uint32_t)o);
double t0 = now_ms();
while (now_ms() - t0 < 20000) {
brokerkr_tick();
@@ -158,6 +161,13 @@ int main(void) {
k = CALL("mail", "get", "imap.example.com", "ana", "");
check(k == 'p' && strstr(prompt, "\"owner\":\"mail\""), ".lpk \"mail\" (owner app.mail) does not own the desktop's \"mail\" item");
check(answer(0) == 'r' && is_err(BST_DENIED, "keyring.notShared"), "denied");
+ /* the system Mail app (assets/sysapps, its own process) keeps the desktop's owner "mail" */
+ call_conn = 7;
+ k = CALL("mail", "get", "imap.example.com", "ana", "");
+ check(k == 'r' && is_ok() && strstr(got, "desk-secret"), "system package \"mail\" (owner mail) reads the desktop's \"mail\" item");
+ CALL("mail", "list", "", "", "");
+ check(is_ok() && !strstr(got, "sync.example.org"), "system \"mail\" still does not see other apps' items");
+ call_conn = 0;
/* bad requests */
CALL("alpha", "nope", "x", "", "");
diff --git a/server/tests/brokermail_test.c b/server/tests/brokermail_test.c
new file mode 100644
index 0000000..78bcb05
--- /dev/null
+++ b/server/tests/brokermail_test.c
@@ -0,0 +1,218 @@
+/* brokermail_test.c — lord-maild for the isolated system apps (src/sec/brokermail.c, BOP_MAIL and
+ * BOP_SYS_OPEN): who may ask, which requests each app may send, which files may travel to
+ * lord-maild, the Mail-only verbs (accounts file, remote images, attachments) and opening another
+ * app. The real brokermail.c runs against stand-ins for brokersrv.c and mailc.c that record what
+ * would have reached lord-maild or the session. Temporary HOME.
+ * `make build/brokermail-test && build/brokermail-test`. */
+#include "sec/broker_int.h"
+#include "mail/mailc.h"
+
+#include <fcntl.h>
+#include <limits.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static int fails, total;
+static void check(int ok, const char *what) { total++; printf("%s: %s\n", ok ? "ok " : "FAIL", what); if (!ok) fails++; }
+
+/* ---- stand-ins for brokersrv.c ---- */
+static int sys_conn[8];
+static const char *conn_app[8] = { "mail", "calendar", "reminders", "contacts", "mail", "notes" };
+const char *brokersrv_conn_app(int conn) { return conn >= 0 && conn < 8 ? conn_app[conn] : NULL; }
+int brokersrv_conn_system(int conn) { return conn >= 0 && conn < 8 && sys_conn[conn]; }
+int brokersrv_conn_event(int conn, const char *kind, const char *data, size_t len) { (void)conn; (void)kind; (void)data; (void)len; return 0; }
+static int last_status, last_fd = -1;
+static char last_reply[4096];
+int brokersrv_reply(int fd, uint32_t reqid, int status, const void *data, uint32_t len, int passfd) {
+ (void)fd; (void)reqid;
+ last_status = status;
+ snprintf(last_reply, sizeof last_reply, "%.*s", (int)len, data ? (const char *)data : "");
+ if (last_fd >= 0) close(last_fd);
+ last_fd = passfd >= 0 ? dup(passfd) : -1;
+ return 0;
+}
+static char shell_kind[32], shell_json[4096];
+void brokersrv_shell_event(const char *kind, const char *json) { snprintf(shell_kind, sizeof shell_kind, "%s", kind); snprintf(shell_json, sizeof shell_json, "%s", json); }
+
+/* ---- stand-ins for mailc.c ---- */
+static char home[PATH_MAX], cache[PATH_MAX + 32], cfg[PATH_MAX + 64];
+static int owners_open, owner_mask[MAIL_OWNERS + 1];
+static int req_count, req_owner, req_nfds;
+static char req_json[4096], saved[4096];
+static int images_n;
+int mail_available(void) { return 0; }
+int mail_start(void) { return 0; }
+const char *mail_config_path(void) { return cfg; }
+const char *mail_cache_path(void) { return cache; }
+int mail_owner_open(int mask) { if (owners_open >= MAIL_OWNERS) return -1; owner_mask[++owners_open] = mask; return owners_open; }
+void mail_owner_close(int owner) { (void)owner; }
+int mail_request_as(int owner, const char *json, size_t len, int *fds, int nfds) {
+ req_count++;
+ req_owner = owner;
+ req_nfds = nfds;
+ snprintf(req_json, sizeof req_json, "%.*s", (int)len, json);
+ for (int i = 0; i < nfds; i++) close(fds[i]);
+ return 100 + req_count;
+}
+char *mail_poll_owner(int owner) { (void)owner; return NULL; }
+int mail_owner_pollfd(void) { return -1; }
+void mail_owner_clear_wake(void) {}
+int mail_image_fd(int owner, int handle, int *w, int *h) { (void)owner; (void)handle; *w = *h = 0; return -1; }
+void mail_image_release_as(int owner, int handle) { (void)owner; (void)handle; }
+int mail_save_config(const char *json, size_t len) { snprintf(saved, sizeof saved, "%.*s", (int)len, json); return strstr(saved, "password") ? 1 : 0; }
+void mail_allow_hosts(const char *const *urls, int n, int seconds) { (void)urls; (void)seconds; images_n = n; }
+
+/* ---- helpers ---- */
+static uint32_t reqid;
+/* payload "verb\0rest" (rest may hold NULs: pass its length) */
+static int call(int conn, const char *verb, const char *rest, size_t rl, int *fds, int nfds) {
+ char p[8192];
+ size_t vl = strlen(verb);
+ memcpy(p, verb, vl + 1);
+ memcpy(p + vl + 1, rest, rl);
+ p[vl + 1 + rl] = 0;
+ int copy[16];
+ for (int i = 0; i < nfds; i++) copy[i] = fds[i];
+ brokermail_handle(conn, 9, ++reqid, conn_app[conn], p, (uint32_t)(vl + 1 + rl), copy, nfds);
+ int leaked = 0; /* the handler closes or keeps every fd */
+ for (int i = 0; i < nfds; i++) if (copy[i] >= 0) leaked = 1;
+ if (leaked) { printf("FAIL: an fd was neither used nor closed\n"); fails++; }
+ return last_status;
+}
+static int req(int conn, const char *json, int *fds, int nfds) { return call(conn, "req", json, strlen(json), fds, nfds); }
+static int sysopen(int conn, const char *target, int nw, const char *json) {
+ char p[2048];
+ size_t n = (size_t)snprintf(p, sizeof p, "%s%c%c%c%s", target, 0, nw ? '1' : '0', 0, json);
+ shell_kind[0] = 0;
+ brokermail_sys_open(conn, 9, ++reqid, conn_app[conn], p, (uint32_t)n);
+ return last_status;
+}
+static int file_fd(const char *name, const char *text) {
+ char path[PATH_MAX + 64];
+ snprintf(path, sizeof path, "%s/%s", home, name);
+ int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600);
+ if (fd >= 0 && write(fd, text, strlen(text)) < 0) { close(fd); return -1; }
+ return fd;
+}
+
+int main(void) {
+ snprintf(home, sizeof home, "/tmp/brokermail-test-%d", (int)getpid());
+ mkdir(home, 0700);
+ snprintf(cache, sizeof cache, "%s/cache", home);
+ snprintf(cfg, sizeof cfg, "%s/accounts.json", home);
+ mkdir(cache, 0700);
+ char d[PATH_MAX + 64];
+ snprintf(d, sizeof d, "%s/att", cache); mkdir(d, 0700);
+ snprintf(d, sizeof d, "%s/att/acct", cache); mkdir(d, 0700);
+ snprintf(d, sizeof d, "%s/att/acct/7-1", cache); mkdir(d, 0700);
+ snprintf(d, sizeof d, "%s/att/acct/7-1/report.pdf", cache);
+ { int f = open(d, O_WRONLY | O_CREAT, 0600); if (f >= 0) { if (write(f, "%PDF", 4) < 0) { /* checked below */ } close(f); } }
+ { char secret[PATH_MAX + 64]; snprintf(secret, sizeof secret, "%s/secret.txt", home); int f = open(secret, O_WRONLY | O_CREAT, 0600); if (f >= 0) close(f);
+ snprintf(d, sizeof d, "%s/att/acct/7-1/link", cache); if (symlink(secret, d)) { /* the test below fails */ } }
+ for (int i = 0; i < 5; i++) sys_conn[i] = 1; /* conn 5 ("notes") is a user package */
+
+ /* who may ask */
+ check(req(5, "{\"op\":\"list\"}", NULL, 0) == BST_DENIED, "a user package (not a system app) gets nothing");
+ sys_conn[4] = 0;
+ check(req(4, "{\"op\":\"list\"}", NULL, 0) == BST_DENIED, "a user .lpk named \"mail\" gets nothing either");
+ sys_conn[4] = 1;
+
+ /* each app sends only its own requests */
+ check(req(0, "{\"op\":\"list\",\"acct\":\"a\"}", NULL, 0) == BST_OK && owner_mask[req_owner] == MAIL_EV_ALL, "Mail: list (all events)");
+ int before = req_count;
+ check(req(1, "{\"op\":\"list\"}", NULL, 0) == BST_DENIED && req_count == before, "Calendar cannot list mail");
+ check(req(1, "{\"op\":\"open\",\"uid\":1}", NULL, 0) == BST_DENIED, "Calendar cannot open a message");
+ check(req(1, "{\"op\":\"send\"}", NULL, 0) == BST_DENIED, "Calendar cannot send mail");
+ check(req(1, "{\"op\":\"ev-list\"}", NULL, 0) == BST_OK && owner_mask[req_owner] == MAIL_EV_PIM, "Calendar: ev-list (PIM events only)");
+ check(req(1, "{\"op\":\"contact-list\"}", NULL, 0) == BST_DENIED, "Calendar cannot read contacts");
+ check(req(2, "{\"op\":\"todo-save\"}", NULL, 0) == BST_OK, "Reminders: todo-save");
+ check(req(2, "{\"op\":\"ev-list\"}", NULL, 0) == BST_DENIED, "Reminders cannot read events");
+ check(req(3, "{\"op\":\"contact-list\"}", NULL, 0) == BST_OK && req(3, "{\"op\":\"autocomplete\",\"q\":\"a\"}", NULL, 0) == BST_OK, "Contacts: contact-list, autocomplete");
+ check(req(3, "{\"op\":\"thread\"}", NULL, 0) == BST_DENIED, "Contacts cannot read threads");
+ check(req(2, "{\"op\":\"status\"}", NULL, 0) == BST_OK, "everyone: status");
+
+ /* malformed requests */
+ check(req(0, "not json", NULL, 0) == BST_ERROR, "not JSON → refused");
+ check(req(0, "{\"x\":1}", NULL, 0) == BST_ERROR, "no op → refused");
+ check(req(0, "{\"op\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", NULL, 0) == BST_ERROR, "an op over 32 bytes → refused");
+
+ /* files */
+ int f = file_fd("budget.txt", "Budget\n");
+ check(req(0, "{\"op\":\"send\"}", &f, 1) == BST_OK && req_nfds == 1, "Mail: send with a regular file");
+ f = file_fd("x.txt", "x");
+ check(req(0, "{\"op\":\"list\"}", &f, 1) == BST_ERROR, "a file with a request that takes none → refused");
+ int sp[2];
+ socketpair(AF_UNIX, SOCK_STREAM, 0, sp);
+ check(req(0, "{\"op\":\"send\"}", &sp[0], 1) == BST_ERROR && !strcmp(last_reply, "fs.outsideHome"), "a socket instead of a file → refused");
+ close(sp[1]);
+ int dfd = open(home, O_RDONLY | O_DIRECTORY);
+ check(req(3, "{\"op\":\"contact-import\"}", &dfd, 1) == BST_ERROR, "a folder fd → refused");
+ char wpath[PATH_MAX + 64];
+ snprintf(wpath, sizeof wpath, "%s/w.txt", home);
+ int wo = open(wpath, O_WRONLY | O_CREAT, 0600);
+ check(req(3, "{\"op\":\"contact-import\"}", &wo, 1) == BST_ERROR, "a write-only fd → refused");
+ f = file_fd("dana.vcf", "BEGIN:VCARD\r\nEND:VCARD\r\n");
+ check(req(3, "{\"op\":\"contact-import\"}", &f, 1) == BST_OK && req_nfds == 1, "Contacts: import a .vcf fd");
+ f = file_fd("e.ics", "BEGIN:VCALENDAR\r\nEND:VCALENDAR\r\n");
+ check(req(1, "{\"op\":\"ev-import\"}", &f, 1) == BST_OK, "Calendar: import an .ics fd");
+ f = file_fd("mail.txt", "x");
+ check(req(1, "{\"op\":\"send\"}", &f, 1) == BST_DENIED, "Calendar cannot send a file as mail");
+
+ /* a large request in a memfd ("reqm") */
+ {
+ int m = memfd_create("req", 0);
+ const char *big = "{\"op\":\"send\",\"text\":\"long body\"}";
+ if (write(m, big, strlen(big)) < 0) { /* checked below */ }
+ int fds2[2] = { m, file_fd("a2.txt", "attachment") };
+ check(call(0, "reqm", "", 0, fds2, 2) == BST_OK && strstr(req_json, "long body") && req_nfds == 1, "reqm: JSON from a memfd, one attachment");
+ }
+
+ /* Mail-only verbs */
+ check(call(1, "config", "", 0, NULL, 0) == BST_DENIED, "Calendar cannot read the accounts file");
+ check(call(0, "config", "", 0, NULL, 0) == BST_OK, "Mail reads the accounts file");
+ const char *acc = "{\"accounts\":[]}";
+ check(call(3, "save", acc, strlen(acc), NULL, 0) == BST_DENIED, "Contacts cannot write the accounts file");
+ check(call(0, "save", acc, strlen(acc), NULL, 0) == BST_OK && !strcmp(saved, acc), "Mail writes the accounts file (validated by mailc)");
+ const char *bad = "{\"accounts\":[{\"password\":\"x\"}]}";
+ check(call(0, "save", bad, strlen(bad), NULL, 0) == BST_ERROR && strstr(last_reply, "mail.badAccounts"), "a password in the accounts file → mail.badAccounts");
+ check(call(2, "images", "https://a.example/x.png\0", 24, NULL, 0) == BST_DENIED, "Reminders cannot open image hosts");
+ images_n = 0;
+ check(call(0, "images", "https://a.example/x.png\0https://b.example/y.png\0", 48, NULL, 0) == BST_OK && images_n == 2, "Mail: remote images of one message");
+
+ /* attachments */
+ check(call(0, "att", "att/acct/7-1/report.pdf", 23, NULL, 0) == BST_OK && last_fd >= 0, "Mail: a read-only fd of a cached attachment");
+ if (last_fd >= 0) { int fl = fcntl(last_fd, F_GETFL); check((fl & O_ACCMODE) == O_RDONLY, "…opened read-only"); }
+ check(call(0, "att", "att/../../secret.txt", 20, NULL, 0) == BST_DENIED, "\"..\" in an attachment path → refused");
+ check(call(0, "att", "accounts.json", 13, NULL, 0) == BST_DENIED, "outside att/ → refused");
+ check(call(0, "att", "att/acct/7-1/link", 17, NULL, 0) == BST_DENIED, "a symlink out of the cache → refused");
+ check(call(1, "att", "att/acct/7-1/report.pdf", 23, NULL, 0) == BST_DENIED, "Calendar cannot read attachments");
+ shell_kind[0] = 0;
+ check(call(0, "open", "att/acct/7-1/report.pdf\0report.pdf", 34, NULL, 0) == BST_OK && !strcmp(shell_kind, "mailopen") && strstr(shell_json, "report.pdf"),
+ "Mail: the session opens a cached attachment");
+ shell_kind[0] = 0;
+ check(call(0, "open", "att/../secret.txt\0x", 19, NULL, 0) == BST_DENIED && !shell_kind[0], "…never a path outside the cache");
+
+ /* opening another system app */
+ check(sysopen(3, "mail", 1, "{\"compose\":{\"to\":[{\"email\":\"[email protected]\"}]}}") == BST_OK && !strcmp(shell_kind, "launch") && strstr(shell_json, "\"new\":true"),
+ "Contacts → Mail: a new message (session event)");
+ check(sysopen(0, "calendar", 0, "{\"at\":1,\"uid\":\"x\"}") == BST_OK, "Mail → Calendar: an invitation");
+ check(sysopen(0, "files", 0, "{}") == BST_DENIED && !shell_kind[0], "not to an app outside the four");
+ check(sysopen(0, "pdf", 0, "{\"path\":\"/home/x/a.pdf\"}") == BST_DENIED, "not to the PDF viewer with a path");
+ check(sysopen(0, "calendar", 0, "{\"path\":\"/etc/passwd\"}") == BST_DENIED, "no \"path\" in the args");
+ check(sysopen(0, "calendar", 0, "[1,2]") == BST_DENIED, "args must be an object");
+ check(sysopen(5, "mail", 0, "{}") == BST_DENIED, "a user package cannot open them");
+
+ brokermail_conn_closed(0);
+ if (last_fd >= 0) close(last_fd);
+ char cmd[PATH_MAX + 32];
+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", home);
+ if (system(cmd)) { /* best effort */ }
+ printf("brokermail-test: %d/%d ok\n", total - fails, total);
+ return fails ? 1 : 0;
+}