1 Commits
Author SHA1 Message Date
Shelley e04b22b359 Introduce BookSprite with isolated Kobo install, verified OTA and snapshot recovery
macos / macOS 15 ARM64 🔨16.4 🎯11.0 (push) Canceled after 0s
macos / macOS 15 x86-64 🔨16.4 🎯10.15 (push) Canceled after 0s
Co-authored-by: Shelley <shelley@exe.dev>
2026-10-30 20:03:54 +00:00
20 changed files with 2238 additions and 472 deletions

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
# BookSprite maintenance
BookSprite is a personal Kobo Clara 2E fork of KOReader. Keep upstream history and
all features; do not redesign menus until the owner asks. Upstream remote is
https://github.com/koreader/koreader.git; initial base is v2026.07.1.
- Public home: https://gitea.jameshall.xyz/exe.dev/booksprite (branch main).
- VM push/API integration: https://forgejo.int.exe.xyz/ (credentials injected).
- Native libraries come from checksum-pinned official Kobo release ZIPs.
Lua is interpreted on device; our build overlays the modified source files.
- Build: `python3 booksprite/build.py`. Test: `python3 -m unittest discover -s booksprite/tests -v`.
- See booksprite/README.md for USB installation, OTA release process and recovery.
- Releases must never contain settings, private books, credentials or signing secrets.
- Never write a Kobo firmware update, replace NickelMenu, or touch .adds/koreader.
- Never ship an OTA automatically from a code change; publish only when asked.
- Keep the outer supervisor stable; app OTA archives cannot replace launch.sh.
- On upstream merges: review changed runtime files and update build.py OVERLAY;
native changes require a new pinned upstream binary base or a full cross-build.
- Validate package archives and test transactional update + rollback before release.
- Hardware behavior cannot be proven on this VM; explicitly ask for device testing.
+15
View File
@@ -1,3 +1,18 @@
# BookSprite 📚
A personal KOReader fork for the Kobo Clara 2E, launched from NickelMenu.
All features retained; separate OTA channel, staged updates, explicit rollback,
and USB recovery. Original KOReader installation stays available.
**[Installation, recovery and release documentation](booksprite/README.md)** ·
**[USB instructions](booksprite/INSTALL.txt)**
Initial release is for device testing; hardware behavior has not yet been verified.
---
## Upstream KOReader documentation
[![KOReader](https://raw.githubusercontent.com/koreader/koreader.github.io/master/koreader-logo.png)](https://koreader.rocks)
#### KOReader is a document viewer primarily aimed at e-ink readers.
+3
View File
@@ -0,0 +1,3 @@
/build/
/dist/
__pycache__/
+68
View File
@@ -0,0 +1,68 @@
BOOKSPRITE 0.1.0 - KOBO CLARA 2E
First release / device-testing build. All KOReader features are retained;
only branding and the update/recovery path have changed. Not yet tested
on physical Kobo hardware. This is an application, not a firmware update.
USB INSTALL (NickelMenu must already be installed)
1. Exit KOReader to the Kobo home screen. Charge the Kobo first.
2. Connect USB and choose Connect on the Kobo.
3. Back up your existing .adds/koreader folder and important book sidecars
(.sdr folders) to your computer. Enable hidden files in your file manager.
4. Extract the ZIP to the ROOT of the Kobo USB drive, merging .adds.
Check that you now have:
.adds/booksprite/launch.sh
.adds/booksprite/koreader/koreader.sh
.adds/nm/booksprite
Do NOT put these files inside .kobo. Do NOT replace .adds/koreader or
your existing NickelMenu configuration. No KoboRoot.tgz is involved.
5. Safely eject. Open NickelMenu > BookSprite.
Your existing KOReader entry remains available as a fallback.
BookSprite starts with its own default settings. Your books stay in place.
Per-book sidecar files alongside books may still be shared with KOReader.
If you want your old global settings/dictionaries, ask for migration help
or copy them only while both readers are closed, keeping a USB backup.
Keep at least 1 GB free before OTA updates (more if using large dictionaries).
OTA UPDATE
Connect Wi-Fi, then open the main menu > BookSprite update > Check for BookSprite updates.
Accept the download. Once told it is ready, EXIT BookSprite completely
and launch it again from NickelMenu. The in-app Restart action alone
is not enough to run the outer updater. Do not unplug power or force a
reboot while it prepares an update. The previous application and its
settings are retained as a rollback copy. Only approved BookSprite
releases are offered; KOReader's upstream server is not used.
RECOVERY
A. If the reader is usable, exit to Nickel and choose
NickelMenu > BookSprite - roll back. It restores and launches the backup.
This swaps back to the previous application/settings snapshot.
Rollback is available only AFTER your first successful OTA install.
Book files and sidecars outside the app folder are not rolled back.
B. If it freezes, hold the power button to power off/restart the Kobo;
return to the ordinary Kobo home screen and try the rollback entry.
C. USB recovery (also works if the menu rollback cannot run):
- Connect to your computer from Kobo's home screen.
- Back up the ENTIRE .adds/booksprite folder first.
- Make a recovery folder OUTSIDE .adds/booksprite. Move these hidden
controls into it if present: .transaction, .transaction.new,
.staging, .launcher.lock, pending.tar.gz. Do not discard them:
.staging can contain a recoverable app after an interrupted update.
- Rename .adds/booksprite/koreader to koreader.failed (if present).
- If .adds/booksprite/previous/koreader exists, move it to
.adds/booksprite/koreader.
- Otherwise copy a fresh koreader folder from this ZIP into
.adds/booksprite/koreader.
- Safely eject and launch BookSprite, or use your original KOReader.
D. To remove BookSprite: back it up, then remove ONLY .adds/nm/booksprite
and .adds/booksprite. Leave NickelMenu and .adds/koreader alone.
Interrupted file swaps are normally recovered just by relaunching.
A crash after an update does not trigger an automatic rollback: use the
explicit rollback entry or USB recovery. This avoids mistaking normal
KOReader exit/restart/USB behavior for a failed release.
Source, releases and issue tracker:
https://gitea.jameshall.xyz/exe.dev/booksprite
Based on KOReader v2026.07.1; AGPLv3, with upstream license notices retained.
+86
View File
@@ -0,0 +1,86 @@
# BookSprite 📚
A small personal fork of KOReader for the Kobo Clara 2E. Version 0.1.0
keeps the reader's features and menus, changing its identity and adding a
separate, recoverable OTA channel. The file browser/menu redesign is future work.
**Status:** initial device-testing release. VM tests do not replace testing the
launcher, display, Wi-Fi, suspend/resume, USB mode and recovery on a physical Kobo.
## Installation and recovery
Read [INSTALL.txt](INSTALL.txt). Copy the USB ZIP's contents to the drive root;
it adds `.adds/booksprite` and `.adds/nm/booksprite` without changing the original
`.adds/koreader`, NickelMenu setup, or Kobo firmware. Enable hidden files when
copying. No root filesystem update or KoboRoot.tgz is involved.
Settings start separate. Book sidecars outside the app directory may be shared.
First back up the original app and important `.sdr` directories. For OTA reserve
at least 1 GB, more when app-local user content is large. A new release is prepared
in staging, then the current app is renamed to a complete previous snapshot.
Recover using the NickelMenu rollback action (which restores and launches the
previous app) or USB. The original KOReader entry
is a second fallback. No automatic crash rollback is claimed.
The stable `launch.sh` supervisor is deliberately outside the app payload; OTA
cannot replace it. Supervisor changes need a separate, reviewed USB install.
## Build
```sh
python3 booksprite/build.py
python3 -m unittest discover -s booksprite/tests -v
```
The builder downloads and SHA256-verifies the official **kobo** (not kobov5)
KOReader v2026.07.1 release, preserves its native ARM executables, libraries,
fonts, translations and license notices, then overlays the modified interpreted
Lua files and Kobo startup script. It does not claim to cross-compile native code.
`build.py` contains the pinned URL and checksum and the explicit overlay list.
Native changes require a matching new binary base or a full upstream cross-build.
Outputs in ignored `booksprite/dist/`:
- `booksprite-kobo-vVERSION-usb.zip`: first install, supervisor and NickelMenu entries.
- `booksprite-kobo-vVERSION.tar.gz`: app-only OTA, rooted at `koreader/`.
- `stable.json`: version, target, exact download URL, byte size and SHA256.
- `SHA256SUMS`, `provenance.json`: integrity and source/binary-base provenance.
Git history, upstream tag and submodule pins remain intact. Upstream sources are
at https://github.com/koreader/koreader/tree/v2026.07.1; the corresponding native
sources are pinned by that tree's `base` submodule, whose third-party definitions
pin the dependent sources. This repository contains our modifications and the
original AGPLv3 COPYING. Bundled components retain their own license notices.
## OTA and trust
The app uses its own Update menu (same menu location), never the upstream mirrors.
It reads:
`https://gitea.jameshall.xyz/exe.dev/booksprite/raw/branch/releases/stable.json`.
The repository and owning account must allow anonymous HTTPS access; no Gitea
credential is shipped to the Kobo. Both manifest and archive connections verify
TLS certificates and the Gitea hostname; redirects and arbitrary download hosts
are rejected. Downloaded bytes are bounded and checked against size and SHA256
before becoming `pending.tar.gz`. SHA256 is an integrity check, **not an independent
publisher signature**: the Gitea account/server and certificate trust store are
the update trust boundary. Keep this personal release channel under your control.
Exit BookSprite entirely and relaunch from NickelMenu to apply a staged update.
In-app Restart is upstream's internal restart, not the outer supervisor. A
rollback restores app-local settings to the saved snapshot, not external book
sidecars. The launcher rejects unsafe archive paths/types before extraction.
## Release process (only with owner approval)
1. Make changes on `main`; review upstream merges rather than blindly rebasing.
2. Update `booksprite/VERSION`, release notes and the binary base/OVERLAY if needed.
3. Run tests and build, inspect ZIP/TAR layout and ensure no personal data.
4. Commit source, tag `booksprite-vVERSION`, push source+tag to Gitea.
5. Run `python3 booksprite/publish.py` to upload versioned release assets and
publish `stable.json` on the `releases` branch **last**.
6. Check every manifest/archive URL anonymously from outside the integration.
7. On the Kobo test USB installation, an actual OTA upgrade, then rollback.
Build and publish are explicit operations, never automatic on every commit.
Keep old release assets available for USB recovery. SHA256SUMS accompanies releases.
Use `upstream` for KOReader; the VM's `origin` uses the injected Forgejo integration.
A normal external clone should use the public Gitea repository URL.
+26
View File
@@ -0,0 +1,26 @@
# BookSprite 0.1.0 — hello, little book spirit 📚
Initial **device-testing release**, based on KOReader v2026.07.1.
All reading features and existing menu structures are retained. This is not a
native-code cross-build: official, checksum-pinned Kobo binaries plus our Lua
and launcher changes.
- BookSprite name in file browser, About, version and restart/exit UI.
- Separate installation and NickelMenu entries; stock KOReader is untouched.
- Dedicated HTTPS OTA channel with CA/hostname verification and size/SHA256 checks.
- Updates prepare a fresh app tree and retain the previous app/settings snapshot.
- Journaled directory swaps, explicit NickelMenu rollback, documented USB recovery.
**First install:** download `booksprite-kobo-v0.1.0-usb.zip`, read
`BOOKSPRITE-INSTALL.txt`, then extract to the Kobo USB drive root with hidden
files included. Back up the current reader and important book sidecars first.
The `.tar.gz` is for OTA, not first installation.
**Not yet tested on physical Kobo hardware.** Launcher/transaction/recovery tests,
archive checks and verified HTTPS smoke tests run on the development VM. Please
confirm launch, reading, suspend/wake, Wi-Fi, USB mode and a future OTA/rollback
cycle on the Clara 2E before treating this as your primary reader.
The future file browser and menu redesign has deliberately not started.
Source and detailed instructions are in the `booksprite/` directory of this repo.
+52
View File
@@ -0,0 +1,52 @@
# Initial release validation — October 30, 2026
## Passed on the development VM
- 34 Python unittest cases: build/archive integration and 29 supervisor tests.
- 15 standalone Lua OTA test groups (also invoked by the Python suite).
- 17 OTA test groups with actual bundled SHA256 and live HTTPS checks.
- The same 17 groups using the packaged **ARM LuaJIT, LuaSocket, LuaSec and LFS**
under qemu-arm-static, not just host x86 Lua modules. The bundled CA certificate
store authenticated the Gitea server and its hostname.
- BusyBox ash and applet staging/update/rollback tests, including an archive with
all 1000+ official runtime files and fork overlays. Only the ARM launch script
in a temporary test copy is changed to a host no-op; production archives are
not modified by this test.
- All six journal phases and intermediate rename states; repeat recovery;
interrupted rollback does not inadvertently swap back.
- Low space, copy/promotion errors, stale/live/concurrent launcher locks,
signal forwarding and preserving upstream exit behavior.
- Path traversal, links, hardlinks, duplicate paths, malformed manifests,
truncated/oversized downloads, wrong hash and wrong target rejected.
- Snapshot rollback restores app-local settings; updates retain untracked user
data and remove obsolete tracked source files.
- Modified Lua compiles; supervisor shellcheck has no warning-level findings.
- USB ZIP does not contain .kobo, KoboRoot.tgz, or stock .adds/koreader paths.
## Still requires physical Kobo testing
- First USB install and NickelMenu launch/return.
- Reading EPUB/PDF, e-ink refresh, touch, light, suspend/wake and battery behavior.
- Wi-Fi manifest and full archive download on the device.
- USB mass-storage mode from within BookSprite.
- Actual on-device OTA and explicit rollback after a later release.
The initial release is deliberately labeled a device-testing build. It is not
claimed to be hardware-validated or guaranteed immune to power-loss corruption.
Keep the original KOReader and a computer-side backup available.
## Run tests
Build with `python3 booksprite/build.py`, then:
```
python3 -m unittest discover -s booksprite/tests -v
luajit spec/booksprite_otamanager_test.lua
```
Builder: Python 3 standard library and git. Tests additionally need LuaJIT,
LuaFileSystem, LuaSocket and LuaSec. BusyBox is recommended and selected when
available. Native/runtime/network smoke checks are additional to offline tests;
see the environment variables at the top of the standalone Lua test.
No credentials or user books/settings are included in the test or release data.
+1
View File
@@ -0,0 +1 @@
0.1.0
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Reproducible Lua-overlay build using verified official KOReader ARM binaries."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import stat
import subprocess
import tarfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parent.parent
HERE = ROOT / 'booksprite'
UPSTREAM_TAG = 'v2026.07.1'
UPSTREAM_ZIP = 'https://github.com/koreader/koreader/releases/download/v2026.07.1/koreader-kobo-v2026.07.1.zip'
UPSTREAM_SHA256 = '0f36a62ce73b12516f969e4ad7862cc06920afb03c7bd4db29a0d990bdd84b2f'
RELEASE_BASE = 'https://gitea.jameshall.xyz/exe.dev/booksprite/releases/download'
OVERLAY = [
'frontend/ui/otamanager.lua',
'frontend/ui/elements/common_info_menu_table.lua',
'frontend/ui/elements/common_exit_menu_table.lua',
'frontend/apps/filemanager/filemanager.lua',
]
EPOCH = 1793318400 # 2026-10-30 00:00 UTC, fixed for deterministic archive metadata.
def sha256(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def build(source_zip=None):
version = (HERE / 'VERSION').read_text().strip()
if not __import__('re').fullmatch(r'\d+\.\d+\.\d+', version):
raise ValueError('VERSION must be major.minor.patch')
work = HERE / 'build'
out = HERE / 'dist'
work.mkdir(exist_ok=True)
out.mkdir(exist_ok=True)
source_zip = Path(source_zip) if source_zip else work / f'upstream-{UPSTREAM_TAG}.zip'
if not source_zip.exists():
urllib.request.urlretrieve(UPSTREAM_ZIP, source_zip)
if sha256(source_zip) != UPSTREAM_SHA256:
raise ValueError('Upstream ZIP checksum mismatch')
stage = work / 'usb'
if stage.exists():
shutil.rmtree(stage)
app = stage / '.adds/booksprite/koreader'
app.mkdir(parents=True)
with zipfile.ZipFile(source_zip) as z:
for info in z.infolist():
if not info.filename.startswith('koreader/') or info.is_dir():
continue
rel = Path(info.filename).relative_to('koreader')
if '..' in rel.parts or rel.is_absolute():
raise ValueError('Unsafe upstream ZIP')
dest = app / rel
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(z.read(info))
os.chmod(dest, (info.external_attr >> 16) & 0o777 or 0o644)
for rel in OVERLAY:
shutil.copyfile(ROOT / rel, app / rel)
shutil.copyfile(ROOT / 'platform/kobo/koreader.sh', app / 'koreader.sh')
os.chmod(app / 'koreader.sh', 0o755)
(app / 'booksprite-version').write_text(version + '\n')
shutil.copyfile(HERE / 'README.md', app / 'BOOKSPRITE.md')
shutil.copyfile(HERE / 'INSTALL.txt', app / 'BOOKSPRITE-INSTALL.txt')
# No upstream updater metadata or unexpected leftover update is ever shipped.
shutil.rmtree(app / 'ota')
(app / 'ota').mkdir()
receipt = dict(name='BookSprite', version=version, upstream_tag=UPSTREAM_TAG,
upstream_zip=UPSTREAM_ZIP, upstream_sha256=UPSTREAM_SHA256,
upstream_commit=subprocess.check_output(['git', 'rev-list', '-n', '1', UPSTREAM_TAG], cwd=ROOT, text=True).strip(),
source_commit=subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),
source_url='https://gitea.jameshall.xyz/exe.dev/booksprite', target='kobo')
(app / 'booksprite-build.json').write_text(json.dumps(receipt, indent=2) + '\n')
tracked = sorted([str(p.relative_to(app)) for p in app.rglob('*') if p.is_file()] + ['booksprite-files.txt'])
(app / 'booksprite-files.txt').write_text('\n'.join(tracked) + '\n')
launcher = stage / '.adds/booksprite/launch.sh'
shutil.copyfile(HERE / 'launch.sh', launcher)
os.chmod(launcher, 0o755)
nm = stage / '.adds/nm/booksprite'
nm.parent.mkdir(parents=True)
shutil.copyfile(HERE / 'nickelmenu.conf', nm)
shutil.copyfile(HERE / 'INSTALL.txt', stage / 'BOOKSPRITE-INSTALL.txt')
archive = out / f'booksprite-kobo-v{version}.tar.gz'
# Stable gzip metadata + tar ordering and numeric owners.
import gzip
with open(archive, 'wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=EPOCH) as gz:
with tarfile.open(fileobj=gz, mode='w', format=tarfile.USTAR_FORMAT) as tar:
for path in sorted(app.rglob('*')):
info = tar.gettarinfo(str(path), 'koreader/' + str(path.relative_to(app)))
info.uid = info.gid = 0
info.uname = info.gname = ''
info.mtime = EPOCH
if path.is_file():
with path.open('rb') as f:
tar.addfile(info, f)
else:
tar.addfile(info)
usb = out / f'booksprite-kobo-v{version}-usb.zip'
import datetime
date_time = datetime.datetime.fromtimestamp(EPOCH, datetime.timezone.utc).timetuple()[:6]
with zipfile.ZipFile(usb, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as z:
for path in sorted(stage.rglob('*')):
if path.is_file():
info = zipfile.ZipInfo(str(path.relative_to(stage)), date_time)
info.external_attr = (stat.S_IFREG | stat.S_IMODE(path.stat().st_mode)) << 16
info.compress_type = zipfile.ZIP_DEFLATED
z.writestr(info, path.read_bytes())
manifest = dict(version=version, target='kobo', url=f'{RELEASE_BASE}/booksprite-v{version}/{archive.name}',
sha256=sha256(archive), size=archive.stat().st_size)
(out / 'stable.json').write_text(json.dumps(manifest, indent=2) + '\n')
sums = ''.join(f'{sha256(p)} {p.name}\n' for p in [usb, archive])
(out / 'SHA256SUMS').write_text(sums)
(out / 'provenance.json').write_text(json.dumps(receipt, indent=2) + '\n')
print(json.dumps(dict(usb=str(usb), ota=str(archive), manifest=manifest), indent=2))
return usb, archive
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--upstream-zip', help='Use a local, checksum-verified upstream ZIP')
build(parser.parse_args().upstream_zip)
+408
View File
@@ -0,0 +1,408 @@
#!/bin/sh
# Stable BookSprite supervisor. Never replace this file in an OTA archive.
# BusyBox ash / FAT compatible; no firmware writes and no stock KOReader access.
#
# Release contract:
# pending.tar.gz contains ONLY koreader/, regular files and directories.
# koreader/booksprite-files.txt lists EVERY shipped regular file, one relative
# path per line (including itself), sorted, without a "koreader/" prefix.
# No links, control characters, dot components, or duplicate archive members.
# Update policy: fresh payload + old untracked files + explicit mutable data.
# Modified shipped code is replaced; removed shipped files are not resurrected.
# previous/koreader is a complete pre-update snapshot, including runtime state.
# --rollback swaps those complete snapshots, not just binaries.
#
# BOOKSPRITE_HOME is a test-only override; production always uses the default.
umask 022
LC_ALL=C
export LC_ALL
HOME_DIR=${BOOKSPRITE_HOME:-/mnt/onboard/.adds/booksprite}
case "$HOME_DIR" in
/*/booksprite) ;;
*) echo "BookSprite: unsafe installation directory" >&2; exit 1 ;;
esac
if [ -L "$HOME_DIR" ] || ! HOME_DIR=$(CDPATH='' cd "$HOME_DIR" && pwd -P); then
echo "BookSprite: installation directory is missing or linked" >&2
exit 1
fi
case "$HOME_DIR" in
/*/booksprite) ;;
*) echo "BookSprite: unsafe resolved installation directory" >&2; exit 1 ;;
esac
# Upstream moves koreader.sh to /tmp for USBMS. This supervisor must likewise
# have neither an open script/log descriptor nor a cwd on onboard while it waits.
if [ "${BOOKSPRITE_RELOCATED:-}" != "$HOME_DIR" ]; then
TEMP_SCRIPT=$(mktemp /tmp/booksprite-launch.XXXXXX) || exit 1
if ! cp "$0" "$TEMP_SCRIPT"; then
rm -f "$TEMP_SCRIPT"
exit 1
fi
BOOKSPRITE_HOME=$HOME_DIR BOOKSPRITE_RELOCATED=$HOME_DIR \
BOOKSPRITE_TEMP_SCRIPT=$TEMP_SCRIPT \
exec sh "$TEMP_SCRIPT" "$@"
exit 1
fi
cd / || exit 1
CURRENT=$HOME_DIR/koreader
PREVIOUS=$HOME_DIR/previous
STAGE=$HOME_DIR/.staging
JOURNAL=$HOME_DIR/.transaction
LOCK=$HOME_DIR/.launcher.lock
LOCKED=false
CHILD=
RECOVERED_ROLLBACK=false
log() {
printf '%s\n' "BookSprite: $*" >&2
if [ ! -L "$HOME_DIR/launcher.log" ]; then
printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >>"$HOME_DIR/launcher.log"
fi
}
die() { log "$*"; exit 1; }
cleanup() {
if [ "$LOCKED" = true ]; then
rm -f "$LOCK/owner.$$"
rm -f "$LOCK/pid"
rmdir "$LOCK" 2>/dev/null || :
fi
case "${BOOKSPRITE_TEMP_SCRIPT:-}" in
/tmp/booksprite-launch.*) rm -f "$BOOKSPRITE_TEMP_SCRIPT" ;;
esac
}
interrupted() {
if [ -n "$CHILD" ]; then
kill -TERM "$CHILD" 2>/dev/null || :
wait "$CHILD" 2>/dev/null || :
fi
exit 143
}
trap cleanup EXIT
trap interrupted HUP INT TERM
# Fail closed on unexpected links at all paths which may be replaced/deleted.
for path in "$CURRENT" "$PREVIOUS" "$PREVIOUS/koreader" "$STAGE" \
"$JOURNAL" "$JOURNAL.new" "$LOCK" "$HOME_DIR/pending.tar.gz" \
"$HOME_DIR/rejected.tar.gz" "$HOME_DIR/launcher.log"; do
[ ! -L "$path" ] || die "Refusing linked control path: $path"
done
read_owner() {
OWNER=
for marker in "$LOCK"/owner.*; do
[ -f "$marker" ] || continue
candidate=${marker##*.}
case "$candidate" in ''|*[!0-9]*) die "Invalid lock owner" ;; esac
[ -z "$OWNER" ] || die "Multiple lock owners; recover over USB"
OWNER=$candidate
done
# Accept the plain PID layout as well, including stale pre-marker locks.
[ -n "$OWNER" ] || OWNER=$(cat "$LOCK/pid" 2>/dev/null)
}
if ! mkdir "$LOCK" 2>/dev/null; then
[ -d "$LOCK" ] || die "Invalid launcher lock"
# Allow an incumbent time to publish its PID after mkdir.
[ -f "$LOCK/pid" ] || sleep 1
read_owner
case "$OWNER" in
''|*[!0-9]*) OWNER= ;;
*) if kill -0 "$OWNER" 2>/dev/null; then
log "Already running (PID $OWNER)"
exit 75
fi ;;
esac
# rmdir deliberately refuses an unexpected/nonempty lock directory.
[ ! -L "$LOCK/pid" ] || die "Invalid lock PID"
# Remove only the observed owner's marker. If two launchers race to reclaim
# a stale lock, the loser cannot delete the winner's differently named live
# owner marker; its rmdir fails instead of admitting a second reader.
[ -z "$OWNER" ] || rm -f "$LOCK/owner.$OWNER" || die "Cannot clear stale owner"
PID_NOW=$(cat "$LOCK/pid" 2>/dev/null)
if [ "$PID_NOW" = "$OWNER" ] || [ -z "$PID_NOW" ]; then
rm -f "$LOCK/pid" || die "Cannot clear stale lock"
fi
rmdir "$LOCK" 2>/dev/null || die "Cannot clear stale lock directory"
mkdir "$LOCK" 2>/dev/null || die "Another launcher acquired the lock"
log "Recovered stale launcher lock"
fi
: >"$LOCK/owner.$$" || die "Cannot write launcher owner"
printf '%s\n' "$$" >"$LOCK/pid" || die "Cannot write launcher lock"
LOCKED=true
remove_stage() {
[ "$STAGE" = "$HOME_DIR/.staging" ] && [ ! -L "$STAGE" ] ||
die "Unsafe staging path"
rm -rf "$STAGE"
}
write_phase() {
printf '%s\n' "$1" >"$JOURNAL.new" || die "Cannot write transaction"
sync
mv "$JOURNAL.new" "$JOURNAL" || die "Cannot publish transaction"
sync
}
has_reader() { [ -d "$1" ] && [ ! -L "$1" ] && [ -f "$1/koreader.sh" ]; }
# Write-ahead phases plus rename-state checks make every individual move
# repeatable after power loss, even between a rename and the next phase write.
recover() {
[ -f "$JOURNAL" ] || return 0
PHASE=$(cat "$JOURNAL") || die "Cannot read transaction"
log "Recovering transaction: $PHASE"
case "$PHASE" in
update-save|update-promote|update-finish|rollback-save|rollback-restore|rollback-finish) ;;
*) die "Unknown transaction; recover installation over USB" ;;
esac
case "$PHASE" in rollback-*) RECOVERED_ROLLBACK=true ;; esac
if [ "$PHASE" = update-save ]; then
has_reader "$STAGE/koreader" || die "Staged update is incomplete"
if has_reader "$CURRENT"; then
[ ! -L "$PREVIOUS" ] || die "Linked backup directory"
# Only the oldest backup is discarded; the running tree is intact.
if [ -e "$PREVIOUS" ]; then
[ -d "$PREVIOUS" ] || die "Invalid backup directory"
rm -rf "$PREVIOUS"
fi
mkdir "$PREVIOUS" || die "Cannot create backup directory"
mv "$CURRENT" "$PREVIOUS/koreader" || die "Cannot save current installation"
sync
else
[ ! -e "$CURRENT" ] && has_reader "$PREVIOUS/koreader" ||
die "Cannot determine update backup state"
fi
write_phase update-promote
PHASE=update-promote
fi
if [ "$PHASE" = update-promote ]; then
has_reader "$PREVIOUS/koreader" || die "Update backup is missing"
if [ -d "$STAGE/koreader" ]; then
[ ! -e "$CURRENT" ] || die "Update destination already exists"
mv "$STAGE/koreader" "$CURRENT" || die "Cannot promote update"
sync
fi
has_reader "$CURRENT" || die "Promoted installation is incomplete"
write_phase update-finish
PHASE=update-finish
fi
if [ "$PHASE" = rollback-save ]; then
has_reader "$PREVIOUS/koreader" || die "Rollback backup is missing"
if has_reader "$CURRENT"; then
[ ! -e "$STAGE/koreader" ] || die "Rollback staging collision"
mv "$CURRENT" "$STAGE/koreader" || die "Cannot stage current installation"
sync
else
[ ! -e "$CURRENT" ] && has_reader "$STAGE/koreader" ||
die "Cannot determine rollback state"
fi
write_phase rollback-restore
PHASE=rollback-restore
fi
if [ "$PHASE" = rollback-restore ]; then
has_reader "$STAGE/koreader" || die "Rollback staging tree is missing"
if [ -d "$PREVIOUS/koreader" ]; then
[ ! -e "$CURRENT" ] || die "Rollback destination already exists"
mv "$PREVIOUS/koreader" "$CURRENT" || die "Cannot restore backup"
sync
fi
has_reader "$CURRENT" || die "Restored installation is incomplete"
write_phase rollback-finish
PHASE=rollback-finish
fi
if [ "$PHASE" = rollback-finish ]; then
if [ -d "$STAGE/koreader" ]; then
[ ! -e "$PREVIOUS/koreader" ] || die "Rollback backup collision"
mv "$STAGE/koreader" "$PREVIOUS/koreader" || die "Cannot retain displaced installation"
sync
fi
has_reader "$CURRENT" && has_reader "$PREVIOUS/koreader" ||
die "Rollback snapshots are incomplete"
fi
has_reader "$CURRENT" || die "Transaction has no runnable installation"
remove_stage || die "Cannot clean transaction staging"
rm -f "$JOURNAL" "$JOURNAL.new" || die "Cannot finish transaction"
sync
log "Transaction complete"
}
# Strict ASCII release paths; spaces are supported, shell metacharacters and
# ambiguous tar escaping are not. Runtime filenames need not follow this rule.
valid_paths() {
awk '
!/^[A-Za-z0-9_.\/+@=,() -]+$/ { exit 1 }
/^\// || /\/\// || /(^|\/)\.\.?($|\/)/ { exit 1 }
{ if (length($0) == 0) exit 1 }
' "$1"
}
valid_manifest() {
[ -f "$1" ] && [ ! -L "$1" ] && [ -s "$1" ] || return 1
valid_paths "$1" || return 1
# Manifests describe files, never directories. Require the shipped sentinel.
awk '/\/$/ { exit 1 }' "$1" || return 1
grep -qxF booksprite-files.txt "$1" || return 1
sort -u "$1" >"$STAGE/manifest.sorted" || return 1
cmp -s "$1" "$STAGE/manifest.sorted"
}
reject_update() {
log "Update not installed: $* (current and backup unchanged)"
if [ -f "$STAGE/payload.tar.gz" ]; then
mv "$STAGE/payload.tar.gz" "$HOME_DIR/rejected.tar.gz" ||
die "Cannot retain rejected archive"
fi
remove_stage || die "Cannot clean rejected staging"
}
stage_update() {
mkdir "$STAGE" || { log "Cannot create staging directory"; return; }
if ! mv "$HOME_DIR/pending.tar.gz" "$STAGE/payload.tar.gz"; then
reject_update "cannot claim pending archive"; return
fi
ARCHIVE=$STAGE/payload.tar.gz
# Validate both names and types BEFORE extraction. The official Kobo release
# contains no links; rejecting all links avoids tar traversal through parents.
if ! tar -tzf "$ARCHIVE" >"$STAGE/members" 2>"$STAGE/tar-error" ||
! valid_paths "$STAGE/members" ||
! awk '$0 != "koreader/" && $0 !~ /^koreader\/.+/ { exit 1 }' "$STAGE/members" ||
! tar -tvzf "$ARCHIVE" >"$STAGE/types" 2>>"$STAGE/tar-error" ||
! awk 'substr($0,1,1) != "-" && substr($0,1,1) != "d" { exit 1 }' "$STAGE/types"; then
reject_update "unsafe or corrupt archive"; return
fi
sort "$STAGE/members" | uniq -d >"$STAGE/duplicates"
if [ -s "$STAGE/duplicates" ] || [ ! -s "$STAGE/members" ]; then
reject_update "empty archive or duplicate members"; return
fi
# Demand at least 512 MiB free, or the full new payload + current tree +
# 64 MiB headroom, whichever is greater. The current tree is a conservative
# upper bound for mutable data copied into the new payload.
AVAILABLE=$(df -Pk "$HOME_DIR" | awk 'END { print $(NF-2) }')
OLD_SIZE=$(du -sk "$CURRENT" 2>/dev/null | awk '{print $1}')
NEEDED=$(awk -v old="$OLD_SIZE" '
{ if ($3 !~ /^[0-9]+$/) bad=1; bytes += $3 }
END {
n = int(bytes / 1024) + 1 + old + 65536;
if (n < 524288) n = 524288;
if (bad) print "invalid"; else printf "%.0f\n", n;
}' "$STAGE/types")
for value in "$AVAILABLE" "$OLD_SIZE" "$NEEDED"; do
case "$value" in
''|*[!0-9]*) reject_update "cannot determine free space"; return ;;
esac
done
if [ "$AVAILABLE" -lt "$NEEDED" ]; then
reject_update "insufficient free space (need ${NEEDED} KiB, have ${AVAILABLE} KiB)"; return
fi
if ! tar -xzf "$ARCHIVE" -C "$STAGE" 2>>"$STAGE/tar-error"; then
reject_update "extraction failed"; return
fi
if ! has_reader "$STAGE/koreader" ||
[ ! -f "$STAGE/koreader/reader.lua" ] ||
! valid_manifest "$STAGE/koreader/booksprite-files.txt" ||
! valid_manifest "$CURRENT/booksprite-files.txt"; then
reject_update "missing launcher/reader or invalid release manifest"; return
fi
# A manifest cannot claim files outside the payload or omit shipped files.
if ! (CDPATH='' cd "$STAGE/koreader" && find . -type f) >"$STAGE/new-files.raw" ||
! sed 's|^\./||' "$STAGE/new-files.raw" >"$STAGE/new-files" ||
! sort "$STAGE/new-files" >"$STAGE/actual"; then
reject_update "cannot enumerate payload"; return
fi
if ! cmp -s "$STAGE/koreader/booksprite-files.txt" "$STAGE/actual"; then
reject_update "release manifest does not match payload"; return
fi
# FAT has no symlinks. Refuse links on test/Unix installations too, rather
# than following a user-created link outside either installation.
if ! find "$CURRENT" -type l >"$STAGE/links" || [ -s "$STAGE/links" ]; then
reject_update "current installation contains links"; return
fi
if ! (CDPATH='' cd "$CURRENT" && find . -type f) >"$STAGE/old-files.raw" ||
! sed 's|^\./||' "$STAGE/old-files.raw" >"$STAGE/old-files"; then
reject_update "cannot enumerate runtime data"; return
fi
if ! awk 'FILENAME != ARGV[3] { tracked[$0]=1; next } !($0 in tracked)' \
"$CURRENT/booksprite-files.txt" "$STAGE/koreader/booksprite-files.txt" \
"$STAGE/old-files" >"$STAGE/copy-files"; then
reject_update "cannot identify mutable data"; return
fi
# Explicit mutable paths may intentionally override shipped defaults. User
# plugins, fonts, defaults.custom.lua, databases etc. are otherwise untracked.
if ! awk '/^(settings\/|history\/|cache\/|clipboard\/|patches\/|data\/dict\/|data\/tessdata\/)/ ||
/^(settings\.reader\.lua|settings\.reader\.lua\.old)$/' \
"$STAGE/old-files" >>"$STAGE/copy-files" ||
! sort -u "$STAGE/copy-files" >"$STAGE/copy.sorted"; then
reject_update "cannot identify runtime overlays"; return
fi
COPY_OK=true
while IFS= read -r file; do
# A path is from find, not the archive. Prefix absolute paths and quote
# every operation; never evaluate filenames or copy directory links.
if [ -d "$STAGE/koreader/$file" ] ||
! mkdir -p "$(dirname "$STAGE/koreader/$file")" ||
! cp -p "$CURRENT/$file" "$STAGE/koreader/$file"; then
COPY_OK=false
break
fi
done <"$STAGE/copy.sorted"
if [ "$COPY_OK" != true ]; then
reject_update "cannot preserve mutable data"; return
fi
sync
write_phase update-save
recover
}
recover
# No journal means an interruption happened before commit. Requeue the claimed
# archive, but never replace a newer USB-uploaded pending archive.
if [ -e "$STAGE" ]; then
[ -d "$STAGE" ] || die "Invalid staging directory"
if [ -f "$STAGE/payload.tar.gz" ]; then
if [ -e "$HOME_DIR/pending.tar.gz" ]; then
mv "$STAGE/payload.tar.gz" "$HOME_DIR/rejected.tar.gz" ||
die "Cannot retain abandoned archive"
else
mv "$STAGE/payload.tar.gz" "$HOME_DIR/pending.tar.gz" ||
die "Cannot requeue abandoned archive"
fi
fi
remove_stage || die "Cannot clean abandoned staging"
fi
rm -f "$JOURNAL.new"
if [ "${1:-}" = --rollback ]; then
shift
if [ "$RECOVERED_ROLLBACK" = true ]; then
# A repeated NickelMenu action completes the interrupted swap, rather
# than swapping straight back to the version the user wanted to leave.
:
elif ! has_reader "$PREVIOUS/koreader"; then
die "No previous installation; restore over USB"
elif [ ! -e "$CURRENT" ]; then
# Recovery from a manually removed/broken current directory.
mv "$PREVIOUS/koreader" "$CURRENT" || die "Cannot restore previous installation"
sync
else
has_reader "$CURRENT" || die "Current directory is incomplete; recover over USB"
mkdir "$STAGE" || die "Cannot create rollback staging"
write_phase rollback-save
recover
fi
log "Manual rollback complete; pending update was not applied"
else
has_reader "$CURRENT" || die "Installation missing; use --rollback or restore over USB"
if [ -f "$HOME_DIR/pending.tar.gz" ]; then
stage_update
fi
fi
has_reader "$CURRENT" || die "No runnable installation"
export KOREADER_DIR="$CURRENT"
log "Starting $KOREADER_DIR"
# Upstream owns 85 (restart), 86 (USBMS), 88 (halt), crash retry, framebuffer
# restoration, and return to Nickel. Do not reinterpret them as update failure.
sh "$CURRENT/koreader.sh" "$@" &
CHILD=$!
wait "$CHILD"
STATUS=$?
CHILD=
log "KOReader exited with status $STATUS; no automatic rollback"
exit "$STATUS"
+3
View File
@@ -0,0 +1,3 @@
# BookSprite is separate from your original KOReader installation.
menu_item :main :BookSprite :cmd_spawn :quiet:exec /bin/sh /mnt/onboard/.adds/booksprite/launch.sh
menu_item :main :BookSprite - roll back :cmd_spawn :quiet:exec /bin/sh /mnt/onboard/.adds/booksprite/launch.sh --rollback
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Explicitly publish a tested local build to the configured Forgejo integration."""
import base64
import hashlib
import json
from pathlib import Path
import subprocess
import urllib.error
import urllib.request
HERE = Path(__file__).resolve().parent
API = 'https://forgejo.int.exe.xyz/api/v1/repos/exe.dev/booksprite'
PUBLIC = 'https://gitea.jameshall.xyz/exe.dev/booksprite'
def request(path, method='GET', data=None):
req = urllib.request.Request(API + path, method=method)
if data is not None:
req.add_header('Content-Type', 'application/json')
req.data = json.dumps(data).encode()
with urllib.request.urlopen(req, timeout=60) as response:
return json.load(response)
def main():
dist = HERE / 'dist'
manifest = json.loads((dist / 'stable.json').read_text())
version = manifest['version']
tag = 'booksprite-v' + version
if subprocess.check_output(['git', 'status', '--porcelain'], cwd=HERE, text=True).strip():
raise SystemExit('Commit all source changes before publishing.')
head = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=HERE, text=True).strip()
receipt = json.loads((dist / 'provenance.json').read_text())
if receipt['source_commit'] != head:
raise SystemExit('Build provenance does not match HEAD. Rebuild after committing.')
if request('/branches/main')['commit']['id'] != head:
raise SystemExit('Push HEAD to main before publishing.')
archive = dist / manifest['url'].rsplit('/', 1)[1]
if archive.stat().st_size != manifest['size'] or hashlib.file_digest(archive.open('rb'), 'sha256').hexdigest() != manifest['sha256']:
raise SystemExit('Archive does not match stable.json.')
try:
release = request('/releases/tags/' + tag)
except urllib.error.HTTPError as error:
if error.code != 404:
raise
release = request('/releases', 'POST', dict(tag_name=tag, target_commitish=head,
name='BookSprite ' + version,
body=(HERE / 'RELEASE_NOTES.md').read_text(),
draft=False, prerelease=True))
assets = {a['name']: a for a in request(f"/releases/{release['id']}/assets")}
for path in [archive, dist / f'booksprite-kobo-v{version}-usb.zip', dist / 'SHA256SUMS', dist / 'provenance.json']:
if path.name in assets:
with urllib.request.urlopen(API.rsplit('/api/v1/', 1)[0] + '/exe.dev/booksprite/releases/download/' + tag + '/' + path.name, timeout=90) as response:
h = hashlib.sha256()
for chunk in iter(lambda: response.read(1024 * 1024), b''):
h.update(chunk)
with path.open('rb') as local:
expected = hashlib.file_digest(local, 'sha256').hexdigest()
if h.hexdigest() != expected:
raise SystemExit('Existing immutable asset differs: ' + path.name + '. Bump VERSION instead of overwriting a release.')
print('Verified existing immutable asset:', path.name)
continue
subprocess.run(['curl', '--fail-with-body', '--silent', '--show-error', '-X', 'POST',
API + f"/releases/{release['id']}/assets?name={path.name}",
'-F', f'attachment=@{path}', '-o', '/tmp/booksprite-upload-result.json'], check=True)
print('Uploaded', path.name)
# An anonymous check is essential: device users have no integration credentials.
try:
with urllib.request.urlopen(manifest['url'], timeout=90) as response:
h = hashlib.sha256()
size = 0
for chunk in iter(lambda: response.read(1024 * 1024), b''):
h.update(chunk)
size += len(chunk)
if h.hexdigest() != manifest['sha256'] or size != manifest['size']:
raise ValueError('Anonymous asset checksum mismatch')
except (urllib.error.HTTPError, urllib.error.URLError) as error:
raise SystemExit('Assets uploaded, but anonymous downloads are blocked. '
'Check repository AND account visibility, then rerun. OTA channel was NOT changed. ' + str(error))
try:
request('/branches/releases')
except urllib.error.HTTPError as error:
if error.code != 404:
raise
request('/branches', 'POST', dict(new_branch_name='releases', old_branch_name='main'))
payload = dict(branch='releases', message='Publish BookSprite ' + version + ' OTA channel',
content=base64.b64encode((dist / 'stable.json').read_bytes()).decode())
try:
existing = request('/contents/stable.json?ref=releases')
payload['sha'] = existing['sha']
method = 'PUT'
except urllib.error.HTTPError as error:
if error.code != 404:
raise
method = 'POST'
request('/contents/stable.json', method, payload)
with urllib.request.urlopen(PUBLIC + '/raw/branch/releases/stable.json', timeout=30) as response:
if json.load(response) != manifest:
raise SystemExit('Published manifest does not match build!')
print('Published and anonymously verified:', PUBLIC + '/releases/tag/' + tag)
if __name__ == '__main__':
main()
+70
View File
@@ -0,0 +1,70 @@
import hashlib
import importlib.util
import json
from pathlib import Path
import subprocess
import tarfile
import unittest
import zipfile
ROOT = Path(__file__).resolve().parents[2]
HERE = ROOT / 'booksprite'
spec = importlib.util.spec_from_file_location('booksprite_build', HERE / 'build.py')
build = importlib.util.module_from_spec(spec)
spec.loader.exec_module(build)
class BuildTests(unittest.TestCase):
def test_overlay_covers_changed_runtime_sources(self):
changed = subprocess.check_output(['git', 'diff', '--name-only', build.UPSTREAM_TAG], cwd=ROOT, text=True).splitlines()
runtime = {f for f in changed if f.startswith('frontend/')}
self.assertEqual(runtime, set(build.OVERLAY))
def test_ota_logic(self):
subprocess.run(['luajit', 'spec/booksprite_otamanager_test.lua'], cwd=ROOT, check=True)
def test_lua_compiles(self):
for file in build.OVERLAY:
subprocess.run(['luajit', '-b', str(ROOT / file), '/dev/null'], check=True)
def test_supervisor_and_upstream_shell_parse(self):
for file in [HERE / 'launch.sh', ROOT / 'platform/kobo/koreader.sh']:
subprocess.run(['/bin/sh', '-n', str(file)], check=True)
def test_packages(self):
dist = HERE / 'dist'
if not (dist / 'stable.json').exists():
self.skipTest('Run build.py first for package integration assertions')
manifest = json.loads((dist / 'stable.json').read_text())
version = (HERE / 'VERSION').read_text().strip()
self.assertEqual(manifest['version'], version)
archive = dist / manifest['url'].rsplit('/', 1)[1]
self.assertEqual(build.sha256(archive), manifest['sha256'])
self.assertEqual(archive.stat().st_size, manifest['size'])
with tarfile.open(archive) as tar:
names = tar.getnames()
for member in tar.getmembers():
self.assertTrue(member.name.startswith('koreader/'))
self.assertTrue(member.isfile() or member.isdir())
self.assertNotIn('..', Path(member.name).parts)
tracked = tar.extractfile('koreader/booksprite-files.txt').read().decode().splitlines()
files = sorted(m.name.removeprefix('koreader/') for m in tar.getmembers() if m.isfile())
self.assertEqual(sorted(tracked), files)
self.assertIn('koreader/libs/libwrap-mupdf.so', names)
self.assertEqual(tar.extractfile('koreader/booksprite-version').read().decode().strip(), version)
for rel in build.OVERLAY:
self.assertEqual(tar.extractfile('koreader/' + rel).read(), (ROOT / rel).read_bytes())
self.assertNotIn('koreader/ota/package.index', names)
with zipfile.ZipFile(dist / f'booksprite-kobo-v{version}-usb.zip') as z:
names = z.namelist()
self.assertIn('.adds/booksprite/launch.sh', names)
self.assertIn('.adds/nm/booksprite', names)
self.assertIn('.adds/booksprite/koreader/koreader.sh', names)
self.assertFalse(any(n.startswith('.adds/koreader/') or n.startswith('.kobo/') for n in names))
self.assertFalse(any(n.endswith('settings.reader.lua') for n in names))
self.assertTrue(z.getinfo('.adds/booksprite/koreader/koreader.sh').external_attr >> 16 & 0o111)
self.assertTrue(z.getinfo('.adds/booksprite/launch.sh').external_attr >> 16 & 0o111)
if __name__ == '__main__':
unittest.main()
+581
View File
@@ -0,0 +1,581 @@
"""Host-side supervisor tests. No Kobo binaries, root, network or firmware writes.
Run: python3 -m unittest discover -s booksprite/tests -p test_launcher.py -v
Also exercise BusyBox: BOOKSPRITE_TEST_SHELL='busybox ash' python3 -m unittest ...
"""
import io
import os
from pathlib import Path
import shlex
import shutil
import signal
import subprocess
import tarfile
import tempfile
import time
import unittest
LAUNCHER = Path(__file__).resolve().parents[1] / "launch.sh"
BUSYBOX = shutil.which("busybox")
SHELL = shlex.split(os.environ.get(
"BOOKSPRITE_TEST_SHELL", "busybox ash" if BUSYBOX else "/bin/sh"
))
READER = """#!/bin/sh
printf '%s\\n' "$KOREADER_DIR" >"$BOOKSPRITE_HOME/observed-dir"
pwd >"$BOOKSPRITE_HOME/observed-cwd"
printf '%s\\n' "$@" >"$BOOKSPRITE_HOME/observed-args"
cat "$KOREADER_DIR/version" >"$BOOKSPRITE_HOME/launched-version"
if [ "${BOOKSPRITE_TEST_WAIT:-}" = yes ]; then
echo ready >"$BOOKSPRITE_HOME/ready"
while [ ! -f "$BOOKSPRITE_HOME/continue" ]; do sleep 0.05; done
fi
exit "${BOOKSPRITE_TEST_STATUS:-0}"
"""
class LauncherTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="booksprite-test-")
self.root = Path(self.temp.name)
self.home = self.root / "booksprite"
self.home.mkdir()
shutil.copy2(LAUNCHER, self.home / "launch.sh")
self.current = self.home / "koreader"
self.previous = self.home / "previous" / "koreader"
self.stock = self.root / "koreader"
self.stock.mkdir()
(self.stock / "untouched").write_text("stock")
self.make_tree(self.current, "old", {"removed.lua": "old tracked"})
self.env = dict(os.environ, BOOKSPRITE_HOME=str(self.home))
self.shell = SHELL
# Local sync is sufficient for functional tests and avoids flushing the
# entire host for every write-ahead phase. Production uses real sync.
self.bin = self.root / "bin"
self.bin.mkdir()
if BUSYBOX:
# Use the actual BusyBox archive/listing/path tools, not just ash
# with GNU tar. This catches differences in tar's verbose output.
for applet in (
"tar", "awk", "sort", "uniq", "cmp", "du", "df", "find", "sed",
"grep", "mkdir", "rm", "rmdir", "cp", "mv", "mktemp", "date",
"cat", "dirname", "sh", "sleep",
):
(self.bin / applet).symlink_to(BUSYBOX)
self.fake_command("sync", "exit 0\n")
self.env["PATH"] = str(self.bin) + ":" + os.environ["PATH"]
def tearDown(self):
self.assertEqual((self.stock / "untouched").read_text(), "stock")
self.assertEqual(list(self.stock.iterdir()), [self.stock / "untouched"])
self.temp.cleanup()
def fake_command(self, name, script):
path = self.bin / name
if path.is_symlink():
path.unlink()
path.write_text("#!/bin/sh\n" + script)
path.chmod(0o755)
def make_tree(self, path, version, extra=None):
path.mkdir(parents=True, exist_ok=True)
files = {
"koreader.sh": READER,
"reader.lua": "-- reader",
"version": version,
"frontend/official.lua": version,
"plugins/official.koplugin/main.lua": version,
}
files.update(extra or {})
for name, text in files.items():
dest = path / name
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(text)
(path / "booksprite-files.txt").write_text(
"".join(name + "\n" for name in sorted([*files, "booksprite-files.txt"]))
)
return path
def pending(self, version="new", extra=None):
payload = self.root / ("payload-" + version)
self.make_tree(payload, version, extra)
with tarfile.open(self.home / "pending.tar.gz", "w:gz", format=tarfile.USTAR_FORMAT) as tar:
tar.add(payload, arcname="koreader")
return payload
def run_launcher(self, *args, status=None):
env = self.env.copy()
if status is not None:
env["BOOKSPRITE_TEST_STATUS"] = str(status)
result = subprocess.run(
self.shell + [str(self.home / "launch.sh"), *args],
env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=20,
)
self.assertFalse((self.home / ".launcher.lock").exists(), result.stderr)
return result
def enable_command_fault_injection(self):
# Debian's BusyBox ash prefers compiled-in applets over PATH, making
# fake cp/mv/df commands ineffective. These three error-path tests run
# under the host POSIX shell after the relocation boundary instead.
self.shell = ["/bin/sh"]
self.env["BOOKSPRITE_RELOCATED"] = str(self.home)
def assert_version(self, version, path=None):
self.assertEqual(((path or self.current) / "version").read_text(), version)
def assert_clean_transaction(self):
self.assertFalse((self.home / ".staging").exists())
self.assertFalse((self.home / ".transaction").exists())
self.assertFalse((self.home / ".transaction.new").exists())
def test_normal_launch_exports_real_directory_and_releases_onboard_cwd(self):
result = self.run_launcher("/mnt/onboard/My Book.epub")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.home / "observed-dir").read_text().strip(), str(self.current))
self.assertEqual((self.home / "observed-cwd").read_text().strip(), "/")
self.assertEqual((self.home / "observed-args").read_text().strip(), "/mnt/onboard/My Book.epub")
self.assert_version("old")
def test_update_preserves_runtime_and_removes_obsolete_tracked_code(self):
runtime = {
"settings.reader.lua": "my settings",
"settings/statistics.sqlite3": "my statistics",
"history/last.lua": "history",
"data/dict/English.dict": "dictionary",
"data/tessdata/eng.traineddata": "OCR",
"patches/2-user.lua": "my patch",
"plugins/custom.koplugin/main.lua": "custom",
"fonts/my font.ttf": "font",
"defaults.custom.lua": "defaults",
}
for name, data in runtime.items():
path = self.current / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(data)
(self.current / "frontend/official.lua").write_text("local modification")
self.pending()
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("new")
self.assert_version("old", self.previous)
for name, data in runtime.items():
self.assertEqual((self.current / name).read_text(), data)
self.assertEqual((self.previous / name).read_text(), data)
self.assertFalse((self.current / "removed.lua").exists())
self.assertEqual((self.current / "frontend/official.lua").read_text(), "new")
self.assertEqual((self.previous / "frontend/official.lua").read_text(), "local modification")
self.assertFalse((self.home / "pending.tar.gz").exists())
self.assert_clean_transaction()
self.assertEqual((self.home / "launched-version").read_text(), "new")
def test_release_wins_new_tracked_collision_but_mutable_data_wins_defaults(self):
(self.current / "new-official.lua").write_text("formerly untracked")
self.pending(extra={"new-official.lua": "release", "settings/default.lua": "new default"})
(self.current / "settings").mkdir()
(self.current / "settings/default.lua").write_text("my setting")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.current / "new-official.lua").read_text(), "release")
self.assertEqual((self.current / "settings/default.lua").read_text(), "my setting")
def test_second_update_replaces_only_oldest_backup(self):
self.pending()
self.assertEqual(self.run_launcher().returncode, 0)
self.pending("third")
self.assertEqual(self.run_launcher().returncode, 0)
self.assert_version("third")
self.assert_version("new", self.previous)
def test_exit_codes_do_not_trigger_automatic_rollback(self):
self.make_tree(self.previous, "backup")
for code in [0, 1, 2, 85, 86, 88, 126, 127, 139]:
with self.subTest(code=code):
result = self.run_launcher(status=code)
self.assertEqual(result.returncode, code, result.stderr)
self.assert_version("old")
self.assert_version("backup", self.previous)
def test_manual_rollback_swaps_complete_snapshots_and_skips_pending(self):
self.make_tree(self.previous, "backup")
(self.current / "settings.reader.lua").write_text("current state")
(self.previous / "settings.reader.lua").write_text("backup state")
self.pending()
result = self.run_launcher("--rollback", "book.epub")
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("backup")
self.assert_version("old", self.previous)
self.assertEqual((self.current / "settings.reader.lua").read_text(), "backup state")
self.assertEqual((self.previous / "settings.reader.lua").read_text(), "current state")
self.assertTrue((self.home / "pending.tar.gz").exists())
self.assertEqual((self.home / "observed-args").read_text().strip(), "book.epub")
self.assert_clean_transaction()
def test_manual_rollback_restores_missing_current(self):
self.make_tree(self.previous, "backup")
shutil.rmtree(self.current)
result = self.run_launcher("--rollback")
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("backup")
def test_no_backup_rollback_fails_without_changing_current(self):
result = self.run_launcher("--rollback")
self.assertEqual(result.returncode, 1)
self.assert_version("old")
def test_low_disk_preserves_current_and_backup_and_quarantines_archive(self):
self.enable_command_fault_injection()
self.make_tree(self.previous, "backup")
self.pending()
self.fake_command("df", "printf 'Filesystem 1024-blocks Used Available Capacity Mounted on\\nfs 1000 999 1 99%% /\\n'\n")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("insufficient free space", result.stderr)
self.assert_version("old")
self.assert_version("backup", self.previous)
self.assertTrue((self.home / "rejected.tar.gz").exists())
self.assert_clean_transaction()
def malformed_archive(self, members):
with tarfile.open(self.home / "pending.tar.gz", "w:gz", format=tarfile.USTAR_FORMAT) as tar:
for name, kind, value in members:
entry = tarfile.TarInfo(name)
entry.type = kind
if kind == tarfile.REGTYPE:
data = value.encode()
entry.size = len(data)
tar.addfile(entry, io.BytesIO(data))
else:
entry.linkname = value
tar.addfile(entry)
def test_rejects_path_traversal_absolute_links_special_files_and_duplicates(self):
cases = [
[("../outside", tarfile.REGTYPE, "bad")],
[("/tmp/booksprite-escape", tarfile.REGTYPE, "bad")],
[("koreader/../../outside", tarfile.REGTYPE, "bad")],
[("koreader/./file", tarfile.REGTYPE, "bad")],
[("koreader//file", tarfile.REGTYPE, "bad")],
[("not-koreader/file", tarfile.REGTYPE, "bad")],
[("koreader/link", tarfile.SYMTYPE, "../../outside")],
[("koreader/link", tarfile.LNKTYPE, "../../outside")],
[("koreader/fifo", tarfile.FIFOTYPE, "")],
[("koreader/file", tarfile.REGTYPE, "a"), ("koreader/file", tarfile.REGTYPE, "b")],
[("koreader/control\nkoreader/other", tarfile.REGTYPE, "bad")],
[("koreader/back\\slash", tarfile.REGTYPE, "bad")],
]
self.make_tree(self.previous, "backup")
for members in cases:
with self.subTest(members=members):
self.malformed_archive(members)
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("Update not installed", result.stderr)
self.assert_version("old")
self.assert_version("backup", self.previous)
self.assert_clean_transaction()
self.assertFalse((self.root / "outside").exists())
self.assertFalse(Path("/tmp/booksprite-escape").exists())
def test_corrupt_archive_is_not_extracted(self):
(self.home / "pending.tar.gz").write_bytes(b"not a gzip")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("unsafe or corrupt", result.stderr)
self.assert_version("old")
self.assert_clean_transaction()
def test_missing_or_untruthful_manifests_are_rejected(self):
for content in [None, "../escape\n", "booksprite-files.txt\n", "z\nbooksprite-files.txt\n"]:
with self.subTest(manifest=content):
payload = self.pending()
manifest = payload / "booksprite-files.txt"
if content is None:
manifest.unlink()
else:
manifest.write_text(content)
with tarfile.open(self.home / "pending.tar.gz", "w:gz") as tar:
tar.add(payload, arcname="koreader")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("Update not installed", result.stderr)
self.assert_version("old")
self.assert_clean_transaction()
def test_missing_current_manifest_refuses_lossy_update(self):
self.pending()
(self.current / "booksprite-files.txt").unlink()
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("invalid release manifest", result.stderr)
self.assert_version("old")
def test_runtime_copy_failure_does_not_commit_partial_stage(self):
self.enable_command_fault_injection()
(self.current / "settings.reader.lua").write_text("settings")
self.pending()
real_cp = shutil.which("cp")
self.fake_command("cp", f"""case "$*" in
*settings.reader.lua*) exit 1 ;;
esac
exec {shlex.quote(real_cp)} "$@"
""")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("cannot preserve mutable data", result.stderr)
self.assert_version("old")
self.assertEqual((self.current / "settings.reader.lua").read_text(), "settings")
self.assertFalse(self.previous.exists())
self.assert_clean_transaction()
def test_symlink_control_paths_are_refused_without_following(self):
outside = self.root / "outside"
outside.mkdir()
protected = outside / "protected"
protected.write_text("safe")
for name in ["previous", ".staging", "pending.tar.gz", "launcher.log"]:
with self.subTest(name=name):
path = self.home / name
if path.exists():
path.unlink()
path.symlink_to(protected if name == "launcher.log" else outside)
result = self.run_launcher()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertEqual(protected.read_text(), "safe")
path.unlink()
def test_runtime_symlink_refuses_update_without_dereferencing(self):
(self.current / "linked").symlink_to(self.stock)
self.pending()
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("contains links", result.stderr)
self.assert_version("old")
def test_stale_lock_recovers(self):
lock = self.home / ".launcher.lock"
lock.mkdir()
(lock / "pid").write_text("99999999\n")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("Recovered stale", result.stderr)
def test_empty_stale_lock_recovers(self):
(self.home / ".launcher.lock").mkdir()
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
def test_live_lock_is_not_removed(self):
lock = self.home / ".launcher.lock"
lock.mkdir()
(lock / "pid").write_text(str(os.getpid()))
result = subprocess.run(SHELL + [str(self.home / "launch.sh")],
env=self.env, capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 75, result.stderr)
self.assertEqual((lock / "pid").read_text(), str(os.getpid()))
self.assertFalse((self.home / "launched-version").exists())
def test_concurrent_launch_refuses_while_reader_running(self):
env = dict(self.env, BOOKSPRITE_TEST_WAIT="yes")
first = subprocess.Popen(SHELL + [str(self.home / "launch.sh")],
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
for _ in range(100):
if (self.home / "ready").exists():
break
time.sleep(0.02)
self.assertTrue((self.home / "ready").exists())
second = subprocess.run(SHELL + [str(self.home / "launch.sh")],
env=self.env, capture_output=True, timeout=10)
self.assertEqual(second.returncode, 75, second.stderr)
self.assertTrue((self.home / ".launcher.lock").exists())
finally:
(self.home / "continue").touch()
first.communicate(timeout=10)
self.assertEqual(first.returncode, 0)
self.assertFalse((self.home / ".launcher.lock").exists())
def test_terminating_supervisor_forwards_signal_to_reader(self):
env = dict(self.env, BOOKSPRITE_TEST_WAIT="yes")
first = subprocess.Popen(SHELL + [str(self.home / "launch.sh")],
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
for _ in range(100):
if (self.home / "ready").exists():
break
time.sleep(0.02)
self.assertTrue((self.home / "ready").exists())
first.send_signal(signal.SIGTERM)
first.communicate(timeout=10)
self.assertEqual(first.returncode, 143)
self.assertFalse((self.home / ".launcher.lock").exists())
finally:
(self.home / "continue").touch()
if first.poll() is None:
first.kill()
first.communicate()
def test_abandoned_precommit_stage_requeues_and_installs(self):
self.pending()
stage = self.home / ".staging"
stage.mkdir()
(self.home / "pending.tar.gz").rename(stage / "payload.tar.gz")
(stage / "partial").write_text("interrupted extraction")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("new")
self.assert_version("old", self.previous)
self.assert_clean_transaction()
def test_new_upload_wins_over_abandoned_precommit_archive(self):
self.pending("abandoned")
stage = self.home / ".staging"
stage.mkdir()
(self.home / "pending.tar.gz").rename(stage / "payload.tar.gz")
self.pending("fresh")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("fresh")
self.assertTrue((self.home / "rejected.tar.gz").exists())
self.assert_clean_transaction()
def prepare_recovery(self, phase, moved=False):
stage = self.home / ".staging"
stage.mkdir()
if phase.startswith("update"):
self.make_tree(stage / "koreader", "new")
self.make_tree(self.previous, "ancient")
(stage / "payload.tar.gz").write_bytes(b"already validated")
if phase != "update-save" or moved:
shutil.rmtree(self.previous)
self.current.rename(self.previous)
if phase == "update-finish" or (phase == "update-promote" and moved):
(stage / "koreader").rename(self.current)
else:
self.make_tree(self.previous, "backup")
if phase != "rollback-save" or moved:
self.current.rename(stage / "koreader")
if phase == "rollback-finish" or (phase == "rollback-restore" and moved):
self.previous.rename(self.current)
if phase == "rollback-finish" and moved:
(stage / "koreader").rename(self.previous)
(self.home / ".transaction").write_text(phase + "\n")
def test_every_update_rename_boundary_recovers(self):
# Each subtest gets a separate on-disk installation.
for phase, moved in [
("update-save", False), ("update-save", True),
("update-promote", False), ("update-promote", True),
("update-finish", False),
]:
with self.subTest(phase=phase, moved=moved):
self.prepare_recovery(phase, moved)
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("new")
self.assert_version("old", self.previous)
self.assert_clean_transaction()
shutil.rmtree(self.current)
shutil.rmtree(self.previous.parent)
self.make_tree(self.current, "old")
def test_every_rollback_rename_boundary_recovers(self):
for phase, moved in [
("rollback-save", False), ("rollback-save", True),
("rollback-restore", False), ("rollback-restore", True),
("rollback-finish", False), ("rollback-finish", True),
]:
with self.subTest(phase=phase, moved=moved):
self.prepare_recovery(phase, moved)
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("backup")
self.assert_version("old", self.previous)
self.assert_clean_transaction()
shutil.rmtree(self.current)
shutil.rmtree(self.previous.parent)
self.make_tree(self.current, "old")
def test_repeated_rollback_action_finishes_interrupted_swap_only_once(self):
self.prepare_recovery("rollback-restore", False)
result = self.run_launcher("--rollback")
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("backup")
self.assert_version("old", self.previous)
self.assert_clean_transaction()
def test_unknown_journal_fails_closed(self):
(self.home / ".transaction").write_text("corrupt\n")
result = self.run_launcher()
self.assertEqual(result.returncode, 1)
self.assert_version("old")
self.assertTrue((self.home / ".transaction").exists())
self.assertFalse((self.home / "launched-version").exists())
def test_failed_promotion_keeps_journal_and_next_launch_recovers(self):
self.enable_command_fault_injection()
self.pending()
real_mv = shutil.which("mv")
self.fake_command("mv", f"""case "$1:$2" in
*/.staging/koreader:*/booksprite/koreader) exit 1 ;;
esac
exec {shlex.quote(real_mv)} "$@"
""")
result = self.run_launcher()
self.assertEqual(result.returncode, 1, result.stderr)
self.assertFalse(self.current.exists())
self.assert_version("old", self.previous)
self.assertEqual((self.home / ".transaction").read_text(), "update-promote\n")
(self.bin / "mv").unlink()
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_version("new")
self.assert_version("old", self.previous)
self.assert_clean_transaction()
def test_full_built_release_payload_when_available(self):
# Only replace the ARM launcher in a temporary copy of the archive;
# production artifacts and manifests remain untouched. Everything else
# (1000+ official files + Lua overlays) passes through the real staging,
# BusyBox archive validation, manifest validation and rename path.
archive_env = os.environ.get("BOOKSPRITE_TEST_OTA")
if archive_env:
archive = Path(archive_env)
self.assertTrue(archive.is_file(), str(archive))
else:
dist = LAUNCHER.parent / "dist"
archives = list(dist.glob("booksprite-kobo-v*.tar.gz"))
if not archives:
self.skipTest("build an OTA archive or set BOOKSPRITE_TEST_OTA")
archive = max(archives, key=lambda path: path.stat().st_mtime_ns)
host_launcher = b"""#!/bin/sh
printf '%s\\n' "$KOREADER_DIR" >"$BOOKSPRITE_HOME/observed-dir"
exit 0
"""
with tarfile.open(archive, "r:gz") as source:
with tarfile.open(self.home / "pending.tar.gz", "w:gz", compresslevel=1,
format=tarfile.USTAR_FORMAT) as dest:
for entry in source:
if entry.name == "koreader/koreader.sh":
entry.size = len(host_launcher)
dest.addfile(entry, io.BytesIO(host_launcher))
else:
dest.addfile(entry, source.extractfile(entry) if entry.isfile() else None)
(self.current / "settings.reader.lua").write_text("full release settings")
result = self.run_launcher()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn("Update not installed", result.stderr)
self.assertTrue((self.current / "booksprite-version").is_file())
manifest = (self.current / "booksprite-files.txt").read_text().splitlines()
self.assertGreater(len(manifest), 1000)
self.assertEqual((self.current / "settings.reader.lua").read_text(), "full release settings")
self.assertFalse((self.current / "removed.lua").exists())
self.assert_version("old", self.previous)
self.assertEqual((self.home / "observed-dir").read_text().strip(), str(self.current))
self.assert_clean_transaction()
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -45,7 +45,7 @@ local Screen = Device.screen
local T = ffiUtil.template
local FileManager = InputContainer:extend{
title = _("KOReader"),
title = _("BookSprite"),
active_widgets = nil, -- array
root_path = lfs.currentdir(),
@@ -457,7 +457,7 @@ function FileChooser:onBack()
return true
elseif back_to_exit == "prompt" then
UIManager:show(ConfirmBox:new{
text = _("Exit KOReader?"),
text = _("Exit BookSprite?"),
ok_text = _("Exit"),
ok_callback = function()
self:onClose()
@@ -19,7 +19,7 @@ exit_settings.exit = {
end,
}
exit_settings.restart_koreader = {
text = _("Restart KOReader"),
text = _("Restart BookSprite"),
callback = function()
UIManager:broadcastEvent(Event:new("Restart"))
end,
@@ -14,6 +14,13 @@ local _ = require("gettext")
local T = require("ffi/util").template
local common_info = {}
local function bookSpriteVersion()
local f = io.open("booksprite-version", "r")
if not f then return "development" end
local version = f:read("*l")
f:close()
return version or "development"
end
-- tools tab
common_info.more_tools = {
@@ -55,7 +62,7 @@ common_info.report_bug = {
keep_menu_open = true,
callback = function(touchmenu_instance)
local log_path = string.format("%s/%s", DataStorage:getDataDir(), "crash.log")
local common_msg = T(_("Please report bugs to \nhttps://github.com/koreader/koreader/issues\n\nVersion:\n%1\n\nDetected device:\n%2"),
local common_msg = T(_("Please report bugs to \nhttps://gitea.jameshall.xyz/exe.dev/booksprite/issues\n\nVersion:\n%1\n\nDetected device:\n%2"),
Version:getCurrentRevision(), Device:info())
local log_msg = T(_("Verbose logs will make our investigations easier. If possible, try to reproduce the issue while it's enabled, and attach %1 to your bug report."), log_path)
@@ -116,11 +123,11 @@ common_info.plugins_disable_external = {
end,
}
common_info.version = {
text = T(_("Version: %1"), Version:getShortVersion()),
text = "BookSprite " .. bookSpriteVersion(),
keep_menu_open = true,
callback = function()
UIManager:show(InfoMessage:new{
text = Version:getCurrentRevision(),
text = "BookSprite " .. bookSpriteVersion() .. "\nKOReader " .. Version:getCurrentRevision(),
})
end
}
@@ -129,7 +136,7 @@ common_info.about = {
keep_menu_open = true,
callback = function()
UIManager:show(InfoMessage:new{
text = T(_("KOReader %1\n\nA document viewer for E Ink devices.\n\nLicensed under Affero GPL v3. All dependencies are free software.\n\nhttp://koreader.rocks"), BD.ltr(Version:getCurrentRevision())),
text = T(_("BookSprite %1\nBased on KOReader %2\n\nA document viewer for E Ink devices.\n\nLicensed under Affero GPL v3. All dependencies are free software.\n\nhttp://koreader.rocks"), bookSpriteVersion(), BD.ltr(Version:getCurrentRevision())),
icon = "koreader",
})
end
+286 -410
View File
@@ -1,455 +1,331 @@
--[[--
Checks for updates on the specified nightly build server.
BookSprite's stable-channel updater.
Only downloads and verifies an archive. The stable NickelMenu launcher,
outside koreader/, installs ../pending.tar.gz on the next launch. Never use
KOReader's installer or restart into the upstream launcher.
]]
local BD = require("ui/bidi")
local ConfirmBox = require("ui/widget/confirmbox")
local DataStorage = require("datastorage")
local Device = require("device")
local InfoMessage = require("ui/widget/infomessage")
local MultiConfirmBox = require("ui/widget/multiconfirmbox")
local NetworkMgr = require("ui/network/manager")
local UIManager = require("ui/uimanager")
local Version = require("version")
local lfs = require("libs/libkoreader-lfs")
local logger = require("logger")
local util = require("util")
local _ = require("gettext")
local C_ = _.pgettext
local T = require("ffi/util").template
local ota_dir = DataStorage:getDataDir() .. "/ota/"
local MANIFEST_URL = "https://gitea.jameshall.xyz/exe.dev/booksprite/raw/branch/releases/stable.json"
local RELEASE_PREFIX = "https://gitea.jameshall.xyz/exe.dev/booksprite/releases/download/"
local UPDATE_HOST = "gitea.jameshall.xyz"
local MAX_ARCHIVE_SIZE = 250 * 1024 * 1024
local MAX_MANIFEST_SIZE = 16 * 1024
local PENDING_FILE = "../pending.tar.gz"
local DOWNLOAD_FILE = "../pending.tar.gz.part"
local OTAManager = {
-- NOTE: Each URL *MUST* end with a /
ota_servers = {
"http://ota.koreader.rocks/",
--[[
-- NOTE: Seems down? Ping @chrox ;).
"http://vislab.bjmu.edu.cn/apps/koreader/ota/",
--]]
"http://koreader-fr.ak-team.com/",
"http://koreader-pl.ak-team.com/",
"http://koreader-na.ak-team.com/",
"http://koreader.ak-team.com/",
},
ota_channels = {
"stable",
"nightly",
},
link_template = "koreader-%s-latest-%s",
zsync_template = "koreader-%s-latest-%s.zsync",
installed_package = ota_dir .. "koreader.installed.tar",
package_indexfile = "ota/package.index",
updated_package = ota_dir .. "koreader.updated.tar",
can_pretty_print = lfs.attributes("./fbink", "mode") == "file" and true or false,
}
local OTAManager = {}
local ota_channels = {
stable = _("Stable"),
nightly = _("Development"),
}
function OTAManager:getOTAType()
local platform, kind = Device:otaModel()
if not platform then return "none" end
return kind
end
function OTAManager:getOTAServer()
return G_reader_settings:readSetting("ota_server") or self.ota_servers[1]
end
function OTAManager:setOTAServer(server)
logger.dbg("Set OTA server:", server)
G_reader_settings:saveSetting("ota_server", server)
end
function OTAManager:getOTAChannel()
return G_reader_settings:readSetting("ota_channel") or self.ota_channels[1]
end
function OTAManager:setOTAChannel(channel)
logger.dbg("Set OTA channel:", channel)
G_reader_settings:saveSetting("ota_channel", channel)
end
function OTAManager:getFilename(kind)
if type(kind) ~= "string" then return end
local model = Device:otaModel()
local channel = self:getOTAChannel()
if kind == "ota" then
return self.zsync_template:format(model, channel)
elseif kind == "link" then
return self.link_template:format(model, channel)
local function parseVersion(version)
if type(version) ~= "string" or #version > 32 then return end
local major, minor, patch = version:match("^(%d+)%.(%d+)%.(%d+)$")
if not major or #major > 9 or #minor > 9 or #patch > 9 then return end
for _, part in ipairs{ major, minor, patch } do
if #part > 1 and part:sub(1, 1) == "0" then return end
end
return { tonumber(major), tonumber(minor), tonumber(patch) }
end
function OTAManager:getZsyncFilename()
return self:getFilename("ota")
local function isNewer(available, installed)
local a, b = parseVersion(available), parseVersion(installed)
if not a or not b then return false end
for i = 1, 3 do
if a[i] ~= b[i] then return a[i] > b[i] end
end
return false
end
function OTAManager:getCurrentVersion()
local file = io.open("booksprite-version", "rb")
if not file then return end
local version = file:read(64)
file:close()
version = version and version:match("^%s*(.-)%s*$")
if parseVersion(version) then return version end
end
function OTAManager:validateManifest(manifest)
if type(manifest) ~= "table" or manifest.target ~= "kobo" or manifest.target ~= Device:otaModel()
or not parseVersion(manifest.version)
or type(manifest.size) ~= "number" or manifest.size ~= manifest.size
or manifest.size <= 0 or manifest.size > MAX_ARCHIVE_SIZE
or manifest.size % 1 ~= 0
or type(manifest.sha256) ~= "string" or #manifest.sha256 ~= 64
or not manifest.sha256:match("^%x+$")
or type(manifest.url) ~= "string" or #manifest.url > 2048
or manifest.url:sub(1, #RELEASE_PREFIX) ~= RELEASE_PREFIX then
return nil, _("Invalid BookSprite update manifest.")
end
-- A release tag and a tar.gz filename only: no redirects, queries,
-- URL escapes, credentials, alternative ports, or traversal components.
local tag, filename = manifest.url:sub(#RELEASE_PREFIX + 1):match("^([%w._%-]+)/([%w._%-]+%.tar%.gz)$")
if not tag or tag == "." or tag == ".." or not filename then
return nil, _("Invalid BookSprite release URL.")
end
return {
version = manifest.version,
target = manifest.target,
size = manifest.size,
sha256 = manifest.sha256:lower(),
url = manifest.url,
}
end
-- LuaSec's default HTTPS configuration does not authenticate the peer. Use
-- the shipped CA bundle AND check the SAN hostname before sending HTTP data.
-- The fixed hostname makes wildcard matching deliberately restrictive.
function OTAManager:certificateMatchesHost(certificate)
if not certificate then return false end
local extensions = certificate:extensions()
local san = extensions and extensions["2.5.29.17"]
for _, name in ipairs(san and san.dNSName or {}) do
name = name:lower()
if name == UPDATE_HOST or name == "*.jameshall.xyz" then return true end
end
return false
end
function OTAManager:createTLSConnection()
local socket = require("socket")
local ssl = require("ssl")
local sock, err = socket.tcp()
if not sock then return nil, err end
local connection = { sock = sock }
local manager = self
function connection:settimeout()
return self.sock:settimeout(15)
end
function connection:close()
return self.sock:close()
end
function connection:connect(host, port)
if host ~= UPDATE_HOST or tonumber(port) ~= 443 then
return nil, "BookSprite update host is not allowed"
end
local ok, connect_err = self.sock:connect(host, port)
if not ok then return nil, connect_err end
local wrapped, wrap_err = ssl.wrap(self.sock, {
mode = "client",
protocol = "any",
options = { "all", "no_sslv2", "no_sslv3", "no_tlsv1", "no_tlsv1_1" },
verify = "peer",
cafile = "data/ca-bundle.crt",
})
if not wrapped then return nil, wrap_err end
self.sock = wrapped
self.sock:settimeout(15)
self.sock:sni(host)
local handshake_ok, handshake_err = self.sock:dohandshake()
if not handshake_ok then return nil, handshake_err end
if not manager:certificateMatchesHost(self.sock:getpeercertificate()) then
return nil, "BookSprite update certificate hostname mismatch"
end
return 1
end
for _, method in ipairs{ "send", "receive", "getfd", "dirty" } do
connection[method] = function(this, ...)
return this.sock[method](this.sock, ...)
end
end
return connection
end
function OTAManager:requestHTTPS(url, sink, limit, timeout)
if url ~= MANIFEST_URL and url:sub(1, #RELEASE_PREFIX) ~= RELEASE_PREFIX then
return nil, _("BookSprite update host is not allowed.")
end
local http = require("socket.http")
local socket = require("socket")
if http.PROXY then return nil, _("Disable the HTTP proxy before updating BookSprite.") end
local started, bytes = socket.gettime(), 0
local connection
local ok, result, code = pcall(http.request, {
url = url,
redirect = false,
headers = { ["accept-encoding"] = "identity" },
create = function()
local err
connection, err = self:createTLSConnection()
return connection, err
end,
sink = function(chunk, err)
if socket.gettime() - started > timeout then
return nil, "BookSprite update download timed out"
end
if err then return nil, err end
if chunk then
bytes = bytes + #chunk
if bytes > limit then return nil, "BookSprite update exceeds size limit" end
return sink(chunk)
end
return 1
end,
})
-- Also close on exceptions, e.g. a sink write failure or TLS API error.
if connection then pcall(connection.close, connection) end
if not ok or not result or tonumber(code) ~= 200 then
logger.warn("BookSprite update request failed:", ok and code or result)
return nil, _("Unable to download the BookSprite update. Check Wi-Fi, free space, and the device clock, then try again.")
end
return bytes
end
function OTAManager:getInstallationError()
if not Device:isKobo() or not lfs.currentdir():match("/%.adds/booksprite/koreader$") then
return _("BookSprite updates require the separate .adds/booksprite installation.")
end
if Device:otaModel() ~= "kobo" then
return _("This BookSprite update channel supports standard Kobo devices only, not Kobo firmware 5 devices.")
end
end
function OTAManager:checkUpdate()
if Device:isDeprecated() then return -1 end
local http = require("socket.http")
local ltn12 = require("ltn12")
local socket = require("socket")
local socketutil = require("socketutil")
local update_kind = self:getOTAType()
if not update_kind then return -1 end
local update_file = self:getFilename(update_kind)
if not update_file then return -2 end
local ota_update_file = self:getOTAServer() .. update_file
local local_update_file = ota_dir .. update_file
-- download zsync file from OTA server
logger.dbg("downloading update file", ota_update_file)
socketutil:set_timeout()
local code, headers, status = socket.skip(1, http.request{
url = ota_update_file,
sink = ltn12.sink.file(io.open(local_update_file, "w")),
})
socketutil:reset_timeout()
if code ~= 200 then
logger.warn("cannot find update file:", status or code or "network unreachable")
logger.dbg("Response headers:", headers)
return
local installation_err = self:getInstallationError()
if installation_err then return nil, nil, installation_err end
local installed = self:getCurrentVersion()
if not installed then
return nil, nil, _("Cannot read booksprite-version. Reinstall the BookSprite package.")
end
-- parse OTA package version
local link, ota_package
local update_info = io.open(local_update_file, "r")
if update_info then
if OTAManager:getOTAType() == "link" then
local i = 0
for line in update_info:lines() do
i = i + 1
if i == 1 then
ota_package = line
link = self:getOTAServer() .. ota_package
end
end
else
for line in update_info:lines() do
ota_package = line:match("^Filename:%s*(.-)%s*$")
if ota_package then break end
end
local chunks = {}
local bytes, err = self:requestHTTPS(MANIFEST_URL, function(chunk)
chunks[#chunks + 1] = chunk
return 1
end, MAX_MANIFEST_SIZE, 30)
if not bytes then return nil, nil, err end
local ok, decoded = pcall(require("json").decode, table.concat(chunks))
if not ok then return nil, nil, _("Invalid BookSprite update manifest.") end
local manifest, validation_err = self:validateManifest(decoded)
if not manifest then return nil, nil, validation_err end
if not isNewer(manifest.version, installed) then return false, installed end
return manifest, installed
end
function OTAManager:downloadUpdate(manifest)
local installation_err = self:getInstallationError()
if installation_err then return nil, installation_err end
-- Validate again at the point of use; no untrusted values reach a shell.
local validated, err = self:validateManifest(manifest)
if not validated then return nil, err end
manifest = validated
if lfs.symlinkattributes(PENDING_FILE) then
return nil, _("A BookSprite update is already ready. Exit and relaunch BookSprite from NickelMenu.")
end
local disk = util.diskUsage("..")
-- Reserve room for the archive and extraction. The launcher must also
-- check actual unpacked size before swapping the application directories.
if not disk.available or disk.available < math.max(1024 * 1024 * 1024, manifest.size * 4 + 32 * 1024 * 1024) then
return nil, _("Not enough free space to safely download and unpack BookSprite.")
end
os.remove(DOWNLOAD_FILE)
local file, open_err = io.open(DOWNLOAD_FILE, "wb")
if not file then
logger.warn("BookSprite update staging failed:", open_err)
return nil, _("Cannot create the BookSprite update download.")
end
local ok, bytes, download_err = pcall(function()
local hash = require("ffi/sha2").sha256()
local count, request_err = self:requestHTTPS(manifest.url, function(chunk)
local written, write_err = file:write(chunk)
if not written then return nil, write_err end
hash(chunk)
return 1
end, manifest.size, 30 * 60)
if not count then return nil, request_err end
if count ~= manifest.size or hash() ~= manifest.sha256 then
return nil, _("BookSprite update verification failed (size or SHA-256 mismatch). Please try again.")
end
update_info:close()
end
local local_ok, local_version = pcall(function()
local rev = Version:getCurrentRevision()
if rev then return Version:getNormalizedVersion(rev) end
return count
end)
local ota_ok, ota_version = pcall(function()
return Version:getNormalizedVersion(ota_package)
end)
-- return ota package version if package on OTA server has version
-- larger than the local package version
if local_ok and ota_ok and ota_version and local_version and
ota_version ~= local_version then
return ota_version, local_version, link, ota_package
elseif ota_version and ota_version == local_version then
return 0
local closed = file:close()
if not ok or not bytes or not closed then
os.remove(DOWNLOAD_FILE)
return nil, (ok and download_err) or _("Unable to verify or save the BookSprite update.")
end
-- Publish the verified, complete archive in one same-filesystem rename.
-- It contains ONLY koreader/; it never updates launch.sh itself.
local renamed, rename_err = os.rename(DOWNLOAD_FILE, PENDING_FILE)
if not renamed then
os.remove(DOWNLOAD_FILE)
logger.warn("BookSprite update rename failed:", rename_err)
return nil, _("Cannot stage the verified BookSprite update.")
end
return true
end
function OTAManager:showStatus(text)
UIManager:show(InfoMessage:new{ text = text })
end
function OTAManager:runWithProgress(text, callback)
if self.busy then return end
self.busy = true
local message = InfoMessage:new{ text = text }
UIManager:show(message)
UIManager:forceRePaint()
UIManager:scheduleIn(0.1, function()
local ok, err = pcall(callback)
self.busy = false
UIManager:close(message)
if not ok then
logger.warn("BookSprite updater failed:", err)
self:showStatus(_("BookSprite update failed. Please try again."))
end
end)
end
function OTAManager:fetchAndProcessUpdate()
if Device:hasOTARunning() then
UIManager:show(InfoMessage:new{
text = _("Download already scheduled. You'll be notified when it's ready."),
})
if lfs.symlinkattributes(PENDING_FILE) then
self:showStatus(_("A BookSprite update is ready.\n\nExit BookSprite, then launch BookSprite again from NickelMenu to install it. Do not use KOReader's restart command."))
return
end
local ota_version, local_version, link, ota_package = OTAManager:checkUpdate()
if ota_version == 0 then
UIManager:show(InfoMessage:new{
text = _("KOReader is up to date."),
})
elseif ota_version == -1 then
UIManager:show(InfoMessage:new{
text = T(_("Device no longer supported.\n\nPlease check %1"), "https://github.com/koreader/koreader/wiki/deprecated-devices")
})
elseif ota_version == -2 then
UIManager:show(InfoMessage:new{
text = _("Unable to determine OTA model.")
})
elseif ota_version == nil then
UIManager:show(InfoMessage:new{
text = _("Unable to contact OTA server. Try again later, or try another mirror."),
})
elseif ota_version then
local update_message = T(_("Do you want to update?\nInstalled version: %1\nAvailable version: %2"),
BD.ltr(local_version),
BD.ltr(ota_version))
local update_ok_text = C_("Application update | Button", "Update")
if ota_version < local_version then
-- Android cannot downgrade APKs. The user needs to uninstall current app first.
-- Instead of doing the auto-update when ready we just download the APK using the browser.
if Device:isAndroid() then
UIManager:show(ConfirmBox:new{
text = T(_("The currently installed version is newer than the available version.\nYou'll need to uninstall the app before installing a previous version.\nDownload anyway?\n\nInstalled version: %1\nAvailable version: %2"),
BD.ltr(local_version),
BD.ltr(ota_version)),
ok_text = _("Download"),
ok_callback = function()
Device:openLink(link)
end,
})
return
end
update_message = T(_("The currently installed version is newer than the available version.\nWould you still like to continue and downgrade?\nInstalled version: %1\nAvailable version: %2"),
BD.ltr(local_version),
BD.ltr(ota_version))
update_ok_text = _("Downgrade")
end
local wait_for_download = _("Downloading may take several minutes…")
if OTAManager:getOTAType() == "link" then
UIManager:show(ConfirmBox:new{
text = update_message,
ok_text = update_ok_text,
ok_callback = function()
if Device:isAndroid() then
Device:download(link, ota_package, wait_for_download)
elseif Device:isSDL() then
Device:openLink(link)
end
end
})
self:runWithProgress(_("Checking for BookSprite updates…"), function()
local manifest, installed, err = self:checkUpdate()
if manifest == false then
self:showStatus(T(_("BookSprite is up to date.\nInstalled version: %1"), installed))
elseif not manifest then
self:showStatus(err)
else
UIManager:show(ConfirmBox:new{
text = update_message,
ok_text = update_ok_text,
text = T(_("Download BookSprite update?\n\nInstalled version: %1\nAvailable version: %2\n\nThe update will be installed when you exit and relaunch BookSprite from NickelMenu."),
installed, manifest.version),
ok_text = _("Download"),
ok_callback = function()
UIManager:show(InfoMessage:new{
text = wait_for_download,
timeout = 3,
})
UIManager:scheduleIn(1, function()
if OTAManager:zsync() == 0 then
Device:install()
-- Make it clear that zsync is done
if self.can_pretty_print then
os.execute("./fbink -q -y -7 -pm ' ' ' '")
end
else
-- Make it clear that zsync is done
if self.can_pretty_print then
os.execute("./fbink -q -y -7 -pm ' ' ' '")
end
UIManager:show(MultiConfirmBox:new{
text = _("Failed to update KOReader.\n\nYou can:\nCancel, keeping temporary files.\nRetry the update process with a full download.\nAbort and cleanup all temporary files."),
choice1_text = _("Retry"),
choice1_callback = function()
UIManager:show(InfoMessage:new{
text = _("Downloading may take several minutes…"),
timeout = 3,
})
-- Clear the installed package, as well as the complete/incomplete update download
os.execute("rm -f " .. self.installed_package)
os.execute("rm -f " .. self.updated_package .. "*")
-- As well as temporary files, in case zsync went kablooey too early...
os.execute("rm -f ./rcksum-*")
-- And then relaunch zsync in full download mode...
UIManager:scheduleIn(1, function()
if OTAManager:zsync(true) == 0 then
Device:install()
-- Make it clear that zsync is done
if self.can_pretty_print then
os.execute("./fbink -q -y -7 -pm ' ' ' '")
end
else
-- Make it clear that zsync is done
if self.can_pretty_print then
os.execute("./fbink -q -y -7 -pm ' ' ' '")
end
UIManager:show(ConfirmBox:new{
text = _("Error updating KOReader. Would you like to delete temporary files?"),
ok_callback = function()
os.execute("rm -f " .. ota_dir .. "ko*")
end,
})
end
end)
end,
choice2_text = _("Abort"),
choice2_callback = function()
os.execute("rm -f " .. ota_dir .. "ko*")
os.execute("rm -f " .. self.updated_package .. "*")
os.execute("rm -f ./rcksum-*")
end,
})
end
NetworkMgr:runWhenOnline(function()
self:runWithProgress(_("Downloading and verifying BookSprite…\n\nThis may take several minutes."), function()
local downloaded, download_err = self:downloadUpdate(manifest)
self:showStatus(downloaded
and _("BookSprite update verified and ready.\n\nExit BookSprite, then launch BookSprite again from NickelMenu to install it. Your previous version will be kept for rollback. Do not use KOReader's restart command.")
or download_err)
end)
end)
end
end,
})
end
end
end
---- Uses zsync and tar to prepare an update package.
function OTAManager:_buildLocalPackage()
--- @todo Validate the installed package?
local installed_package = self.installed_package
if lfs.attributes(installed_package, "mode") == "file" then
return 0
end
if lfs.attributes(self.package_indexfile, "mode") ~= "file" then
logger.err("Missing ota metadata:", self.package_indexfile)
return nil
end
local tar_cmd = {
'./tar',
'--create', '--file='..self.installed_package,
'--mtime', tostring(Version:getBuildDate()),
'--numeric-owner', '--owner=0', '--group=0',
'--ignore-failed-read', '--no-recursion', '-C', '..',
'--verbatim-files-from', '--files-from', self.package_indexfile,
}
-- With visual feedback if supported...
if self.can_pretty_print then
os.execute("./fbink -q -y -7 -pmh 'Preparing local OTA package'")
-- We need a vague idea of how much space the tarball we're creating will take to compute a proper percentage...
-- Get the size from the latest zsync package, which'll be a closer match than anything else we might come up with.
local update_file = self:getZsyncFilename()
local local_update_file = ota_dir .. update_file
local tarball_size = nil
local zsync = io.open(local_update_file, "r")
if zsync then
for line in zsync:lines() do
tarball_size = line:match("^Length: (%d*)$")
if tarball_size then break end
end
zsync:close()
end
-- Next, we need to compute the amount of tar blocks that'll take, knowing that tar's default blocksize is 20 * 512 bytes.
-- c.f., https://superuser.com/questions/168749 & http://www.noah.org/wiki/tar_notes
-- Defaults to a sane-ish value as-of now, in case shit happens...
local blocks = 6405
if tarball_size then
blocks = tarball_size * (1/(512 * 20))
end
-- And since we want a percentage, devise the exact value we need for tar to spit out exactly 100 checkpoints ;).
local cpoints = blocks * (1/100)
table.insert(tar_cmd, string.format('--checkpoint=%d', cpoints))
table.insert(tar_cmd, string.format('--checkpoint-action=exec=./fbink -q -y -6 -P $(($TAR_CHECKPOINT/%d))', cpoints))
end
return os.execute(util.shell_escape(tar_cmd))
end
function OTAManager:zsync(full_dl)
if full_dl or self:_buildLocalPackage() == 0 then
local zsync_wrapper = "./zsync2"
local use_pipefail = true
-- With visual feedback if supported...
if self.can_pretty_print then
zsync_wrapper = "./spinning_zsync"
-- And because everything is terrible, we can't check for pipefail's usability in spinning_zsync,
-- because older ash versions abort on set -o failures...
-- c.f., ko/#5844
-- So, instead, check from this side of the fence...
-- (remember, os.execute is essentially system(), it goes through sh)
use_pipefail = (os.execute("set -o pipefail 2>/dev/null") == 0)
end
local zsync_cmd = {
'env',
string.format('WITH_PIPEFAIL=%s', use_pipefail),
}
-- Honor HTTP proxy setting.
local http_proxy = G_reader_settings:readSetting("http_proxy")
if http_proxy then
table.insert(zsync_cmd, string.format("http_proxy=%s", http_proxy))
end
table.insert(zsync_cmd, zsync_wrapper)
-- Only add input tarball when not doing a full download.
if not full_dl then
util.arrayAppend(zsync_cmd, {"-i", self.installed_package})
end
util.arrayAppend(zsync_cmd, {
"-o", self.updated_package,
"-u", self:getOTAServer(),
ota_dir .. self:getZsyncFilename(),
})
return os.execute(util.shell_escape(zsync_cmd))
end
end
function OTAManager:genServerList()
local servers = {}
for _, server in ipairs(self.ota_servers) do
local server_item = {
text = server,
checked_func = function() return self:getOTAServer() == server end,
callback = function() self:setOTAServer(server) end
}
table.insert(servers, server_item)
end
return servers
end
function OTAManager:genChannelList()
local channels = {}
for _, channel in ipairs(self.ota_channels) do
local channel_item = {
text = ota_channels[channel],
checked_func = function() return self:getOTAChannel() == channel end,
callback = function() self:setOTAChannel(channel) end
}
table.insert(channels, channel_item)
end
return channels
end)
end
function OTAManager:getOTAMenuTable()
local check = function()
NetworkMgr:runWhenOnline(function() self:fetchAndProcessUpdate() end)
end
return {
text = C_("Application update | Menu", "Update"),
hold_callback = function()
local connect_callback = function()
OTAManager:fetchAndProcessUpdate()
end
NetworkMgr:runWhenOnline(connect_callback)
end,
text = _("BookSprite update"),
hold_callback = check,
sub_item_table = {
{
text = _("Check for updates"),
callback = function()
local working_im = InfoMessage:new{
alignment = "center",
show_icon = false,
text = "⌛",
}
UIManager:show(working_im)
UIManager:forceRePaint()
local connect_callback = function()
OTAManager:fetchAndProcessUpdate()
end
UIManager:close(working_im)
NetworkMgr:runWhenOnline(connect_callback)
end
},
{
text = _("Settings"),
sub_item_table = {
{
text = _("Update server"),
sub_item_table = self:genServerList()
},
{
text = _("Update channel"),
sub_item_table = self:genChannelList()
},
}
},
}
{ text = _("Check for BookSprite updates"), callback = check },
{ text = _("Channel: BookSprite stable"), enabled = false },
},
}
end
+3 -55
View File
@@ -91,61 +91,9 @@ if [ "${current_cpufreq_gov}" != "interactive" ]; then
fi
fi
# update to new version from OTA directory
ko_update_check() {
NEWUPDATE="${KOREADER_DIR}/ota/koreader.updated.tar"
INSTALLED="${KOREADER_DIR}/ota/koreader.installed.tar"
if [ -f "${NEWUPDATE}" ]; then
# Clear screen to delete UI leftovers
./fbink --cls
./fbink -q -y -7 -pmh "Updating KOReader"
# Keep a copy of the old manifest for cleaning leftovers later.
cp "${KOREADER_DIR}/ota/package.index" /tmp/
# Setup the FBInk daemon
export FBINK_NAMED_PIPE="/tmp/koreader.fbink"
rm -f "${FBINK_NAMED_PIPE}"
# We'll want to use REAGL on sunxi, because AUTO is slow, and fast merges are extremely broken outside of REAGL...
eval "$(./fbink -e | tr ';' '\n' | grep -e isSunxi | tr '\n' ';')"
# shellcheck disable=SC2154
if [ "${isSunxi}" = "1" ]; then
PBAR_WFM="REAGL"
else
PBAR_WFM="AUTO"
fi
FBINK_PID="$(./fbink --daemon 1 %KOREADER% -q -y -6 -P 0 -W ${PBAR_WFM})"
# NOTE: See frontend/ui/otamanager.lua for a few more details on how we squeeze a percentage out of tar's checkpoint feature
# NOTE: %B should always be 512 in our case, so let stat do part of the maths for us instead of using %s ;).
FILESIZE="$(stat -c %b "${NEWUPDATE}")"
BLOCKS="$((FILESIZE / 20))"
export CPOINTS="$((BLOCKS / 100))"
# shellcheck disable=SC2016
./tar xf "${NEWUPDATE}" --strip-components=1 --no-same-permissions --no-same-owner --checkpoint="${CPOINTS}" --checkpoint-action=exec='printf "%s" $((TAR_CHECKPOINT / CPOINTS)) > ${FBINK_NAMED_PIPE}'
fail=$?
kill -TERM "${FBINK_PID}"
# Cleanup behind us...
if [ "${fail}" -eq 0 ]; then
mv "${NEWUPDATE}" "${INSTALLED}"
# Cleanup leftovers from previous install.
(cd "${UNPACK_DIR}" && grep -xvFf "${KOREADER_DIR}/ota/package.index" /tmp/package.index | xargs -r rm -vf)
./fbink -q -y -6 -pm "Update successful :)"
./fbink -q -y -5 -pm "KOReader will start momentarily . . ."
# Warn if the startup script has been updated...
if [ "$(md5sum "/tmp/koreader.sh" | cut -f1 -d' ')" != "$(md5sum "${KOREADER_DIR}/koreader.sh" | cut -f1 -d' ')" ]; then
./fbink -q -pmMh "Update contains a startup script update!"
fi
else
# Uh oh...
./fbink -q -y -6 -pmh "Update failed :("
./fbink -q -y -5 -pm "KOReader may fail to function properly!"
fi
rm -f /tmp/package.index "${NEWUPDATE}" # always purge newupdate to prevent update loops
unset CPOINTS FBINK_NAMED_PIPE
unset BLOCKS FILESIZE FBINK_PID
# Ensure everything is flushed to disk before we restart. This *will* stall for a while on slow storage!
sync
fi
}
# BookSprite updates are staged and applied by the outer launch.sh supervisor.
# Never run upstream's in-place extractor: it cannot provide our rollback copy.
ko_update_check() { :; }
# NOTE: Keep doing an initial update check, in addition to one during the restart loop, so we can pickup potential updates of this very script...
ko_update_check
# If an update happened, and was successful, reexec
+368
View File
@@ -0,0 +1,368 @@
-- Standalone, no KOReader build required:
-- luajit spec/booksprite_otamanager_test.lua
-- Optional real TLS smoke test (LuaSocket + LuaSec, no update installation):
-- BOOKSPRITE_OTA_LIVE_TEST=1 luajit spec/booksprite_otamanager_test.lua
-- Override the live test's CA file with BOOKSPRITE_OTA_CA_BUNDLE.
-- All production files and package.loaded entries are restored on exit.
local lfs = require("lfs")
local real_http = require("socket.http")
local real_socket = require("socket")
local real_ssl = require("ssl")
local source = assert(lfs.currentdir()) .. "/frontend/ui/otamanager.lua"
local original_dir = assert(lfs.currentdir())
local directory = os.tmpname()
os.remove(directory)
assert(lfs.mkdir(directory))
for _, suffix in ipairs{ "/.adds", "/.adds/booksprite", "/.adds/booksprite/koreader" } do
assert(lfs.mkdir(directory .. suffix))
end
assert(lfs.chdir(directory .. "/.adds/booksprite/koreader"))
local function write(path, contents)
local file = assert(io.open(path, "wb"))
assert(file:write(contents))
assert(file:close())
end
local function read(path)
local file = io.open(path, "rb")
if not file then return end
local contents = file:read("*a")
file:close()
return contents
end
local saved = {}
local function replace(name, value)
if saved[name] == nil then saved[name] = { package.loaded[name] } end
package.loaded[name] = value
end
local available = 2 * 1024 * 1024 * 1024
local kobo, model = true, "kobo"
local shown, repaints = {}, 0
local widget = { new = function(_, value) return value end }
replace("ui/widget/confirmbox", widget)
replace("ui/widget/infomessage", widget)
replace("device", {
isKobo = function() return kobo end,
otaModel = function() return model, "ota" end,
})
replace("ui/network/manager", { runWhenOnline = function(_, fn) fn() end })
replace("ui/uimanager", {
show = function(_, value) shown[#shown + 1] = value end,
close = function() end,
forceRePaint = function() repaints = repaints + 1 end,
scheduleIn = function(_, _, fn) fn() end,
})
replace("libs/libkoreader-lfs", lfs)
replace("logger", { warn = function() end })
replace("util", { diskUsage = function() return { available = available } end })
replace("gettext", function(value) return value end)
replace("ffi/util", {
template = function(value, ...)
for i, replacement in ipairs{ ... } do
value = value:gsub("%%" .. i, tostring(replacement))
end
return value
end,
})
local digest_abc = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
-- Deterministic hash double; the bundled real SHA implementation is exercised
-- separately by the optional BOOKSPRITE_OTA_SHA2_FILE integration check.
replace("ffi/sha2", {
sha256 = function()
local data = ""
return function(chunk)
if chunk then data = data .. chunk; return end
return data == "abc" and digest_abc or string.rep("0", 64)
end
end,
})
local manager = dofile(source)
local original_request = manager.requestHTTPS
local manifest_url = "https://gitea.jameshall.xyz/exe.dev/booksprite/raw/branch/releases/stable.json"
local release_url = "https://gitea.jameshall.xyz/exe.dev/booksprite/releases/download/v0.1.1/booksprite-kobo.tar.gz"
local function manifest()
return { version = "0.1.1", target = "kobo", size = 3, sha256 = digest_abc, url = release_url }
end
local tests = 0
local function test(name, callback)
callback()
tests = tests + 1
io.stdout:write("ok ", tests, " - ", name, "\n")
end
local function contains(value, text)
assert(type(value) == "string" and value:find(text, 1, true), tostring(value))
end
local function failed(result, err)
assert(not result)
assert(type(err) == "string" and #err > 0)
end
local function cert(names)
return { extensions = function() return { ["2.5.29.17"] = { dNSName = names } } end }
end
local function fakeDownload(chunks)
manager.requestHTTPS = function(_, url, sink, limit)
assert(url == release_url)
local count = 0
for _, chunk in ipairs(chunks) do
count = count + #chunk
if count > limit then return nil, "size limit" end
local ok, err = sink(chunk)
if not ok then return nil, err end
end
return count
end
end
local ok, error_message = xpcall(function()
test("accept valid manifest and normalize digest", function()
local m = manifest()
m.sha256 = m.sha256:upper()
assert(manager:validateManifest(m).sha256 == digest_abc)
end)
test("reject wrong target, malformed fields, versions, and size limits", function()
for key, values in pairs{
target = { "kobov5", "kindle", false },
version = { "v0.1.1", "0.1", "0.1.1-beta", "01.2.3", "0.1.1000000000", false },
size = { 0, -1, 0.5, 250 * 1024 * 1024 + 1, math.huge, 0/0, "3", false },
sha256 = { "bad", string.rep("g", 64), false },
url = { false },
} do
for _, value in ipairs(values) do
local m = manifest()
m[key] = value
failed(manager:validateManifest(m))
end
end
failed(manager:validateManifest(nil))
failed(manager:validateManifest("not JSON"))
end)
test("reject URL injection, redirects, alternative hosts and traversal", function()
for _, url in ipairs{
"http://gitea.jameshall.xyz/exe.dev/booksprite/releases/download/v0.1.1/booksprite.tar.gz",
"https://gitea.jameshall.xyz.evil.test/exe.dev/booksprite/releases/download/v0.1.1/a.tar.gz",
"https://evil.test/a.tar.gz",
release_url .. "?redirect=https://evil.test",
release_url .. "#fragment",
release_url:gsub("/v0.1.1/", "/../"),
release_url:gsub("/v0.1.1/", "/%%2e%%2e/"),
release_url:gsub("/v0.1.1/", "/v0.1.1/extra/"),
release_url:gsub("/v0.1.1/", "/v0.1.1/'$(touch pwned)"),
release_url:gsub("gitea.jameshall.xyz/", "gitea.jameshall.xyz:443/"),
} do
local m = manifest()
m.url = url
failed(manager:validateManifest(m))
end
end)
test("require SAN exact hostname or single-label wildcard", function()
assert(manager:certificateMatchesHost(cert{ "gitea.jameshall.xyz" }))
assert(manager:certificateMatchesHost(cert{ "*.jameshall.xyz" }))
assert(manager:certificateMatchesHost(cert{ "GITEA.JAMESHALL.XYZ" }))
for _, names in ipairs{
{}, { "*.xyz" }, { "evil.jameshall.xyz" },
{ "gitea.jameshall.xyz.evil.test" }, { "*gitea.jameshall.xyz" },
{ "gitea.jameshall.xyz\0.evil.test" },
} do
assert(not manager:certificateMatchesHost(cert(names)))
end
assert(not manager:certificateMatchesHost(nil))
end)
test("TLS factory requires CA verification, SNI, and hostname", function()
local config, sni, closed
local tls = {
settimeout = function() return 1 end,
sni = function(_, value) sni = value; return 1 end,
dohandshake = function() return 1 end,
getpeercertificate = function() return cert{ "gitea.jameshall.xyz" } end,
close = function() closed = true; return 1 end,
send = function(_, data) return #data end,
receive = function() return "response" end,
}
replace("socket", { tcp = function() return {
settimeout = function() return 1 end,
connect = function(_, host, port)
assert(host == "gitea.jameshall.xyz" and port == 443)
return 1
end,
close = function() closed = true end,
} end })
replace("ssl", { wrap = function(_, params) config = params; return tls end })
local connection = assert(manager:createTLSConnection())
assert(connection:settimeout())
assert(connection:connect("gitea.jameshall.xyz", 443))
assert(config.verify == "peer" and config.cafile == "data/ca-bundle.crt")
assert(sni == "gitea.jameshall.xyz")
assert(connection:send("abc") == 3 and connection:receive() == "response")
connection:close()
assert(closed)
connection = assert(manager:createTLSConnection())
failed(connection:connect("evil.test", 443))
failed(connection:connect("gitea.jameshall.xyz", 80))
tls.getpeercertificate = function() return cert{ "evil.test" } end
failed(connection:connect("gitea.jameshall.xyz", 443))
replace("socket", real_socket)
replace("ssl", real_ssl)
end)
test("HTTPS sink limits bytes, rejects status/redirect, catches exceptions", function()
manager.requestHTTPS = original_request
local code, content, raises = 200, "abc", false
replace("socket.http", { request = function(req)
assert(req.redirect == false)
assert(req.headers["accept-encoding"] == "identity")
if raises then error("network exception") end
local accepted, err = req.sink(content)
if not accepted then return nil, err end
assert(req.sink(nil))
return 1, code
end })
assert(manager:requestHTTPS(manifest_url, function() return 1 end, 3, 30) == 3)
failed(manager:requestHTTPS(manifest_url, function() return 1 end, 2, 30))
for _, status in ipairs{ 301, 302, 307, 404, 500 } do
code = status
failed(manager:requestHTTPS(manifest_url, function() return 1 end, 3, 30))
end
code, raises = 200, true
failed(manager:requestHTTPS(manifest_url, function() return 1 end, 3, 30))
failed(manager:requestHTTPS("https://evil.test", function() return 1 end, 3, 30))
package.loaded["socket.http"].PROXY = "http://proxy.test"
failed(manager:requestHTTPS(manifest_url, function() return 1 end, 3, 30))
replace("socket.http", real_http)
end)
test("read fork version, numeric comparison, never downgrade", function()
local decoded = manifest()
replace("json", { decode = function() return decoded end })
manager.requestHTTPS = function(_, url, sink, limit)
assert(url == manifest_url and limit == 16 * 1024)
sink("{}")
return 2
end
write("booksprite-version", "0.1.0\n")
local result, installed = manager:checkUpdate()
assert(result.version == "0.1.1" and installed == "0.1.0")
write("booksprite-version", "0.1.9\n")
decoded.version = "0.1.10"
assert(manager:checkUpdate().version == "0.1.10")
decoded.version = "0.1.9"
assert(manager:checkUpdate() == false)
decoded.version = "0.1.2"
assert(manager:checkUpdate() == false)
write("booksprite-version", "upstream-v2026.07.1")
local _, _, err = manager:checkUpdate()
contains(err, "booksprite-version")
write("booksprite-version", "0.1.0\n")
end)
test("reject non-Kobo, kobov5, wrong installation, invalid JSON", function()
kobo = false
local result, _, err = manager:checkUpdate()
failed(result, err)
kobo, model = true, "kobov5"
result, _, err = manager:checkUpdate()
failed(result, err)
model = "kobo"
assert(lfs.chdir(".."))
result, _, err = manager:checkUpdate()
failed(result, err)
assert(lfs.chdir("koreader"))
replace("json", { decode = function() error("malformed JSON") end })
result, _, err = manager:checkUpdate()
failed(result, err)
end)
test("stage exact verified payload atomically", function()
fakeDownload{ "a", "bc" }
write("../pending.tar.gz.part", "stale partial")
assert(manager:downloadUpdate(manifest()))
assert(read("../pending.tar.gz") == "abc")
assert(not lfs.attributes("../pending.tar.gz.part"))
end)
test("preserve already-pending update without another download", function()
manager.requestHTTPS = function() error("must not download") end
failed(manager:downloadUpdate(manifest()))
assert(read("../pending.tar.gz") == "abc")
os.remove("../pending.tar.gz")
end)
test("wrong hash, truncated and oversized responses leave no pending/partial", function()
for _, chunks in ipairs{ { "abd" }, { "ab" }, { "abcd" } } do
fakeDownload(chunks)
failed(manager:downloadUpdate(manifest()))
assert(not lfs.attributes("../pending.tar.gz"))
assert(not lfs.attributes("../pending.tar.gz.part"))
end
end)
test("download exception cleans partial", function()
manager.requestHTTPS = function(_, _, sink)
sink("a")
error("interrupted")
end
failed(manager:downloadUpdate(manifest()))
assert(not lfs.attributes("../pending.tar.gz.part"))
end)
test("disk space check fails closed, with at least 1GiB reserve", function()
for _, space in ipairs{ 0, 1024 * 1024 * 1024 - 1, false } do
available = space or nil
failed(manager:downloadUpdate(manifest()))
assert(not lfs.attributes("../pending.tar.gz.part"))
end
available = 2 * 1024 * 1024 * 1024
end)
test("UI pending notice and menu contain only BookSprite stable", function()
write("../pending.tar.gz", "abc")
manager:fetchAndProcessUpdate()
contains(shown[#shown].text, "NickelMenu")
os.remove("../pending.tar.gz")
local menu = manager:getOTAMenuTable()
assert(menu.text == "BookSprite update" and #menu.sub_item_table == 2)
assert(menu.sub_item_table[2].text == "Channel: BookSprite stable")
end)
test("progress repaints before blocking and recovers from errors", function()
manager:runWithProgress("working", function() error("failure") end)
assert(repaints > 0 and not manager.busy)
contains(shown[#shown].text, "failed")
end)
if os.getenv("BOOKSPRITE_OTA_SHA2_FILE") then
test("real bundled SHA256 incremental API", function()
local sha = dofile(os.getenv("BOOKSPRITE_OTA_SHA2_FILE"))
local hash = sha.sha256()
hash("a"); hash("bc")
assert(hash() == digest_abc)
end)
end
if os.getenv("BOOKSPRITE_OTA_LIVE_TEST") == "1" then
test("live HTTPS handshake and authenticated HTTP response", function()
assert(lfs.mkdir("data"))
local ca_path = os.getenv("BOOKSPRITE_OTA_CA_BUNDLE") or "/etc/ssl/certs/ca-certificates.crt"
write("data/ca-bundle.crt", assert(read(ca_path)))
manager.requestHTTPS = original_request
local chunks = {}
local result, code = real_http.request{
url = "https://gitea.jameshall.xyz/api/v1/version",
redirect = false,
create = function() return manager:createTLSConnection() end,
sink = function(chunk) if chunk then chunks[#chunks + 1] = chunk end; return 1 end,
}
assert(result and tonumber(code) == 200, tostring(code))
contains(table.concat(chunks), "version")
local bytes, err = manager:requestHTTPS(manifest_url, function() return 1 end, 16 * 1024, 30)
-- A private/non-published manifest may return a safe 404, but the
-- preceding API call must always complete authenticated TLS.
assert(bytes or (type(err) == "string" and #err > 0))
end)
end
end, debug.traceback)
-- Explicit paths only; no recursive deletion or shell cleanup.
for _, path in ipairs{
"booksprite-version", "data/ca-bundle.crt", "../pending.tar.gz", "../pending.tar.gz.part",
} do os.remove(path) end
lfs.rmdir("data")
assert(lfs.chdir(original_dir))
for _, suffix in ipairs{ "/.adds/booksprite/koreader", "/.adds/booksprite", "/.adds", "" } do
assert(lfs.rmdir(directory .. suffix))
end
for name, value in pairs(saved) do package.loaded[name] = value[1] end
if not ok then error(error_message, 0) end
io.stdout:write("Passed ", tests, " BookSprite OTA tests.\n")