diff --git a/src/lib/modules/device/lib/ble.ts b/src/lib/modules/device/lib/ble.ts index b58fa92..f6fb1bc 100644 --- a/src/lib/modules/device/lib/ble.ts +++ b/src/lib/modules/device/lib/ble.ts @@ -1045,7 +1045,7 @@ export class Watch { state: Wp2State, onProgress: (pct: number) => void = () => {}, ) { - const { pkg, slot } = planInstall(data, state, crc32); + const { pkg, slot, body } = planInstall(data, state, crc32); const call = async (req: number, rep: number, payload: Uint8Array) => { await this.send(req, payload); const r = await this.waitFor(rep, 8000); @@ -1065,13 +1065,13 @@ export class Watch { hv = new DataView(head.buffer); head[0] = slot; - hv.setUint32(1, data.length, true); - hv.setUint32(5, crc32(data), true); + hv.setUint32(1, body.length, true); + hv.setUint32(5, crc32(body), true); this.status(`installing ${pkg.name}…`); dbg("install", pkg.name, "v" + pkg.version, "slot", slot === LOADER_SLOT ? "L" : slot); await call(CMD.stubBegin, CMD.stubBeginRep, head); - for (let off = 0; off < data.length; off += MAX_DATA) { - const part = data.subarray(off, off + MAX_DATA); + for (let off = 0; off < body.length; off += MAX_DATA) { + const part = body.subarray(off, off + MAX_DATA); const req = new Uint8Array(4 + part.length); new DataView(req.buffer).setUint32(0, off, true); @@ -1081,7 +1081,7 @@ export class Watch { if (written !== off + part.length) throw new Error(`the watch has ${written} bytes, expected ${off + part.length}`); - onProgress(Math.min(99, Math.floor(((off + part.length) / data.length) * 100))); + onProgress(Math.min(99, Math.floor(((off + part.length) / body.length) * 100))); } // the stub's decrypt returns nothing for an empty plaintext, so END carries one dummy byte await call(CMD.stubEnd, CMD.stubEndRep, new Uint8Array([0])); diff --git a/src/lib/modules/device/lib/wp2.ts b/src/lib/modules/device/lib/wp2.ts index 33cce60..bed34ff 100644 --- a/src/lib/modules/device/lib/wp2.ts +++ b/src/lib/modules/device/lib/wp2.ts @@ -89,12 +89,33 @@ const LOADER_SIZE = 0x1_0000; const APP_SIZE = 0x2_0000; // stub 1 doesn't say which abi_minor it takes; every stub on a watch so far takes 3 const DEFAULT_ABI_MINOR = 3; +// Widget icons (cmf-watch-sdk docs/app-icons.md): an optional trailer after the relocation table, +// outside the header's sizes and body CRC — "WP2W", version 1, count 1..16, size 40, 0, crc32 of the +// pixels, count × 40·40·3 bytes. Stubs before 10 refuse any byte past the relocations. +const STUB_TRAILER = 10; +const ICON_BYTES = 40 * 40 * 3; + +function trailerOk(t: Uint8Array, crc32: (d: Uint8Array) => number) { + if (t.length < 12 || new TextDecoder().decode(t.subarray(0, 4)) !== "WP2W") return false; + const [version, count, side, zero] = t.subarray(4, 8); + + return ( + version === 1 && + count >= 1 && + count <= 16 && + side === 40 && + zero === 0 && + t.length === 12 + count * ICON_BYTES && + crc32(t.subarray(12)) === new DataView(t.buffer, t.byteOffset + 8, 4).getUint32(0, true) + ); +} /** * The stub's own checks (wp2-core pkg.rs: parse_header, check_slot, the body CRC), run before a * byte goes out so a package that would be refused at the end isn't sent first. Returns the slot * it goes to: L for a loader, else the slot that already holds an app of that name (an update - * replaces it), else the first free one. + * replaces it), else the first free one — and `body`, what goes out: the package whole, or for a + * stub before 10 without its widget icon trailer. */ export function planInstall(data: Uint8Array, state: Wp2State, crc32: (d: Uint8Array) => number) { const fail = (why: string) => { @@ -115,8 +136,13 @@ export function planInstall(data: Uint8Array, state: Wp2State, crc32: (d: Uint8A const relocs = dv.getUint32(44, true); if (pkg.size > (pkg.kind === 1 ? LOADER_SIZE : APP_SIZE)) fail("too big for its slot"); - if (data.length !== HEADER_SIZE + pkg.size + 4 * relocs) fail("truncated or padded"); - if (crc32(data.subarray(HEADER_SIZE)) !== pkg.crc) fail("body checksum"); + const end = HEADER_SIZE + pkg.size + 4 * relocs; + + if (data.length < end) fail("truncated or padded"); + if (data.length > end && !trailerOk(data.subarray(end), crc32)) + fail("broken widget icon trailer"); + if (crc32(data.subarray(HEADER_SIZE, end)) !== pkg.crc) fail("body checksum"); + const body = state.stub.version < STUB_TRAILER ? data.subarray(0, end) : data; let slot: number; @@ -129,5 +155,5 @@ export function planInstall(data: Uint8Array, state: Wp2State, crc32: (d: Uint8A else if (free !== undefined) slot = free; else throw new Error(`all ${APP_SLOTS} app slots are taken — remove an app on the watch first`); } else throw new Error("can't install this package: unknown kind"); - return { pkg, slot: slot! }; + return { pkg, slot: slot!, body }; } diff --git a/src/lib/modules/device/messages.ts b/src/lib/modules/device/messages.ts index 28a3dbd..5408fc2 100644 --- a/src/lib/modules/device/messages.ts +++ b/src/lib/modules/device/messages.ts @@ -112,6 +112,7 @@ const en = { "unknown ABI": "unknown ABI", "too big for its slot": "too big for its slot", "truncated or padded": "truncated or padded", + "broken widget icon trailer": "broken widget icon trailer", "body checksum": "body checksum", "unknown kind": "unknown kind", } as Record, @@ -215,6 +216,7 @@ export const bt = dict(en, { "unknown ABI": "неизвестный ABI", "too big for its slot": "не помещается в слот", "truncated or padded": "файл обрезан или дополнен", + "broken widget icon trailer": "повреждён блок иконок виджета", "body checksum": "контрольная сумма данных", "unknown kind": "неизвестный тип", }, @@ -316,6 +318,7 @@ export const bt = dict(en, { "unknown ABI": "невідомий ABI", "too big for its slot": "не вміщується в слот", "truncated or padded": "файл обрізано або доповнено", + "broken widget icon trailer": "пошкоджено блок іконок віджета", "body checksum": "контрольна сума даних", "unknown kind": "невідомий тип", }, @@ -419,6 +422,7 @@ export const bt = dict(en, { "unknown ABI": "ABI desconocida", "too big for its slot": "demasiado grande para su espacio", "truncated or padded": "archivo truncado o con relleno", + "broken widget icon trailer": "bloque de iconos del widget dañado", "body checksum": "suma de comprobación de los datos", "unknown kind": "tipo desconocido", }, @@ -518,6 +522,7 @@ export const bt = dict(en, { "unknown ABI": "अज्ञात ABI", "too big for its slot": "स्लॉट के लिए बहुत बड़ा", "truncated or padded": "फ़ाइल अधूरी या बढ़ी हुई", + "broken widget icon trailer": "विजेट आइकन ब्लॉक खराब है", "body checksum": "डेटा चेकसम", "unknown kind": "अज्ञात प्रकार", }, diff --git a/tests/__fixtures__/icons-stripped.wp2app b/tests/__fixtures__/icons-stripped.wp2app new file mode 100644 index 0000000..126e831 Binary files /dev/null and b/tests/__fixtures__/icons-stripped.wp2app differ diff --git a/tests/__fixtures__/icons.wp2app b/tests/__fixtures__/icons.wp2app new file mode 100644 index 0000000..4baf8c5 Binary files /dev/null and b/tests/__fixtures__/icons.wp2app differ diff --git a/tests/ble-messages.test.ts b/tests/ble-messages.test.ts index dfe8aa1..8c30413 100644 --- a/tests/ble-messages.test.ts +++ b/tests/ble-messages.test.ts @@ -55,6 +55,9 @@ test("the reasons inside a sentence are translated, and the error prefix survive expect(bleText(w, "can't install this package: body checksum")).toBe( "no se puede instalar este paquete: suma de comprobación de los datos", ); + expect(bleText(w, "can't install this package: broken widget icon trailer")).toBe( + "no se puede instalar este paquete: bloque de iconos del widget dañado", + ); expect(bleText(w, "uploading “Dots”… 42%")).toBe("enviando «Dots»… 42%"); expect(bleText(w, "something nobody wrote a rule for")).toBe("something nobody wrote a rule for"); i18nModel.localePicked("en"); diff --git a/tests/wp2.browser.test.ts b/tests/wp2.browser.test.ts index e405e79..4c509cf 100644 --- a/tests/wp2.browser.test.ts +++ b/tests/wp2.browser.test.ts @@ -13,6 +13,15 @@ import { STUB_SLOT, type Wp2State, } from "$lib/modules/device/lib/wp2"; +// built by cmf-watch-sdk (widget-templates) package.pack: an app with 2 widget icons, and the same +// app packed without them — what package.strip_trailer makes of the first +import iconsUrl from "./__fixtures__/icons.wp2app?url"; +import strippedUrl from "./__fixtures__/icons-stripped.wp2app?url"; + +const load = (url: string) => + fetch(url) + .then((r) => r.arrayBuffer()) + .then((b) => new Uint8Array(b)); // a .wp2app header as wp2apps `pack` writes it (<4sHBB24sIIIIII8s) function header(name: string, version: number, crc: number, kind = 0) { @@ -123,8 +132,12 @@ function pack(name: string, size: number, kind = 0, abiMinor = 3) { out.set(body, 64); return out; } -const state = (apps: Record, abiMinor: number | null = 3): Wp2State => ({ - stub: { version: 2, abiMinor }, +const state = ( + apps: Record, + abiMinor: number | null = 3, + version = 2, +): Wp2State => ({ + stub: { version, abiMinor }, loader: null, apps: Object.fromEntries( Object.entries(apps).map(([slot, name]) => [slot, parsePackageHeader(pack(name, 64))!]), @@ -174,6 +187,72 @@ test.each([ expect(() => planInstall(data, st, crc32)).toThrow(why); }); +test("widget icons go whole to stub 10 and later, cut off for an older stub", async () => { + const [icons, stripped] = await Promise.all([load(iconsUrl), load(strippedUrl)]); + + expect(planInstall(icons, state({}, 3, 10), crc32).body).toEqual(icons); + expect(planInstall(icons, state({}, 3, 9), crc32).body).toEqual(stripped); + expect(planInstall(icons, state({}, null, 1), crc32).body).toEqual(stripped); + expect(planInstall(stripped, state({}, 3, 9), crc32).body).toEqual(stripped); +}); + +test.each([ + ["a bad magic", 0, 0x20], + ["an unknown version", 4, 1], + ["no icons", 5, -2], + ["17 icons", 5, 15], + ["another icon size", 6, 1], + ["a nonzero pad", 7, 1], + ["a bad CRC", 12, 1], +] as const)("refuses a widget icon trailer with %s", async (_, at, delta) => { + const icons = await load(iconsUrl); + const stripped = await load(strippedUrl); + const bad = icons.slice(); + + bad[stripped.length + at] += delta; + for (const version of [9, 10]) + expect(() => planInstall(bad, state({}, 3, version), crc32)).toThrow( + /broken widget icon trailer/, + ); +}); + +test("refuses a widget icon trailer that is cut short or runs long", async () => { + const icons = await load(iconsUrl); + const stripped = await load(strippedUrl); + const long = new Uint8Array(icons.length + 1); + + long.set(icons); + for (const bad of [icons.subarray(0, -1), long, icons.subarray(0, stripped.length + 5)]) + expect(() => planInstall(bad, state({}, 3, 10), crc32)).toThrow(/broken widget icon trailer/); +}); + +test("an older stub is sent the package without its icons, size and CRC to match", async () => { + const [icons, stripped] = await Promise.all([load(iconsUrl), load(strippedUrl)]); + const w = new Watch(); + const sent: [number, Uint8Array][] = []; + let written = 0; + let last = 0; + + w.send = async (key, payload) => { + sent.push([key, payload!]); + last = key; + if (key === CMD.stubData) written += payload!.length - 4; + }; + w.waitFor = async () => { + if (last !== CMD.stubData) return new Uint8Array([0]); + const r = new Uint8Array(5); + + new DataView(r.buffer).setUint32(1, written, true); + return r; + }; + await w.installPackage(icons, state({}, 3, 9)); + const begin = new DataView(sent[0][1].buffer); + + expect(begin.getUint32(1, true)).toBe(stripped.length); + expect(begin.getUint32(5, true)).toBe(crc32(stripped)); + expect(written).toBe(stripped.length); +}); + test("an install is BEGIN, DATA at the stub's offset in 128-byte pieces, END", async () => { const w = new Watch(); const data = pack("workout", 300);