File: ntpleapfetch

package info (click to toggle)
ntpsec 1.2.0%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 10,044 kB
  • sloc: ansic: 60,737; python: 31,610; sh: 1,494; yacc: 1,291; makefile: 176; javascript: 138
file content (478 lines) | stat: -rwxr-xr-x 13,719 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
#! /bin/sh

# Copyright (C) 2014 Timothe Litt litt at acm dot org
# Modified 20180105 Sanjeev Gupta ghane0@gmail.com
#
# SPDX-License-Identifier: BSD-2-Clause
#
# Bugfixes and improvements would be appreciated by the author.

# leap-seconds file manager/updater

# Depends on:
#  wget sed, tr, shasum/sha1sum, logger
#
# This file needs to remain free of bash-isms.  Make sure it
# runs on plain POSIX shell.

# GNU sed has many extensions not on macOS and FreeBSD.  If
# you change near sed, test on FreeBSD.

# ########## Default configuration ##########
#
# Where to get the file
LEAPSRC="https://www.ietf.org/timezones/data/leap-seconds.list"

# How many times to try to download new file
MAXTRIES=6
INTERVAL=10

# Where to find ntp config file
NTPCONF=/etc/ntpsec/ntp.conf

# How long before expiration to get updated file
PREFETCH="60 days"

# How to restart NTP - older NTP: service ntpd? try-restart | condrestart
# Recent NTP checks for new file daily, so there's nothing to do
RESTART=

# Where to put temporary copy before it's validated
TMPFILE="/tmp/leap-seconds.$$.tmp"

# Syslog facility
LOGFAC=daemon
# ###########################################

# Places to look for commands.  Allows for CRON having path to
# old utilities on embedded systems

PATHLIST="/opt/sbin:/opt/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:"

REQUIREDCMDS=" wget logger tr sed"

SELF="`basename $0`"

displayHelp() {
            cat <<EOF
Usage: $SELF [options] [leapfile]

Verifies and if necessary, updates leap-second definition file

All arguments are optional:  Default (or current value) shown:
    -s    Specify the URL of the master copy to download
          $LEAPSRC
    -4    Use only IPv4
    -6    Use only IPv6
    -p 4|6
          Prefer IPv4 or IPv6 (as specified) addresses, but use either
    -e    Specify how long before expiration the file is to be refreshed
          Units are required, e.g. "-e 60 days"  Note that larger values
          imply more frequent refreshes.
          "$PREFETCH"
    -f    Specify location of ntp.conf (used to make sure leapfile directive is
          present and to default  leapfile)
          $NTPCONF
    -F    Force update even if current file is OK and not close to expiring.
    -c    Command to restart NTP after installing a new file
          <none> - ntpd checks file daily
    -r    Specify number of times to retry on get failure
          $MAXTRIES
    -i    Specify number of minutes between retries
          $INTERVAL
    -l    Use syslog for output (Implied if CRONJOB is set)
    -L    Don't use syslog for output
    -P    Specify the syslog facility for logging
          $LOGFAC
    -t    Name of temporary file used in validation
    -q    Only report errors to stdout
    -v    Verbose output
    -z    Specify path for utilities
          $PATHLIST
    -Z    Only use system path
    -V    Output version information and exit

$SELF will validate the file currently on the local system

Ordinarily, the file is found using the "leapfile" directive in $NTPCONF.
However, an alternate location can be specified on the command line.

If the file does not exist, is not valid, has expired, or is expiring soon,
a new copy will be downloaded.  If the new copy validates, it is installed and
NTP is (optionally) restarted.

If the current file is acceptable, no download or restart occurs.

-c can also be used to invoke another script to perform administrative
functions, e.g. to copy the file to other local systems.

This can be run as a cron job.  As the file is rarely updated, and leap
seconds are announced at least one month in advance (usually longer), it
need not be run more frequently than about once every three weeks.

For cron-friendly behavior, define CRONJOB=1 in the crontab.

This script depends on: sha1sum/shasum $REQUIREDCMDS

Version @NTPSEC_VERSION_EXTENDED@
EOF
   return 0
}

displayVersion() {
            cat <<EOF
ntpleapfetch ntpsec-@NTPSEC_VERSION_EXTENDED@
EOF
   return 0
}

# Default: Use syslog for logging if running under cron

SYSLOG="$CRONJOB"

if [ "$1" = "--help" ]; then
    displayHelp
    exit 0
fi

if [ "$1" = "--version" ]; then
    displayVersion
    exit 0
fi

# Parse options

