#!/bin/sh
#
# clockguard - refuse to believe an implausible wall clock.
#
# WHY THIS EXISTS
#
# The RB5009UPr+S+IN's Marvell Armada 7040 has an on-chip RTC driven by
# `armada38x-rtc`, but there is no battery on the board backing its registers.
# After a *power cut* those registers come up holding random bits, and
# CONFIG_RTC_HCTOSYS hands that value straight to the kernel as the initial wall
# clock. Both of the following are from real RB5009UPr+S+IN boots on this
# project's own hardware (artifacts/session-transcripts/, see notes/clock.md):
#
#   [ 1.210726] armada38x-rtc f2284000.rtc: setting system clock to
#               2097-07-24T02:20:57 UTC (4025470857)        <- in the future
#   [ 1.341530] armada38x-rtc f2284000.rtc: setting system clock to
#               2022-05-29T17:51:51 UTC (1653846711)        <- in the past
#
# Both bounds therefore have to be checked. The register is uninitialised, so
# what comes out can land anywhere, and it has now been seen on both sides of
# the present - a clock that is merely *wrong*, not specifically *late*.
#
# A warm reboot does NOT do this - the RTC keeps counting as long as the board
# has power - so the fault is intermittent and presents as "TLS certificates are
# not yet valid" / "logs are dated 2097" / "ntpd refuses to step the clock",
# never as anything that points at the RTC.
#
# WHY /etc/init.d/sysfixtime DOES NOT FIX IT
#
# sysfixtime (START=00, i.e. immediately before us) is the intended guard, but
# it is aimed at a different fault: it establishes a *floor*, never a ceiling.
# Its boot path is
#
#   hwclock_load                    # RTC -> system clock
#   maxtime="$(find_max_time)"      # newest mtime under /etc
#   [ "$(date +%s)" -lt "$maxtime" ] && date -s @$maxtime
#
# Note that the mtime comparison is NOT skipped when the RTC exists - it runs
# either way. Two consequences, and they point in opposite directions:
#
# 1. It only ever moves the clock FORWARD. A clock reading 2097 is not *less
#    than* the newest /etc mtime, so the test fails and the bogus time survives
#    untouched. That is by design: it is a floor, not a sanity check.
# 2. Worse, its reference is poisonable. find_max_time() takes the newest mtime
#    under /etc, and /etc sits on the overlay - so a file written during *this*
#    bad-clock boot carries an mtime years in the future. On a later cold start
#    that file *raises* the floor, and sysfixtime will then set the clock to the
#    garbage value itself, on a boot where the RTC came up perfectly sane. So it
#    can amplify the fault we are repairing, not merely fail to catch it.
#
# That is why the anchor here is BUILD_EPOCH from /etc/build_info, which lives
# in the read-only squashfs layer and is fixed at image build time. A bad clock
# cannot move that value, so it stays trustworthy however many bad-clock boots
# have already preceded this one.
#
# WHAT THIS DOES
#
# A cold-started router with no working RTC and no NTP has no way to know the
# wall clock at all. Whatever it claims must therefore lie between the moment
# its firmware was built and the last moment it was seen running with a clock it
# could trust. Anything outside that window is uninitialised hardware, and gets
# clamped back to the newest time we have actual evidence for - whether it came
# out too early or too late.
#
# The upper bound is deliberately loose (GRACE_YEARS below) because a unit that
# sat in a box, or one whose high-water mark went stale after a run of unclean
# shutdowns, must not be second-guessed. Garbage out of an unbacked RTC misses
# by decades, never by years, so it can never slip in underneath the allowance.
#
# SEE ALSO
#
#   /etc/init.d/clockguard  - runs this at START=01 (right after sysfixtime)
#   notes/clock.md          - measured behaviour and how to reproduce
#   scripts/test-clockguard.sh - decision-logic tests, no hardware needed

set -u

BUILD_INFO="${CLOCKGUARD_BUILD_INFO:-/etc/build_info}"
HWM="${CLOCKGUARD_HWM:-/etc/clockguard.hwm}"
RTC_DEV="${CLOCKGUARD_RTC_DEV:-/dev/rtc0}"
HWCLOCK="${CLOCKGUARD_HWCLOCK:-/sbin/hwclock}"

# How far past our newest evidence we are still willing to believe a clock.
# Five years, on purpose: see "The upper bound is deliberately loose" above.
GRACE_YEARS=5
GRACE=$((GRACE_YEARS * 365 * 86400))

MODE=fix
QUIET=0

