fix: close the update popup instead of racing to prevent it
Build / build (push) Successful in 46s

Blocking snu.lge.com in /etc/hosts never stopped the boot popup on a CX,
and the reason only showed up on the TV itself: /usr/sbin/update is a
systemd unit (webos-mbd.target) that runs its version check against
https://snu.lge.com/CheckSWAutoUpdate.laf 15-20 seconds before the
Homebrew Channel gets as far as running its init.d hooks. The check
therefore succeeds on every boot and the alert is already on screen
before any hosts entry exists. Homebrew Channel's own "block system
updates" toggle loses the same race.

Nothing running that late can win it: every systemd unit path is a
read-only overlay except tmpfs /run, and no persistent setting gates the
check - automaticUpdate, support/softwareUpdateEnable,
hotelMode/swUpdateEnable and .UpdateIsInprogress were each measured by
restarting the daemon and counting its requests.

So dismiss the popup instead. The boot hook recovers the alert id from
the updater's own log (_gAlertWindowId), which is the only way to reach
an alert that opened before we could subscribe - com.webos.notification
never reports it to a late subscriber and closeAllAlerts rejects every
source id it accepts. A companion alert-watch.sh then stays subscribed
for the rest of the session.

Also drop two things that were never true. There is no staged firmware
image driving the popup (the staging dir is empty at boot; the size the
daemon reports is in-memory only), and there is no update service to
stop - /etc/init is dead upstart leftovers on a systemd TV, so the old
stopServices layer printed "stopped update" while doing nothing.

  - rename the hook to 00-lgupdateblocker so run-parts runs it first,
    removing the legacy file on apply
  - add support/ and hotelMode/ to the scanned settings categories
  - stop matching "ota" inside screenRotation, which would have switched
    screen rotation off
  - kill the watcher by process group, and make its TERM trap exit - a
    trap that only returns resumes the script, which then re-subscribes

