Files
Programming-Contests/files/time/time_from_contest.sh
T
2026-10-15 20:44:05 -03:00

22 lines
1.0 KiB
Bash

#!/bin/bash
# Fallback for the clock. If chrony has no time server after two minutes of
# uptime (for instance when the campus network blocks NTP), the clock is set
# from the Date header of the contest site, which is accurate to the second.
CONF=/etc/contest-firewall
[ "$(cut -d. -f1 /proc/uptime)" -ge 120 ] || exit 0
if chronyc -n sources 2>/dev/null | grep -qE '^\^\*'; then
exit 0
fi
site=$(sed -e 's/#.*//' -e 's/[[:space:]]//g' "$CONF/allowed_domains.txt" | grep -m1 .)
# -k: certificates cannot be checked while the clock is far off
date_header=$(curl -skI --max-time 10 "https://$site/" | tr -d '\r' | sed -n 's/^[Dd]ate: //p')
[ -n "$date_header" ] || { logger -t time_from_contest "no answer from $site"; exit 1; }
server=$(date -d "$date_header" +%s) || exit 1
now=$(date +%s)
offset=$((server - now))
if [ "${offset#-}" -ge 2 ]; then
# The header has whole seconds: aim for the middle of the second
date -s "@$server.5" >/dev/null
logger -t time_from_contest "chrony has no time server; clock set from $site (was off by $offset s)"
fi