while getopts 46p:P:s:e:f:Fc:r:i:lLt:hqvz:ZV opt; do
    case $opt in
        4)
            PROTO="-4"
            ;;
        6)
            PROTO="-6"
            ;;
        p)
            if [ "$OPTARG" = '4' -o "$OPTARG" = '6' ]; then
                PREFER="--prefer-family=IPv$OPTARG"
            else
                echo "Invalid -p $OPTARG" >&2
                exit 1;
            fi
            ;;
        P)
            LOGFAC="$OPTARG"
            ;;
        s)
            LEAPSRC="$OPTARG"
            ;;
        e)
            PREFETCH="$OPTARG"
            ;;
        f)
            NTPCONF="$OPTARG"
            ;;
        F)
            FORCE="Y"
            ;;
        c)
            RESTART="$OPTARG"
            ;;
        r)
            MAXTRIES="$OPTARG"
            ;;
        i)
            INTERVAL="$OPTARG"
            ;;
        t)
            TMPFILE="$OPTARG"
            ;;
        l)
            SYSLOG="y"
            ;;
        L)
            SYSLOG=
            ;;
        h)
            displayHelp
            exit 0
            ;;
        V)
            displayVersion
            exit 0
            ;;
        q)
            QUIET="Y"
            ;;
        v)
            VERBOSE="Y"
            ;;
        z)
            PATHLIST="$OPTARG:"
            ;;
        Z)
            PATHLIST=
            ;;
        *)
            echo "$SELF -h for usage" >&2
            exit 1
            ;;
    esac
done
shift $((OPTIND-1))

export PATH="$PATHLIST$PATH"

# Add to path to deal with embedded systems
#
for P in $REQUIREDCMDS ; do
    if >/dev/null 2>&1 which "$P" ; then
        continue
    fi
    [ "$P" = "logger" ] && continue
    echo "FATAL: missing $P command, please install"
    exit 1
done

# find sha1sum or shasum
if >/dev/null 2>&1 which "sha1sum" ; then
    SHASUM="sha1sum"
elif >/dev/null 2>&1 which "shasum" ; then
    SHASUM="shasum"
else
    echo "FATAL: Can not find sha1sum or shasum command, please install"
    exit 1
fi

# Handle logging

if ! LOGGER="`2>/dev/null which logger`" ; then
    LOGGER=
fi

log() {
    # "priority" "message"
    #
    # Stdout unless syslog specified or logger isn't available
    #
    if [ -z "$SYSLOG" -o -z "$LOGGER" ]; then
        if [ -n "$QUIET" -a \( "$1" = "info" -o "$1" = "notice" -o "$1" = "debug" \) ]; then
            return 0
        fi
        echo "`echo \"$1\" | tr a-z A-Z`: $2"
        return 0
    fi

    # Also log to stdout if cron job && notice or higher
    local S
    if [ -n "$CRONJOB" -a \( "$1" != "info" \) -a \( "$1" != "debug" \) ] || [ -n "$VERBOSE" ]; then
        S="-s"
    fi
    $LOGGER $S -t "$SELF[$$]" -p "$LOGFAC.$1" "$2"
}

# Verify interval
INTERVAL=$(( $INTERVAL *1 ))

# Validate a leap-seconds file checksum
#
# File format: (full description in files)
# # marks comments, except:
# #$ number : the NTP date of the last update
# #@ number : the NTP date that the file expires
# Date (seconds since 1900) leaps : leaps is the # of seconds to add for times >= Date
# Date lines have comments.
# #h hex hex hex hex hex is the SHA-1 checksum of the data & dates, excluding whitespace w/o leading zeroes

verifySHA1() {

    if [ ! -f "$1" ]; then
        return 1
    fi

    # Remove comments, except those that are markers for last update, expires and hash

    local RAW="`sed -ne'/^#[\$@h]/p;/^[^#]/s/.#.*$//p' $1 `"

    # Extract just the data, removing all whitespace

    local DATA="`echo \"$RAW\" | sed -e'/^#h/d' -e's/^#[\$@]//g' | tr -d '[:space:]'`"

    # Compute the SHA-1 hash of the data, removing the marker and filename
    # Computed in binary mode, which shouldn't matter since whitespace
    # has been removed
    # shasum/sha1sum comes in several flavors;
    # a portable one is available in Perl (with Digest::SHA)

    local DSHA1="`printf \"$DATA\" | $SHASUM | sed -e's/[? *].*$//'`"

    # Extract the file's hash. Restore any leading zeroes in hash segments.

    # The sed [] includes a tab (\t) and space; #h is followed by a tab and space
    # or maybe a space and a tab.  remove the tab, wherever it may be.  Add some 0x
    # so it can be run through printf to restore missing leading zeros.
    #
    local FSHA1="`grep '^#h' $1 | tr -d '[:cntrl:]' | sed -e's/^#h/0x/' -e's/ / 0x/g'`"
    FSHA1=`printf '%08x%08x%08x%08x%08x' $FSHA1`

    if [ -n "$FSHA1" -a \( "$FSHA1" = "$DSHA1" \) ]; then
        if [ -n "$2" ]; then
            log "info" "Checksum of $1 validated"
        fi
    else
        log "error" "Checksum of $1 is invalid:"
        [ -z "$FSHA1" ] && FSHA1="(no checksum record found in file)"
        log "error" "EXPECTED: $FSHA1"
        log "error" "COMPUTED: $DSHA1"
        return 1
    fi

    # Check the expiration date, converting NTP epoch to Unix epoch used by date

    EXPIRES="`echo \"$RAW\" | sed -e'/^#@/!d' -e's/^#@//' | tr -d '[:space:]'`"
    EXPIRES="$(($EXPIRES - 2208988800 ))"

    if [ $EXPIRES -lt `date -u +%s` ]; then
        log "notice" "File expired on `date -u -d \"Jan 1, 1970 00:00:00 +0000 + $EXPIRES seconds\"`"
        return 2
    fi

}

