3 # Copyright (C) 2015 Network Time Foundation
6 # Original shell version:
7 # Copyright (C) 2014 Timothe Litt litt at acm dot org
9 # This script may be freely copied, used and modified providing that
10 # this notice and the copyright statement are included in all copies
11 # and derivative works. No warranty is offered, and use is entirely at
12 # your own risk. Bugfixes and improvements would be appreciated by the
17 use Digest::SHA qw(sha1_hex);
18 use File::Copy qw(move);
20 use Getopt::Long qw(:config auto_help no_ignore_case bundling);
25 # leap-seconds file manager/updater
27 # ########## Default configuration ##########
30 my $CRONJOB = $ENV{'CRONJOB'};
31 $CRONJOB = "" unless defined($CRONJOB);
36 # Where to get the file
38 # https://www.ietf.org/timezones/data/leap-seconds.list
39 # ftp://time.nist.gov/pub/leap-seconds.list
40 my $LEAPSRC="https://www.ietf.org/timezones/data/leap-seconds.list";
43 # How many times to try to download new file
47 # Where to find ntp config file
48 my $NTPCONF="/etc/ntp.conf";
50 # How long (in days) before expiration to get updated file
53 # How to restart NTP - older NTP: service ntpd? try-restart | condrestart
54 # Recent NTP checks for new file daily, so there's nothing to do
60 # Where to put temporary copy before it's validated
61 my $TMPFILE="/tmp/leap-seconds.$$.tmp";
66 # ###########################################
70 Usage: $0 [options] [leapfile]
72 Verifies and if necessary, updates leap-second definition file
74 All arguments are optional: Default (or current value) shown:
75 -s Specify the URL of the master copy to download
77 -d Specify the filename on the local system
79 -e Specify how long (in days) before expiration the file is to be
80 refreshed. Note that larger values imply more frequent refreshes.
82 -f Specify location of ntp.conf (used to make sure leapfile directive is
83 present and to default leapfile)
85 -F Force update even if current file is OK and not close to expiring.
86 -r Specify number of times to retry on get failure
88 -i Specify number of minutes between retries
90 -l Use syslog for output (Implied if CRONJOB is set)
91 -L Don't use syslog for output
92 -P Specify the syslog facility for logging
94 -t Name of temporary file used in validation
96 -q Only report errors to stdout
99 The following options are not (yet) implemented in the perl version:
102 -c Command to restart NTP after installing a new file
103 <none> - ntpd checks file daily
105 Prefer IPv4 or IPv6 (as specified) addresses, but use either
106 -z Specify path for utilities
108 -Z Only use system path
110 $0 will validate the file currently on the local system
112 Ordinarily, the file is found using the "leapfile" directive in $NTPCONF.
113 However, an alternate location can be specified on the command line.
115 If the file does not exist, is not valid, has expired, or is expiring soon,
116 a new copy will be downloaded. If the new copy validates, it is installed and
117 NTP is (optionally) restarted.
119 If the current file is acceptable, no download or restart occurs.
121 -c can also be used to invoke another script to perform administrative
122 functions, e.g. to copy the file to other local systems.
124 This can be run as a cron job. As the file is rarely updated, and leap
125 seconds are announced at least one month in advance (usually longer), it
126 need not be run more frequently than about once every three weeks.
128 For cron-friendly behavior, define CRONJOB=1 in the crontab.
133 # Default: Use syslog for logging if running under cron
135 my $SYSLOG = $CRONJOB;
157 $LOGFAC=$opt{P} if (defined($opt{P}));
158 $LEAPSRC=$opt{s} if (defined($opt{s}));
159 $PREFETCH=$opt{e} if (defined($opt{e}));
160 $NTPCONF=$opt{f} if (defined($opt{f}));
161 $FORCE="Y" if (defined($opt{F}));
162 $RESTART=$opt{c} if (defined($opt{c}));
163 $MAXTRIES=$opt{r} if (defined($opt{r}));
164 $INTERVAL=$opt{i} if (defined($opt{i}));
165 $TMPFILE=$opt{t} if (defined($opt{t}));
166 $SYSLOG="Y" if (defined($opt{l}));
167 $SYSLOG="" if (defined($opt{L}));
168 $QUIET="Y" if (defined($opt{q}));
169 $VERBOSE="Y" if (defined($opt{v}));
171 # export PATH="$PATHLIST$PATH"
175 openlog($0, 'pid', $LOGFAC);
178 my ($priority, $message) = @_;
180 # "priority" "message"
182 # Stdout unless syslog specified or logger isn't available
184 if ($SYSLOG eq "" or $LOGGER eq "") {
185 if ($QUIET ne "" and ( $priority eq "info" or $priority eq "notice" or $priority eq "debug" ) ) {
188 printf "%s: $message\n", uc $priority;
192 # Also log to stdout if cron job && notice or higher
193 if (($CRONJOB ne "" and ($priority ne "info" ) and ($priority ne "debug" )) || ($VERBOSE ne "")) {
194 # Log to stderr as well
195 print STDERR "$0: $priority: $message\n";
197 syslog($priority, $message);
201 # INTERVAL=$(( $INTERVAL *1 ))
203 # Validate a leap-seconds file checksum
205 # File format: (full description in files)
206 # # marks comments, except:
207 # #$ number : the NTP date of the last update
208 # #@ number : the NTP date that the file expires
209 # Date (seconds since 1900) leaps : leaps is the # of seconds to add for times >= Date
210 # Date lines have comments.
211 # #h hex hex hex hex hex is the SHA-1 checksum of the data & dates, excluding whitespace w/o leading zeroes
219 my ($file, $verbose) = @_;
225 # Remove comments, except those that are markers for last update,
228 unless (open(LF, $file)) {
229 warn "Can't open <$file>: $!\n";
230 print "Will try and create that file.\n";
244 $EXPIRES = $_ - 2208988800;
246 elsif (/^#h\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)\s+([[:xdigit:]]+)/) {
249 $FSHA = sprintf("%08s%08s%08s%08s%08s", $1, $2, $3, $4, $5);
260 print "Unexpected line: <$_>\n";
265 # Remove all white space
268 # Compute the SHA hash of the data, removing the marker and filename
269 # Computed in binary mode, which shouldn't matter since whitespace has been removed
271 my $DSHA = sha1_hex($data);
273 # Extract the file's hash. Restore any leading zeroes in hash segments.
275 if ( ( "$FSHA" ne "" ) && ( $FSHA eq $DSHA ) ) {
276 if ( $verbose ne "" ) {
277 logger("info", "Checksum of $file validated");
280 logger("error", "Checksum of $file is invalid:");
281 $FSHA="(no checksum record found in file)"
283 logger("error", "EXPECTED: $FSHA");
284 logger("error", "COMPUTED: $DSHA");
288 # Check the expiration date, converting NTP epoch to Unix epoch used by date
290 if ( $EXPIRES < time() ) {
291 logger("notice", "File expired on " . gmtime($EXPIRES));
299 -r $NTPCONF || die "Missing ntp configuration: $NTPCONF\n";
301 # Parse ntp.conf for leapfile directive
303 open(LF, $NTPCONF) || die "Can't open <$NTPCONF>: $!\n";
306 if (/^ *leapfile\s+"(\S+)"/) {
312 -s $LEAPFILE || warn "$NTPCONF specifies $LEAPFILE as a leapfile, which is empty.\n";
314 # Allow placing the file someplace else - testing
316 if ( defined $ARGV[0] ) {
317 if ( $ARGV[0] ne $LEAPFILE ) {
318 logger("notice", "Requested install to $ARGV[0], but $NTPCONF specifies $LEAPFILE");
320 $LEAPFILE = $ARGV[0];
323 # Verify the current file
324 # If it is missing, doesn't validate or expired
325 # Or is expiring soon
328 if ( $FORCE ne "" || verifySHA($LEAPFILE, $VERBOSE) || ( $EXPIRES lt ( $PREFETCH * 86400 + time() ) )) {
330 my $ff = File::Fetch->new(uri => $LEAPSRC) || die "Fetch failed.\n";
333 logger("info", "Attempting download from $LEAPSRC, try $TRY..")
335 my $where = $ff->fetch( to => '/tmp' );
338 logger("info", "Download of $LEAPSRC succeeded");
340 if ( verifySHA($where, $VERBOSE )) {
341 # There is no point in retrying, as the file on the
342 # server is almost certainly corrupt.
344 logger("warning", "Downloaded file $where rejected -- saved for diagnosis");
348 # While the shell script version will set correct permissions
349 # on temporary file, for the perl version that's harder, so
350 # for now at least one should run this script as the
353 # REFFILE="$LEAPFILE"
354 # if [ ! -f $LEAPFILE ]; then
355 # logger "notice" "$LEAPFILE was missing, creating new copy - check permissions"
357 # # Can't copy permissions from old file, copy from NTPCONF instead
360 # chmod --reference $REFFILE $TMPFILE
361 # chown --reference $REFFILE $TMPFILE
362 # ( which selinuxenabled && selinuxenabled && which chcon ) >/dev/null 2>&1
363 # if [ $? == 0 ] ; then
364 # chcon --reference $REFFILE $TMPFILE
367 # Replace current file with validated new one
369 if ( move $where, $LEAPFILE ) {
370 logger("notice", "Installed new $LEAPFILE from $LEAPSRC");
372 logger("error", "Install $where => $LEAPFILE failed -- saved for diagnosis: $!");
376 # Restart NTP (or whatever else is specified)
378 if ( $RESTART ne "" ) {
379 if ( $VERBOSE ne "" ) {
380 logger("info", "Attempting restart action: $RESTART");
384 #R="$( 2>&1 $RESTART )"
385 #if [ $? -eq 0 ]; then
386 # logger "notice" "Restart action succeeded"
387 # if [ -n "$VERBOSE" -a -n "$R" ]; then
391 # logger "error" "Restart action failed"
392 # if [ -n "$R" ]; then
393 # logger "error" "$R"
401 # Failed to download. See about trying again
404 if ( $TRY ge $MAXTRIES ) {
407 if ( $VERBOSE ne "" ) {
408 logger("info", "Waiting $INTERVAL minutes before retrying...");
410 sleep $INTERVAL * 60 ;
413 # Failed and out of retries
415 logger("warning", "Download from $LEAPSRC failed after $TRY attempts");
419 print "FORCE is <$FORCE>\n";
420 print "verifySHA is " . verifySHA($LEAPFILE, "") . "\n";
421 print "EXPIRES <$EXPIRES> vs ". ( $PREFETCH * 86400 + time() ) . "\n";
423 logger("info", "Not time to replace $LEAPFILE");