fix: support BusyBox process snapshots for stale lock recovery

This commit is contained in:
2026-10-14 18:33:41 +08:00
parent 6945095222
commit 568e5d6b7d
2 changed files with 97 additions and 11 deletions
+19 -11
View File
@@ -382,16 +382,24 @@ lock_process_state() {
# A live reused PID is deliberately treated as occupied. Never kill an # A live reused PID is deliberately treated as occupied. Never kill an
# owner or infer staleness from its executable name/start-time mismatch. # owner or infer staleness from its executable name/start-time mismatch.
if kill -0 "$lock_pid" 2>/dev/null; then lock_process=live; return; fi if kill -0 "$lock_pid" 2>/dev/null; then lock_process=live; return; fi
# kill -0 can fail for permissions. Require a working process query before # kill -0 can fail for permissions. Require a successful all-process PID
# declaring absence; unavailable/unsupported ps fails closed. # snapshot before declaring absence. GNU/BSD accept -A; BusyBox ps does not
command -v ps >/dev/null 2>&1 || return 0 # in every build, but its default selection includes all visible processes.
self_pid=$(ps -p "$$" -o pid= 2>/dev/null | tr -d ' ') || return 0 # Do not fall back to plain "ps -o pid": GNU's default selection is narrower.
[ "$self_pid" = "$$" ] || return 0 if process_pids=$(ps -A -o pid 2>/dev/null); then :
process_status=0 elif command -v busybox >/dev/null 2>&1 && process_pids=$(busybox ps -o pid 2>/dev/null); then :
process_pid=$(ps -p "$lock_pid" -o pid= 2>/dev/null) || process_status=$? else return 0; fi
process_pid=$(printf '%s' "$process_pid" | tr -d ' ') # Verify the complete output, including our own PID; failed, empty or
if [ "$process_status" = 0 ] && [ "$process_pid" = "$lock_pid" ]; then lock_process=live # malformed queries never turn an uncertain owner into a stale lock.
elif [ "$process_status" = 1 ] && [ -z "$process_pid" ]; then lock_process=dead; fi lock_process=$(printf '%s\n' "$process_pids" | awk -v own="$$" -v owner="$lock_pid" '
NR==1 {if(NF!=1 || $1!="PID") bad=1; next}
NF!=1 || $1 !~ /^[1-9][0-9]*$/ || length($1)>10 || $1+0>2147483647 {bad=1; next}
$1==own {self=1}
$1==owner {live=1}
END {if(bad || !self) print "unknown"; else if(live) print "live"; else print "dead"}
')
# Recheck after the snapshot: a PID may have appeared while ps was running.
if [ "$lock_process" = dead ] && kill -0 "$lock_pid" 2>/dev/null; then lock_process=live; fi
} }
acquire_lock() { acquire_lock() {
lock_recovered=no lock_recovered=no
@@ -1600,7 +1608,7 @@ sync_keys() {
validate_response ); then accepted=yes; accepted_source=$source_url; break; fi validate_response ); then accepted=yes; accepted_source=$source_url; break; fi
source_failure=validation source_failure=validation
fi fi
[ "$source_failure" = retrieval ] && [ "$source_attempt" -lt 5 ] || break if [ "$source_failure" != retrieval ] || [ "$source_attempt" -ge 5 ]; then break; fi
case $source_attempt in 1) retry_delay=1 ;; 2) retry_delay=3 ;; 3) retry_delay=8 ;; 4) retry_delay=12 ;; esac case $source_attempt in 1) retry_delay=1 ;; 2) retry_delay=3 ;; 3) retry_delay=8 ;; 4) retry_delay=12 ;; esac
say "Retrieval attempt $source_attempt/5 failed for $source_url; retrying in ${retry_delay}s." >&2 say "Retrieval attempt $source_attempt/5 failed for $source_url; retrying in ${retry_delay}s." >&2
sleep "$retry_delay" sleep "$retry_delay"
+78
View File
@@ -23,6 +23,10 @@ import errno
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
SOURCE = (ROOT / 'conf-sshd.sh').read_text() SOURCE = (ROOT / 'conf-sshd.sh').read_text()
SHELL = shlex.split(os.environ.get('CONF_SSHD_TEST_SHELL', '/bin/sh')) SHELL = shlex.split(os.environ.get('CONF_SSHD_TEST_SHELL', '/bin/sh'))
# Keep the selected real shell independent of test-specific PATH mocks (notably
# the busybox command mock used to exercise its process-list fallback).
if SHELL and not os.path.isabs(SHELL[0]):
SHELL[0] = shutil.which(SHELL[0]) or SHELL[0]
ORIGIN = 'https://keys.example.test' ORIGIN = 'https://keys.example.test'
SCRIPT = SOURCE.replace('@@BASE_URL@@', ORIGIN).replace('@@DEFAULT_CRON@@', '*/15 * * * *').replace('@@DEFAULT_GPG_VERIFY@@', 'off').replace('@@DEFAULT_GPG_FINGERPRINT@@', '').replace('@@DEFAULT_GPG_PIN_MODE@@', 'primary').replace('@@DEFAULT_LIST_ID@@', '').replace('@@DEFAULT_GPG_EMAIL@@', '') SCRIPT = SOURCE.replace('@@BASE_URL@@', ORIGIN).replace('@@DEFAULT_CRON@@', '*/15 * * * *').replace('@@DEFAULT_GPG_VERIFY@@', 'off').replace('@@DEFAULT_GPG_FINGERPRINT@@', '').replace('@@DEFAULT_GPG_PIN_MODE@@', 'primary').replace('@@DEFAULT_LIST_ID@@', '').replace('@@DEFAULT_GPG_EMAIL@@', '')
KEY = (ROOT / 'tests/fixtures/keys.pub').read_bytes().strip() + b'\n' KEY = (ROOT / 'tests/fixtures/keys.pub').read_bytes().strip() + b'\n'
@@ -636,10 +640,84 @@ fi
shutil.rmtree(lock) shutil.rmtree(lock)
lock = self.make_lock() lock = self.make_lock()
self.mock('ps', '#!/bin/sh\nexit 2\n') self.mock('ps', '#!/bin/sh\nexit 2\n')
self.mock('busybox', '#!/bin/sh\nexit 2\n')
self.run_script('-o', ok=False) self.run_script('-o', ok=False)
self.assertEqual((lock / 'pid').read_text(), '2147483647') self.assertEqual((lock / 'pid').read_text(), '2147483647')
self.assertEqual(self.calls.read_text(), '') self.assertEqual(self.calls.read_text(), '')
def mock_busybox_process_listing(self, listing=None, status=0):
# BusyBox standalone ash may resolve the ps applet before PATH and its
# ps lacks -p/-A. Simulate those options on every installed shell too.
self.mock('ps', '''#!/bin/sh
printf 'ps %s\\n' "$*" >> "$TEST_CALLS"
exit 1
''')
body = 'exec /bin/ps -A -o pid' if listing is None else (
'printf \'%s\\n\' ' + shlex.quote(listing) + '\nexit ' + str(status))
self.mock('busybox', '''#!/bin/sh
printf 'busybox %s\\n' "$*" >> "$TEST_CALLS"
[ "$*" = 'ps -o pid' ] || exit 2
''' + body + '\n')
def test_full_process_selection_succeeds_without_busybox_fallback(self):
self.make_lock()
self.mock('ps', '''#!/bin/sh
printf 'ps %s\\n' "$*" >> "$TEST_CALLS"
[ "$*" = '-A -o pid' ] || exit 2
exec /bin/ps "$@"
''')
self.mock('busybox', '#!/bin/sh\necho UNEXPECTED busybox fallback >> "$TEST_CALLS"\nexit 2\n')
self.run_script('-o')
self.assertIn('ps -A -o pid\n', self.calls.read_text())
self.assertEqual(len(self.fetch_calls()), 1)
self.assert_clean()
def test_nonzero_or_corrupt_full_snapshot_still_fails_closed(self):
for mutation in ('exit 1', "printf 'not-a-pid\\n'", "printf '1 extra-column\\n'"):
with self.subTest(mutation=mutation):
lock = self.make_lock()
self.mock('ps', '#!/bin/sh\n/bin/ps -A -o pid\n' + mutation + '\n')
self.mock('busybox', '#!/bin/sh\nexit 2\n')
result = self.run_script('-o', ok=False)
self.assertIn('Cannot prove', result.stderr)
self.assertEqual((lock / 'pid').read_text(), '2147483647')
self.assertFalse((lock / 'reclaim').exists())
shutil.rmtree(lock)
self.assertEqual(self.fetch_calls(), [])
def test_busybox_ps_without_selection_flags_recovers_stale_lock(self):
self.make_lock()
self.mock_busybox_process_listing()
self.run_script('-o')
self.assertIn('ps -A -o pid\n', self.calls.read_text())
self.assertIn('busybox ps -o pid\n', self.calls.read_text())
self.assertEqual(len(self.fetch_calls()), 1)
self.assert_clean()
def test_process_snapshot_keeps_live_pid_when_kill_probe_is_denied(self):
lock = self.make_lock(str(os.getpid()))
self.mock('kill', '#!/bin/sh\nexit 1\n')
self.mock_busybox_process_listing()
result = self.run_script('-o')
self.assertIn('skipping', result.stdout)
self.assertEqual((lock / 'pid').read_text(), str(os.getpid()))
self.assertEqual(self.fetch_calls(), [])
self.assertFalse((lock / 'reclaim').exists())
def test_failed_empty_or_malformed_process_snapshots_never_reap(self):
for listing, status in [('', 0), ('PID\n', 0), ('PID\n1\n', 0),
('PID\nnot-a-pid\n', 0), ('PID\n2147483648\n', 0),
('PID\n1 extra-column\n', 0), ('PID\n1\n', 1)]:
with self.subTest(listing=listing, status=status):
lock = self.make_lock()
self.mock_busybox_process_listing(listing, status)
result = self.run_script('-o', ok=False)
self.assertIn('Cannot prove', result.stderr)
self.assertEqual((lock / 'pid').read_text(), '2147483647')
self.assertFalse((lock / 'reclaim').exists())
self.assertEqual(self.fetch_calls(), [])
shutil.rmtree(lock)
def test_malicious_lock_paths_are_rejected_without_touching_targets(self): def test_malicious_lock_paths_are_rejected_without_touching_targets(self):
outside = self.root / 'outside-lock' outside = self.root / 'outside-lock'
outside.mkdir(mode=0o700) outside.mkdir(mode=0o700)