# Verify ntp.conf

if ! [ -f "$NTPCONF" ]; then
    log "critical" "Missing ntp configuration $NTPCONF"
    exit 1
fi

# Parse ntp.conf for leapfile directive
LEAPFILE="`grep -x 'leapfile *.*' $NTPCONF | grep -o ' [^ ]*.*'`"
if [ -z "$LEAPFILE" ]; then
    log "warning" "$NTPCONF does not specify a leapfile"
fi

# Allow placing the file someplace else - testing

if [ -n "$1" ]; then
    if [ "$1" != "$LEAPFILE" ]; then
	log "notice" "Requested install to $1, but $NTPCONF specifies $LEAPFILE"
    fi
    LEAPFILE="$1"
fi
if [ -z "$LEAPFILE" ]; then
    log "error" "No leapfile in ntp.conf or on the command line."
    exit 1
fi

# Verify the current file
# If it is missing, doesn't validate or expired
# Or is expiring soon
#  Download a new one

if [ -n "$FORCE" ] || ! verifySHA1 $LEAPFILE "$VERBOSE" || [ $EXPIRES -lt `date -d "NOW + $PREFETCH" +%s` ] ; then
    TRY=0
    while true; do
        TRY=$(( $TRY + 1 ))
        if [ -n "$VERBOSE" ]; then
            log "info" "Attempting download from $LEAPSRC, try $TRY.."
        fi
        if wget -T 10 $PROTO $PREFER -o ${TMPFILE}.log $LEAPSRC -O $TMPFILE ; then
            log "info" "Download of $LEAPSRC succeeded"
            if [ -n "$VERBOSE" ]; then
                cat ${TMPFILE}.log
            fi

            if ! verifySHA1 $TMPFILE "$VERBOSE" ; then
                # There is no point in retrying, as the file on the server is almost
                # certainly corrupt.

                log "warning" "Downloaded file $TMPFILE rejected -- saved for diagnosis"
                cat ${TMPFILE}.log
                rm -f ${TMPFILE}.log
                exit 1
            fi
            rm -f ${TMPFILE}.log

            # Set correct permissions on temporary file

            REFFILE="$LEAPFILE"
            if [ ! -f $LEAPFILE ]; then
                log "notice" "$LEAPFILE was missing, creating new copy - check permissions"
                touch $LEAPFILE
                # Can't copy permissions from old file,
                # copy from NTPCONF instead
                REFFILE="$NTPCONF"
            fi
            chmod --reference=$REFFILE $TMPFILE > /dev/null 2>&1
            if  [ $? -ne 0 ] ; then
                # the above chmod fails on macOS and BSD, just force it
                chmod 644 $TMPFILE
            fi
            chown --reference=$REFFILE $TMPFILE > /dev/null 2>&1
            if  [ $? -ne 0 ] ; then
                # the above chown fails on macOS and BSD, just force it
                chown root:wheel $TMPFILE
            fi
            ( which selinuxenabled && selinuxenabled && which chcon ) >/dev/null 2>&1
            if  [ $? -eq 0 ] ; then
                chcon --reference $REFFILE $TMPFILE
            fi

            # Replace current file with validated new one

            if mv -f $TMPFILE $LEAPFILE ; then
                log "notice" "Installed new $LEAPFILE from $LEAPSRC"
            else
                log "error" "Install $TMPFILE => $LEAPFILE failed -- saved for diagnosis"
                exit 1
            fi

            # Restart NTP (or whatever else is specified)

            if [ -n "$RESTART" ]; then
                if [ -n "$VERBOSE" ]; then
                    log "info" "Attempting restart action: $RESTART"
                fi
                R="$( 2>&1 $RESTART )"
                if [ $? -eq 0 ]; then
                    log "notice" "Restart action succeeded"
                    if [ -n "$VERBOSE" -a -n "$R" ]; then
                        log "info" "$R"
                    fi
                else
                    log "error" "Restart action failed"
                    if [ -n "$R" ]; then
                        log "error" "$R"
                    fi
                    exit 2
                fi
            fi
            exit 0
        fi

        # Failed to download.  See about trying again

        rm -f $TMPFILE
        if [ $TRY -ge $MAXTRIES ]; then
            break;
        fi
        if [ -n "$VERBOSE" ]; then
            cat ${TMPFILE}.log
            log "info" "Waiting $INTERVAL minutes before retrying..."
        fi
        sleep $(( $INTERVAL * 60))
    done

    # Failed and out of retries

    log "warning" "Download from $LEAPSRC failed after $TRY attempts"
    if [ -f ${TMPFILE}.log ]; then
        cat ${TMPFILE}.log
        rm -f ${TMPFILE}.log $TMPFILE
    fi
    exit 1
fi
log "info" "Not time to replace $LEAPFILE"

exit 0

# EOF