blob: 3a622b2b3881ee03d7226ed21557fd71832a0428 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001#!/bin/sh
2# Copyright (C) 2006-2014 OpenWrt.org
3
4. /lib/functions.sh
5
6unset SERVER
7unset PORT
8unset INTERVAL
9unset COUNT
10unset INTERFACE_GLOBAL
11
12NTPC=$(command -v ntpclient)
13
14check_server() {
15 local hostname
16 local port
17 local interface
18 [ -n "$SERVER" ] && return
19 config_get hostname $1 hostname
20 config_get port $1 port
21 config_get interface $1 interface
22
23 [ -z "$interface" ] && interface=$INTERFACE_GLOBAL
24
25 [ -n "$interface" ] && {
26 # $INTERFACE is passed from hotplug event
27 [ "$interface" = "$INTERFACE" ] || return
28 }
29
30 [ -z "$hostname" ] && return
31 $NTPC -c 1 -p ${port:-123} -i 2 -h $hostname > /dev/null && { SERVER=$hostname; PORT=${port:-123}; }
32}
33
34set_drift() {
35 config_get freq $1 freq
36 [ -n "$freq" ] && adjtimex -f $freq >/dev/null
37}
38
39start_ntpclient() {
40 config_foreach set_drift ntpdrift
41 config_foreach check_server ntpserver
42 [ -z "$SERVER" ] && exit 0
43 logger starting ntpclient
44 $NTPC ${COUNT:+-c $COUNT} ${INTERVAL:+-i $INTERVAL} -s -l -D -p $PORT -h $SERVER 2> /dev/null
45}
46
47stop_ntpclient() {
48 logger stopping ntpclient
49 killall ntpclient
50}
51
52load_settings() {
53 local interval
54 local count
55 local interface
56
57 config_get interval $1 interval
58 config_get count $1 count
59 config_get interface $1 interface
60
61 [ -n "$count" ] && COUNT=$count
62 [ -n "$interval" ] && INTERVAL=$interval
63 [ -n "$interface" ] && INTERFACE_GLOBAL=$interface
64}
65
66config_load ntpclient
67config_foreach load_settings ntpclient
68
69NTP_RUNNING=$(busybox ps | grep $NTPC | grep -v grep)
70
71case "${ACTION:-ifup}" in
72 ifup)
73 [ -z "$NTP_RUNNING" ] && start_ntpclient
74 ;;
75 ifdown)
76 [ -n "$NTP_RUNNING" ] && stop_ntpclient
77 ;;
78esac