Verified on an LG OLED55CX8LB (webOS 5, 04.60.65): after a reboot the
boot log records "dismissed update popup
com.webos.service.update-1788650782451", matching the id the updater
logged that boot. Raised 01:26:22, closed 01:26:37 - so it is visible
for ~15s and then goes away on its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Rene Kievits
2026-09-06 01:39:45 +02:00
co-authored by Claude Opus 5
parent ae8229588e
commit ef8b6b96c4
8 changed files with 418 additions and 103 deletions
+239 -70
View File
@@ -4,15 +4,29 @@
* Everything this service does is reversible and is applied in layers:
*
* 1. hosts - point LG's firmware update servers at 127.0.0.1
* 2. purge - delete the firmware image the TV already staged
* 3. lock - bind-mount an empty read-only dir over the staging dir
* 4. settings - switch off the update-related com.webos.settingsservice keys
* 5. services - stop the update related upstart jobs (advanced, opt-in)
* 2. dismiss - close the "software update available" alert at boot
* 3. purge - delete the firmware image the TV already staged
* 4. lock - bind-mount an empty read-only dir over the staging dir
* 5. settings - switch off the update-related com.webos.settingsservice keys
*
* / is read-only on webOS, and /tmp, /etc and the mount namespace are reset on
* every boot, so each layer is re-applied by a boot hook script dropped into
* /var/lib/webosbrew/init.d (run by the Homebrew Channel startup script).
*
* Why the hosts block alone is not enough: /usr/sbin/update is started by
* systemd (webos-mbd.target) and runs its version check against snu.lge.com
* roughly 20 seconds before the Homebrew Channel gets as far as running the
* hooks in init.d. On a CX that check therefore *succeeds* on every boot and
* the popup is already on screen by the time anything of ours runs - which is
* also why the Homebrew Channel's own "block system updates" toggle does not
* stop it. Nothing persistent gates that check (automaticUpdate,
* support/softwareUpdateEnable, hotelMode/swUpdateEnable and the
* .UpdateIsInprogress flag were all measured to make no difference), and there
* is no writable directory early enough in the boot to win the race: every
* systemd unit path except /run is a read-only overlay. So the popup is closed
* instead of prevented, and the hosts block stops the download and every
* later check.
*
* Written in ES5 without dependencies - it runs on the TV's own node with the
* platform-provided webos-service module and nothing else.
*/
@@ -37,7 +51,13 @@ var SETTINGS_BACKUP_PATH = STATE_DIR + '/settings-backup.json';
var EMPTY_DIR = STATE_DIR + '/empty';
var BOOT_LOG_PATH = STATE_DIR + '/boot.log';
var BOOT_HOOK_DIR = '/var/lib/webosbrew/init.d';
var BOOT_HOOK_PATH = BOOT_HOOK_DIR + '/' + SLUG;
/* run-parts runs the hooks in lexical order and the popup is already on screen
* by then, so sort ahead of the other homebrew hooks. Older versions installed
* the hook under the bare slug; installBootHook removes that leftover. */
var BOOT_HOOK_PATH = BOOT_HOOK_DIR + '/00-' + SLUG;
var LEGACY_BOOT_HOOK_PATH = BOOT_HOOK_DIR + '/' + SLUG;
var WATCHER_PATH = STATE_DIR + '/alert-watch.sh';
var WATCHER_PID_PATH = '/tmp/' + SLUG + '-watch.pid';
var HOSTS_PATH = '/etc/hosts';
var HOSTS_TMP = '/tmp/' + SLUG + '-hosts';
@@ -56,18 +76,31 @@ var CACHE_DIRS = [
];
var CACHE_GUARD = '/mnt/lg/';
var UPSTART_DIR = '/etc/init';
var JOB_PATTERN = /(swupdate|softwareupdate|firmware|fota|update|upgrade|nsu)/i;
/* /usr/sbin/update logs its own alert id here as
* _NSU_CreateAlertCallback - _gAlertWindowId : com.webos.service.update-<ms>
* which is the only way to learn the id of a popup that opened before we did:
* com.webos.notification only pushes alerts to clients already subscribed, and
* closeAllAlerts rejects every source id we can pass it. */
var UPDATE_DAEMON_LOG = '/tmp/var/log/update.log';
var ALERT_ID_PATTERN = 'com\\.webos\\.service\\.update-[0-9]*';
var SETTINGS_CATEGORIES = ['option', 'general', 'network', 'commercial'];
var SETTINGS_KEY_PATTERN = /(update|upgrade|firmware|ota)/i;
var SETTINGS_CATEGORIES = ['option', 'general', 'network', 'commercial', 'support', 'hotelMode'];
var SETTINGS_KEY_PATTERN = /(update|upgrade|firmware)/i;
/* "ota" and "nsu" are substrings of perfectly innocent keys - screenRotation,
* consumerMode - and switching one of those off would be a nasty surprise, so
* only match them at a word or camelCase boundary. */
var SETTINGS_ABBREV_PATTERN = /(^|[^A-Za-z])(ota|nsu)|Ota|OTA|Nsu|NSU/;
function isUpdateKey(key) {
return SETTINGS_KEY_PATTERN.test(key) || SETTINGS_ABBREV_PATTERN.test(key);
}
var DEFAULT_CONFIG = {
blockHosts: true,
dismissPopup: true,
purgeCache: true,
lockCache: false,
disableSettings: true,
stopServices: false
disableSettings: true
};
var CONFIG_KEYS = Object.keys(DEFAULT_CONFIG);
@@ -411,34 +444,83 @@ function unlockCache(log) {
});
}
/* ----------------------------------------------------------- upstart jobs */
/* ------------------------------------------------------------ update popup */
function discoverJobs() {
var entries;
try {
entries = fs.readdirSync(UPSTART_DIR);
} catch (err) {
return [];
}
return entries
.filter(function (entry) {
return /\.conf$/.test(entry) && JOB_PATTERN.test(entry);
})
.map(function (entry) {
return entry.replace(/\.conf$/, '');
})
.sort();
/* Id of the last update alert the daemon raised this boot, recovered from its
* own log. /tmp is wiped at boot, so at boot time this is the popup currently
* on screen; later in a session it may already have been closed. Closing an
* alert that is gone is a no-op, so it is safe either way. */
function lastAlertId() {
var log = readFile(UPDATE_DAEMON_LOG, '');
var matches = log.match(/_gAlertWindowId\s*:\s*(com\.webos\.service\.update-[0-9]+)/g);
if (!matches || !matches.length) return null;
return matches[matches.length - 1].replace(/^.*:\s*/, '');
}
function stopJobs(jobs, log) {
if (!jobs.length) {
log.add('no update-related upstart jobs found');
function closeAlert(alertId, callback) {
callLuna('luna://com.webos.notification/closeAlert', { alertId: alertId }, callback);
}
function watcherPid() {
var pid = parseInt(readFile(WATCHER_PID_PATH, ''), 10);
if (!pid || !exists('/proc/' + pid)) return 0;
/* the pid file survives a crash; make sure it is still our watcher */
var cmdline = readFile('/proc/' + pid + '/cmdline', '');
return cmdline.indexOf('alert-watch') >= 0 ? pid : 0;
}
function stopWatcher() {
var pid = watcherPid();
if (!pid) return false;
/* the watcher is a pipeline in its own session (setsid / detached spawn), so
* kill the whole group - killing the script alone orphans its luna-send */
sh('kill -TERM -' + pid + ' 2>/dev/null || kill ' + pid);
try {
fs.unlinkSync(WATCHER_PID_PATH);
} catch (err) {
/* already gone */
}
return true;
}
function startWatcher(log) {
if (watcherPid()) {
log.add('alert watcher already running');
return;
}
jobs.forEach(function (job) {
var res = sh('initctl stop ' + job);
if (!res.ok) res = sh('stop ' + job);
log.add(res.ok ? 'stopped upstart job ' + job : '! could not stop ' + job + ': ' + res.output);
if (!exists(WATCHER_PATH)) {
log.add('! alert watcher missing at ' + WATCHER_PATH);
return;
}
try {
var child = childProcess.spawn('/bin/sh', [WATCHER_PATH], {
detached: true,
stdio: 'ignore'
});
child.unref();
log.add('alert watcher started');
} catch (err) {
log.add('! could not start alert watcher: ' + err.message);
}
}
/* Close a popup that is on screen right now, then keep watching for the next
* one. Used by apply(); at boot the hook does the same thing in shell. */
function dismissPopup(log, done) {
var alertId = lastAlertId();
if (!alertId) {
log.add('no update popup raised this boot');
startWatcher(log);
return done();
}
closeAlert(alertId, function (res) {
log.add(
res && res.returnValue
? 'closed update popup ' + alertId
: '! could not close ' + alertId + ': ' + ((res && res.errorText) || 'no response')
);
startWatcher(log);
done();
});
}
@@ -495,7 +577,7 @@ function discoverSettings(callback) {
callLuna('luna://com.webos.settingsservice/getSystemSettings', { category: category }, function (payload) {
var settings = (payload && payload.settings) || {};
Object.keys(settings).forEach(function (key) {
if (!SETTINGS_KEY_PATTERN.test(key)) return;
if (!isUpdateKey(key)) return;
found.push({
category: category,
key: key,
@@ -610,7 +692,7 @@ function restoreSettings(log, callback) {
/* -------------------------------------------------------------- boot hook */
function bootHookScript(config, domains, jobs) {
function bootHookScript(config, domains) {
return [
'#!/bin/sh',
'# LG Update Blocker boot hook - generated by ' + pkgInfo.name + ' v' + pkgInfo.version + '.',
@@ -619,18 +701,39 @@ function bootHookScript(config, domains, jobs) {
'STATE=' + STATE_DIR,
'LOG=' + BOOT_LOG_PATH,
'HOSTS_TMP=' + HOSTS_TMP,
'WATCHER=' + WATCHER_PATH,
'BLOCK_HOSTS=' + (config.blockHosts ? 1 : 0),
'DISMISS_POPUP=' + (config.dismissPopup ? 1 : 0),
'PURGE_CACHE=' + (config.purgeCache ? 1 : 0),
'LOCK_CACHE=' + (config.lockCache ? 1 : 0),
'STOP_SERVICES=' + (config.stopServices ? 1 : 0),
'CACHE_DIRS="' + CACHE_DIRS.join(' ') + '"',
'JOBS="' + jobs.join(' ') + '"',
'',
'mkdir -p "$STATE"',
'if [ -f "$LOG" ] && [ "$(wc -c < "$LOG")" -gt 65536 ]; then rm -f "$LOG"; fi',
'exec >>"$LOG" 2>&1',
'echo "--- $(date) LG Update Blocker ---"',
'',
'# First, because by now the popup has been on screen for ~20 seconds: the',
'# updater runs its version check from webos-mbd.target, long before the',
'# Homebrew Channel gets round to running these hooks.',
'if [ "$DISMISS_POPUP" = 1 ]; then',
' id=$(sed -n \'s/.*_gAlertWindowId : \\(' + ALERT_ID_PATTERN + '\\).*/\\1/p\' \\',
' ' + UPDATE_DAEMON_LOG + ' 2>/dev/null | tail -1)',
' if [ -n "$id" ] && luna-send -t 1 -f luna://com.webos.notification/closeAlert \\',
' "{\\"alertId\\":\\"$id\\"}" >/dev/null 2>&1; then',
' echo "dismissed update popup $id"',
' fi',
' # and stay subscribed for the rest of the session in case it comes back',
' if [ -x "$WATCHER" ]; then',
' if command -v setsid >/dev/null 2>&1; then',
' setsid "$WATCHER" >/dev/null 2>&1 </dev/null &',
' else',
' "$WATCHER" >/dev/null 2>&1 </dev/null &',
' fi',
' echo "alert watcher started"',
' fi',
'fi',
'',
'if [ "$BLOCK_HOSTS" = 1 ] && [ -f "$STATE/hosts.txt" ]; then',
' if ! (: >> /etc/hosts) 2>/dev/null; then',
' cp /etc/hosts "$HOSTS_TMP" && chmod 644 "$HOSTS_TMP" \\',
@@ -682,42 +785,99 @@ function bootHookScript(config, domains, jobs) {
' done',
'fi',
'',
'if [ "$STOP_SERVICES" = 1 ] && [ -n "$JOBS" ]; then',
' for job in $JOBS; do',
' if initctl stop "$job" >/dev/null 2>&1 || stop "$job" >/dev/null 2>&1; then',
' echo "stopped $job"',
' else',
' echo "could not stop $job (not running?)"',
' fi',
' done',
'fi',
'',
'echo "done"',
''
].join('\n');
}
function installBootHook(config, jobs, log) {
/* Long-lived companion to the boot hook: subscribes to the notification
* manager and closes update alerts as they open. Kept as a separate file so
* the hook itself stays a short, ordinary run-parts script. */
function watcherScript() {
return [
'#!/bin/sh',
'# LG Update Blocker alert watcher - generated by ' + pkgInfo.name + ' v' + pkgInfo.version + '.',
'# Closes LG\'s "a new software version is available" alert as it opens.',
'',
'LOG=' + BOOT_LOG_PATH,
'PIDFILE=' + WATCHER_PID_PATH,
'',
'echo $$ > "$PIDFILE"',
'# the INT/TERM handler has to exit explicitly: a trap that just returns',
'# resumes the script, which would then re-subscribe and outlive the kill',
'trap \'rm -f "$PIDFILE"\' EXIT',
'trap \'rm -f "$PIDFILE"; exit 0\' INT TERM',
'',
'note() { echo "$(date) $*" >> "$LOG"; }',
'',
'close_alert() {',
' [ -n "$1" ] || return 1',
' luna-send -t 1 -f luna://com.webos.notification/closeAlert \\',
' "{\\"alertId\\":\\"$1\\"}" >/dev/null 2>&1',
'}',
'',
'# getAlertNotification only pushes to clients that were already subscribed,',
'# so it never reports the popup that is on screen right now - and',
'# closeAllAlerts rejects every source id it accepts arguments for. The',
'# subscription below therefore only covers alerts raised from now on; the',
'# boot hook handles the one already open, using the updater\'s own log.',
'while :; do',
' luna-send -i -f luna://com.webos.notification/getAlertNotification \\',
' \'{"subscribe":true}\' 2>/dev/null |',
' while read -r line; do',
' case "$line" in',
' *com.webos.service.update-*) ;;',
' *) continue ;;',
' esac',
' id=$(echo "$line" | sed -n \'s/.*\\(' + ALERT_ID_PATTERN + '\\).*/\\1/p\')',
' close_alert "$id" || continue',
' # one line per popup, not per notification the bus repeats',
' [ "$id" = "$last" ] && continue',
' last=$id',
' note "dismissed update popup $id"',
' done',
' # the bus dropped us; wait before re-subscribing rather than spinning',
' sleep 30',
'done',
''
].join('\n');
}
function installBootHook(config, log) {
var domains = readDomains();
mkdirp(STATE_DIR);
mkdirp(BOOT_HOOK_DIR);
fs.writeFileSync(HOSTS_LIST_PATH, domains.join('\n') + '\n');
fs.writeFileSync(BOOT_HOOK_PATH, bootHookScript(config, domains, jobs));
fs.writeFileSync(WATCHER_PATH, watcherScript());
fs.chmodSync(WATCHER_PATH, parseInt('755', 8));
fs.writeFileSync(BOOT_HOOK_PATH, bootHookScript(config, domains));
fs.chmodSync(BOOT_HOOK_PATH, parseInt('755', 8));
log.add('boot hook installed at ' + BOOT_HOOK_PATH);
/* versions before 1.1 installed the hook under the bare slug, which
* run-parts would then run a second time */
if (exists(LEGACY_BOOT_HOOK_PATH)) {
try {
fs.unlinkSync(LEGACY_BOOT_HOOK_PATH);
log.add('removed old boot hook ' + LEGACY_BOOT_HOOK_PATH);
} catch (err) {
log.add('! could not remove old boot hook: ' + err.message);
}
}
}
function removeBootHook(log) {
if (!exists(BOOT_HOOK_PATH)) {
log.add('no boot hook installed');
return;
}
try {
fs.unlinkSync(BOOT_HOOK_PATH);
log.add('removed boot hook ' + BOOT_HOOK_PATH);
} catch (err) {
log.add('! could not remove boot hook: ' + err.message);
}
var removed = [BOOT_HOOK_PATH, LEGACY_BOOT_HOOK_PATH].filter(function (target) {
if (!exists(target)) return false;
try {
fs.unlinkSync(target);
return true;
} catch (err) {
log.add('! could not remove boot hook: ' + err.message);
return false;
}
});
log.add(removed.length ? 'removed boot hook ' + removed.join(', ') : 'no boot hook installed');
}
/* ---------------------------------------------------------------- methods */
@@ -736,7 +896,10 @@ function baseStatus() {
totalDomains: readDomains().length
},
cache: cacheStatus(),
jobs: discoverJobs(),
popup: {
lastAlertId: lastAlertId(),
watcherPid: watcherPid()
},
bootHook: {
path: BOOT_HOOK_PATH,
installed: exists(BOOT_HOOK_PATH)
@@ -784,13 +947,8 @@ service.register('apply', function (message) {
unlockCache(log);
}
var jobs = discoverJobs();
if (config.stopServices) {
stopJobs(jobs, log);
}
if (anyEnabled(config)) {
installBootHook(config, config.stopServices ? jobs : [], log);
installBootHook(config, log);
} else {
removeBootHook(log);
}
@@ -805,10 +963,19 @@ service.register('apply', function (message) {
message.respond({ returnValue: true, log: log.lines, config: config, status: baseStatus() });
}
function afterSettings() {
if (config.dismissPopup) {
dismissPopup(log, finish);
} else {
if (stopWatcher()) log.add('alert watcher stopped');
finish();
}
}
if (config.disableSettings) {
disableSettings(log, finish);
disableSettings(log, afterSettings);
} else {
restoreSettings(log, finish);
restoreSettings(log, afterSettings);
}
});
@@ -827,6 +994,7 @@ service.register('revert', function (message) {
try {
removeHosts(log);
unlockCache(log);
if (stopWatcher()) log.add('alert watcher stopped');
removeBootHook(log);
mkdirp(STATE_DIR);
writeJson(CONFIG_PATH, config);
@@ -835,7 +1003,7 @@ service.register('revert', function (message) {
}
restoreSettings(log, function () {
log.add('everything reverted; stopped services come back after a reboot');
log.add('everything reverted - the update popup will be back on the next boot');
message.respond({ returnValue: true, log: log.lines, config: config, status: baseStatus() });
});
});
@@ -860,6 +1028,7 @@ service.register('diagnostics', function (message) {
osInfo: readJson('/var/run/nyx/os_info.json', null),
hostsFile: readFile(HOSTS_PATH, '(unreadable)').split('\n').slice(-40).join('\n'),
bootLog: readFile(BOOT_LOG_PATH, '(no boot log yet)').split('\n').slice(-40).join('\n'),
updateLog: readFile(UPDATE_DAEMON_LOG, '(no update log)').split('\n').slice(-40).join('\n'),
mounts: mountTargets().filter(function (target) {
return target === HOSTS_PATH || target.indexOf('/mnt/lg') === 0;
})