while [ $# -gt 0 ]; do
	case "$1" in
		--fix)      MODE=fix ;;
		--check)    MODE=check ;;
		--ratchet)  MODE=ratchet ;;
		-q|--quiet) QUIET=1 ;;
		-h|--help)
			echo "usage: clockguard [--fix|--check|--ratchet] [-q]"
			echo "  --fix      (default) clamp an impossible clock to a defensible time"
			echo "  --check    report only; exit 1 if the clock is impossible"
			echo "  --ratchet  record a believable clock as the high-water mark"
			echo "  -q         suppress logging"
			echo
			echo "exit: 0 clock is believable (or was repaired)"
			echo "      1 clock is impossible and was not repaired"
			echo "      2 no reference time available, so no judgement was possible"
			exit 0 ;;
		*) echo "clockguard: unknown option: $1" >&2; exit 2 ;;
	esac
	shift
done

# Logging has to work at START=01, before logd exists. /dev/kmsg gets the line
# into dmesg (where anyone debugging a boot will already be looking); logger is
# best-effort and harmless when it silently has nowhere to go.
log() {
	[ "$QUIET" = 1 ] && return 0
	if [ -w /dev/kmsg ]; then
		printf 'clockguard: %s\n' "$*" > /dev/kmsg
	fi
	logger -t clockguard "$*" 2>/dev/null
	return 0
}

# The moment this firmware was built, baked in by build.sh. Everything we know
# about "what time is it allowed to be" is anchored here.
build_epoch() {
	local be=0
	if [ -r "$BUILD_INFO" ]; then
		# shellcheck source=/dev/null
		. "$BUILD_INFO"
		case "${BUILD_EPOCH:-}" in
			''|*[!0-9]*) be=0 ;;
			*) be="${BUILD_EPOCH}" ;;
		esac
	fi
	printf '%s\n' "$be"
}

read_hwm() {
	[ -r "$HWM" ] || return 1
	read -r v < "$HWM" || return 1
	case "$v" in ''|*[!0-9]*) return 1 ;; esac
	printf '%s\n' "$v"
}

save_hwm() {
	printf '%s\n' "$1" > "$HWM" 2>/dev/null || return 1
	chmod 0644 "$HWM" 2>/dev/null
	return 0
}

# The newest wall clock this device has actual evidence for: its own firmware
# build, raised by the high-water mark once a previous run got further.
reference_time() {
	ref="$(build_epoch)"
	hwm="$(read_hwm)" || hwm=0
	if [ "$hwm" -gt "$ref" ]; then
		ref="$hwm"
	fi
	printf '%s\n' "$ref"
}

main() {
	ref="$(reference_time)"
	now="$(date +%s)"

	case "$now" in
		''|*[!0-9]*)
			echo "clockguard: date(1) returned '$now', not a number" >&2
			exit 1 ;;
	esac

	if [ "$MODE" = ratchet ]; then
		# Shutdown: record the clock so the next cold start has a better
		# reference than the build date. Only ever write down a time we would
		# also have been willing to believe at boot - if NTP never synced and
		# the clock is still garbage, persisting it would poison every later
		# decision.
		prev="$(read_hwm)" || prev=0
		if [ "$ref" -gt 0 ] && [ "$now" -ge "$ref" ] &&
		   [ "$now" -le "$((ref + GRACE))" ] && [ "$now" -gt "$prev" ]; then
			if save_hwm "$now"; then
				log "recorded $now as the high-water mark for the next cold start"
			fi
		fi
		exit 0
	fi

	if [ "$ref" -le 0 ]; then
		# No BUILD_EPOCH. Say so out loud rather than silently skipping: a
		# skipped check looks exactly like a passing one at the next boot, and
		# this is what you would see on an image built by an older build.sh.
		log "no BUILD_EPOCH in $BUILD_INFO - cannot judge the clock, leaving it at $now"
		[ "$MODE" = check ] && echo "clockguard: no reference time available"
		exit 2
	fi

	lo="$ref"
	hi=$((ref + GRACE))

	if [ "$now" -ge "$lo" ] && [ "$now" -le "$hi" ]; then
		[ "$MODE" = check ] &&
			echo "clockguard: $now is believable (window $lo..$hi)"
		exit 0
	fi

	if [ "$MODE" = check ]; then
		echo "clockguard: $now is NOT believable (window $lo..$hi)"
		exit 1
	fi

	log "rejecting wall clock $now: outside the window this firmware can justify ($lo..$hi)"

	if date -s "@$lo" >/dev/null 2>&1; then
		log "clamped system clock to $lo ($(date -u '+%Y-%m-%dT%H:%M:%SZ' 2>/dev/null))"
	else
		log "could not set the system clock to $lo"
		exit 1
	fi

	# Push the corrected time back into the hardware. Best effort: if this
	# fails, the system clock is already right and only the *next* cold start
	# will need repair again, which is precisely the case this script is for.
	if [ -x "$HWCLOCK" ] && [ -e "$RTC_DEV" ]; then
		if "$HWCLOCK" -u -w -f "$RTC_DEV" >/dev/null 2>&1; then
			log "wrote the corrected time back to $RTC_DEV"
		else
			log "could not write back to $RTC_DEV (harmless, the system clock is already right)"
		fi
	fi

	exit 0
}

main
