summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--FAQ253
-rw-r--r--INSTALL8
-rw-r--r--Makefile.in16
-rw-r--r--NEWS34
-rw-r--r--README6
-rw-r--r--candm.h29
-rw-r--r--chrony.conf.5.in6
-rw-r--r--chrony.texi.in672
-rw-r--r--chrony.txt4608
-rw-r--r--chronyc.1.in16
-rw-r--r--chronyd.8.in48
-rw-r--r--client.c854
-rw-r--r--clientlog.c60
-rw-r--r--cmdmon.c737
-rw-r--r--cmdmon.h1
-rw-r--r--conf.c127
-rw-r--r--conf.h6
-rwxr-xr-xconfigure231
-rw-r--r--contrib/bryan_christianson_1/README.txt103
-rwxr-xr-xcontrib/bryan_christianson_1/chronylogrotate.sh45
-rw-r--r--contrib/bryan_christianson_1/org.tuxfamily.chronyc.plist22
-rw-r--r--contrib/bryan_christianson_1/org.tuxfamily.chronyd.plist19
-rw-r--r--examples/chrony-wait.service2
-rw-r--r--examples/chrony.conf.example14
-rw-r--r--examples/chrony.conf.example214
-rw-r--r--examples/chrony.conf.example339
-rw-r--r--examples/chrony.keys.example30
-rw-r--r--examples/chrony.logrotate2
-rw-r--r--examples/chrony.nm-dispatcher4
-rw-r--r--examples/chrony.spec2
-rw-r--r--getdate.c1171
-rw-r--r--getdate.y7
-rw-r--r--hash_nss.c3
-rw-r--r--keys.c79
-rw-r--r--keys.h2
-rw-r--r--logging.c52
-rw-r--r--logging.h26
-rw-r--r--main.c59
-rw-r--r--mkdirpp.c135
-rw-r--r--mkdirpp.h31
-rw-r--r--nameserv_async.h3
-rw-r--r--ntp_io.c20
-rw-r--r--ntp_sources.c17
-rw-r--r--ntp_sources.h3
-rw-r--r--pktlength.c4
-rw-r--r--reference.c4
-rw-r--r--rtc.c62
-rw-r--r--rtc_linux.c47
-rw-r--r--rtc_linux.h2
-rw-r--r--sources.c43
-rw-r--r--strerror.c38
-rw-r--r--stubs.c47
-rw-r--r--sys.c78
-rw-r--r--sys.h8
-rw-r--r--sys_generic.c94
-rw-r--r--sys_generic.h3
-rw-r--r--sys_linux.c361
-rw-r--r--sys_linux.h4
-rw-r--r--sys_macosx.c198
-rw-r--r--sys_macosx.h2
-rw-r--r--sys_netbsd.c306
-rw-r--r--sys_netbsd.h2
-rw-r--r--sys_solaris.c428
-rw-r--r--sys_sunos.c418
-rw-r--r--sys_sunos.h34
-rw-r--r--sys_timex.c243
-rw-r--r--sys_timex.h50
-rw-r--r--sysincl.h64
-rwxr-xr-xtest/compilation/001-features8
-rw-r--r--test/kernel/Makefile7
-rw-r--r--test/kernel/adjtime.c185
-rw-r--r--test/kernel/ntpadjtime.c75
-rwxr-xr-xtest/simulation/114-presend1
-rw-r--r--util.c259
-rw-r--r--util.h22
-rw-r--r--version.txt2
-rw-r--r--wrap_adjtimex.c204
-rw-r--r--wrap_adjtimex.h40
78 files changed, 3736 insertions, 9213 deletions
diff --git a/FAQ b/FAQ
index 14a81be..92e061d 100644
--- a/FAQ
+++ b/FAQ
@@ -1,22 +1,25 @@
Frequently Asked Questions
__________________________________________________________________
-1. Chrony compared to other programs
+1. chrony compared to other programs
1.1. How does chrony compare to ntpd?
- chrony can usually synchronise the system clock faster and with better
- time accuracy, but it doesn’t implement all NTP features, e.g.
- broadcast/multicast mode, or authentication based on public-key
- cryptography. For a more detailed comparison, see the [1]comparison
- page on the chrony website and section [2]Comparison with ntpd in the
- manual.
+ chronyd was designed to work well in a wide range of conditions and it
+ can usually synchronise the system clock faster and with better time
+ accuracy. It doesn’t implement some of the less useful NTP modes like
+ broadcast client or multicast server/client.
- If your computer connects to the 'net only for few minutes at a time,
- you turn your Linux computer off or suspend it frequently, the clock is
- not very stable (e.g. it is a virtual machine), or you want to use NTP
- on an isolated network with no hardware clocks in sight, chrony will
- probably work much better for you.
+ For a more detailed comparison of features and performance, see the
+ [1]comparison page on the chrony website and the [2]Comparison with
+ ntpd section in the manual.
+
+ If your computer is connected to the internet only for few minutes at a
+ time, the network connection is often congested, you turn your computer
+ off or suspend it frequently, the clock is not very stable (e.g. there
+ are rapid changes in the temperature or it’s a virtual machine), or you
+ want to use NTP on an isolated network with no hardware reference
+ clocks in sight, chrony will probably work much better for you.
The original reason chrony was written was that ntpd (called xntpd at
the time) could not to do anything sensible on a PC which was connected
@@ -41,7 +44,44 @@
2. Configuration issues
- 2.1. I have several computers on a LAN. Should be all clients of an external
+ 2.1. What is the minimum recommended configuration for an NTP client?
+
+ First, the client needs to know which NTP servers it should ask for the
+ current time. They are specified by the server or pool directive. The
+ pool directive can be used for names that resolve to multiple
+ addresses. For good reliability the client should have at least three
+ servers. The iburst option speeds up the initial synchronisation.
+
+ To stabilize the initial synchronisation on the next start, the
+ estimated drift of the system clock is saved by adding the driftfile
+ directive.
+
+ If the system clock can be far from the true time after boot for any
+ reason, chronyd should be allowed to correct it quickly by stepping
+ instead of slewing, which would take a very long time. The makestep
+ directive does that.
+
+ In order to keep the real-time clock (RTC) close to the true time on
+ Linux, so the system time is reasonably close to the true time when
+ it’s initialized on the next boot from the RTC, the rtcsync directive
+ enables a kernel mode in which the system time is copied to the RTC
+ every 11 minutes.
+
+ If you want to use public NTP servers from the [3]pool.ntp.org project,
+ the minimal chrony.conf file could be:
+
+ pool pool.ntp.org iburst
+ driftfile /var/lib/chrony/drift
+ makestep 1 3
+ rtcsync
+
+ 2.2. How do I make an NTP server from an NTP client?
+
+ You need to add an allow directive to the chrony.conf file in order to
+ open the NTP port and allow chronyd to reply to client requests. allow
+ with no specified subnet allows all IPv4 and IPv6 addresses.
+
+ 2.3. I have several computers on a LAN. Should be all clients of an external
server?
The best configuration is usually to make one computer the master, with
@@ -52,7 +92,7 @@
* if your external connection goes down, the computers on the LAN
will maintain a common time with each other.
- 2.2. Must I specify servers by IP address if DNS is not available on chronyd
+ 2.4. Must I specify servers by IP address if DNS is not available on chronyd
start?
No. Starting from version 1.25, chronyd will keep trying to resolve the
@@ -60,7 +100,7 @@
intervals until it succeeds. The online command can be issued from
chronyc to try to resolve them immediately.
- 2.3. How can I make chronyd more secure?
+ 2.5. How can I make chronyd more secure?
If you don’t need to serve time to NTP clients or peers, you can add
port 0 to the chrony.conf file to completely disable the NTP server
@@ -76,16 +116,29 @@
bindcmdaddress 127.0.0.1
bindcmdaddress ::1
- If you don’t need to use chronyc at all, you can disable the command
- sockets by adding cmdport 0 to the configuration file.
+ If you don’t need to use chronyc at all or you need to run chronyc only
+ under the root or chrony user (which can access chronyd through a Unix
+ domain socket since version 2.2), you can disable the internet command
+ sockets completely by adding cmdport 0 to the configuration file.
On Linux, if chronyd is compiled with support for Linux capabilities
- (available in the libcap library), you can specify an unprivileged user
- with the -u option or user directive in the chrony.conf file to drop
- root privileges after start. The configure option --with-user can be
- used to drop the privileges by default.
-
- 2.4. How can I improve the accuracy of the system clock with NTP sources?
+ (available in the libcap library), or on NetBSD with the /dev/clockctl
+ device, you can specify an unprivileged user with the -u option or user
+ directive in the chrony.conf file to drop root privileges after start.
+ The configure option --with-user can be used to drop the privileges by
+ default.
+
+ Also, if chronyd is compiled with support for the Linux secure
+ computing (seccomp) facility, you can enable a system call filter with
+ the -F option. It will significantly reduce the kernel attack surface
+ and possibly prevent kernel exploits from the chronyd process if
+ compromised. The filter shouldn’t be enabled without testing that it
+ allows all system calls needed with the specific configuration and
+ libraries that chronyd is using (e.g. libc and its NSS configuration).
+ If chronyd is getting killed, some system call is missing and the
+ filter has to be disabled until it’s patched to allow that call.
+
+ 2.6. How can I improve the accuracy of the system clock with NTP sources?
Select NTP servers that are well synchronised, stable and close to your
network. It’s better to use more than one server, three or four is
@@ -127,6 +180,16 @@
the example with local NTP server
server ntp.local minpoll 2 maxpoll 4 polltarget 30 maxdelaydevratio 2
+
+ 2.7. What happened to the commandkey and generatecommandkey directives?
+
+ They were removed in version 2.2. Authentication is no longer supported
+ in the command protocol. Commands that required authentication are now
+ allowed only through a Unix domain socket, which is accessible only by
+ the root and chrony users. If you need to configure chronyd remotely or
+ locally without the root password, please consider using ssh and/or
+ sudo to run chronyc under the root or chrony user on the same host as
+ chronyd is running.
__________________________________________________________________
3. Computer is not synchronising
@@ -142,14 +205,36 @@
an external modem, see if the receive light blinks straight after the
transmit light (when the link is quiet apart from the NTP traffic.) Try
adding log measurements to the chrony.conf file and look in the
- measurements.log file after chrony has been running for a short period.
- See if any measurements appear.
+ measurements.log file after chronyd has been running for a short
+ period. See if any measurements appear.
3.2. Are NTP servers specified with the offline option?
Check that you’re using chronyc's online and offline commands
appropriately. Again, check in measurements.log to see if you’re
getting any data back from the server.
+
+ 3.3. Is chronyd allowed to step the system clock?
+
+ By default, chronyd adjusts the clock gradually by slowing it down or
+ speeding it up. If the clock is too far from the correct time, it will
+ take a long time to correct the error. The System time value printed by
+ the chronyc's tracking command is the remaining correction that needs
+ to be applied to the system clock.
+
+ The makestep directive can be used to allow chronyd to step the clock.
+ For example, if chrony.conf had
+
+ makestep 1 3
+
+ the clock would be stepped in the first three updates if its offset was
+ larger than one second. Normally, it’s recommended to allow the step
+ only in the first few updates, but in some cases (e.g. a computer
+ without RTC or virtual machine which can be suspended and resumed with
+ incorrect time) it may be necessary to allow the step at any clock
+ update. The example above would change to
+
+ makestep 1 -1
__________________________________________________________________
4. Issues with chronyc
@@ -170,7 +255,13 @@
Perhaps you have a firewall set up in a way that blocks packets on port
323/udp. You need to amend the firewall configuration in this case.
- 4.2. Is the chronyc / chronyd protocol documented anywhere?
+ 4.2. I keep getting the error 501 Not authorised
+
+ Since version 2.2, the password command doesn’t do anything and chronyc
+ needs to run under the root or chrony user, which are allowed to access
+ the Unix domain command socket.
+
+ 4.3. Is the chronyc / chronyd protocol documented anywhere?
Only by the source code :-) See cmdmon.c (chronyd side) and client.c
(chronyc side).
@@ -181,21 +272,37 @@
5.1. What is the real-time clock (RTC)?
This is the clock which keeps the time even when your computer is
- turned off. It works with 1 second resolution. chronyd can monitor the
- rate at which the real-time clock gains or loses time, and compensate
- for it when you set the system time from it at the next reboot. See the
- documentation for details.
-
- 5.2. I want to use chronyd's real-time clock support. Must I disable hwclock?
+ turned off. It is used to initialize the system clock on boot. It
+ normally doesn’t drift more than few seconds per day.
+
+ There are two approaches how chronyd can work with it. One is to use
+ the rtcsync directive, which tells chronyd to enable a kernel mode
+ which sets the RTC from the system clock every 11 minutes. chronyd
+ itself won’t touch the RTC. If the computer is not turned off for a
+ long time, the RTC should still be close to the true time when the
+ system clock will be initialized from it on the next boot.
+
+ The other option is to use the rtcfile directive, which will tell
+ chronyd to monitor the rate at which the RTC gains or loses time. When
+ chronyd is started with the -s option on the next boot, it will set the
+ system time from the RTC and also compensate for the drift it has
+ measured previously. The rtcautotrim directive can be used to keep the
+ RTC close to the true time, but it’s not strictly necessary if its only
+ purpose is to set the system clock when chronyd is started on boot. See
+ the documentation for details.
+
+ 5.2. I want to use chronyd's RTC support. Must I disable hwclock?
The hwclock program is often set-up by default in the boot and shutdown
- scripts with many Linux installations. If you want to use chronyd's
- real-time clock support, the important thing is to disable hwclock in
- the shutdown procedure. If you don’t, it will over-write the RTC with a
- new value, unknown to chronyd. At the next reboot, chronyd will
- compensate this (wrong) time with its estimate of how far the RTC has
- drifted whilst the power was off, giving a meaningless initial system
- time.
+ scripts with many Linux installations. With the kernel RTC
+ synchronisation (rtcsync directive), the RTC will be set also every 11
+ minutes as long as the system clock is synchronised. If you want to use
+ chronyd's RTC monitoring (rtcfile directive), it’s important to disable
+ hwclock in the shutdown procedure. If you don’t, it will over-write the
+ RTC with a new value, unknown to chronyd. At the next reboot, chronyd
+ started with the -s option will compensate this (wrong) time with its
+ estimate of how far the RTC has drifted whilst the power was off,
+ giving a meaningless initial system time.
There is no need to remove hwclock from the boot process, as long as
chronyd is started after it has run.
@@ -209,38 +316,29 @@
* an rtcfile directive in your chrony.conf file
__________________________________________________________________
-6. Microsoft Windows
+6. NTP-specific issues
- 6.1. Does chrony support Windows?
+ 6.1. Can chronyd be driven from broadcast NTP servers?
- No. The chronyc program (the command-line client used for configuring
- chronyd while it is running) has been successfully built and run under
- Cygwin in the past. chronyd is not portable, because part of it is very
- system-dependent. It needs adapting to work with Windows' equivalent of
- the adjtimex() call, and it needs to be made to work as a service.
-
- 6.2. Are there any plans to support Windows?
-
- We have no plans to do this. Anyone is welcome to pick this work up and
- contribute it back to the project.
- __________________________________________________________________
-
-7. NTP-specific issues
+ No, the broadcast client mode is not supported and there is currently
+ no plan to implement it. The broadcast and multicast modes are
+ inherently less accurate and less secure (even with authentication)
+ than the ordinary server/client mode and they are not as useful as they
+ used to be. Even with very modest hardware a single NTP server can
+ serve time to hundreds of thousands of clients using the ordinary mode.
- 7.1. Can chrony be driven from broadcast NTP servers?
+ 6.2. Can chronyd transmit broadcast NTP packets?
- No, this NTP mode is not implemented yet.
+ Yes, the broadcast directive can be used to enable the broadcast server
+ mode to serve time to clients in the network which support the
+ broadcast client mode (it’s not supported in chronyd, see the previous
+ question).
- 7.2. Can chronyd transmit broadcast NTP packets (e.g. to synchronise other
- computers on a private LAN)?
-
- Yes. Starting from version 1.17, chrony has this capability.
-
- 7.3. Can chrony keep the system clock a fixed offset away from real time?
+ 6.3. Can chronyd keep the system clock a fixed offset away from real time?
This is not possible as the program currently stands.
- 7.4. What happens if the network connection is dropped without using chronyc's
+ 6.4. What happens if the network connection is dropped without using chronyc's
offline command first?
chronyd will keep trying to access the server(s) that it thinks are
@@ -254,30 +352,33 @@
be useful to switch the servers to the offline state automatically.
__________________________________________________________________
-8. Linux-specific issues
+7. Linux-specific issues
- 8.1. I get Could not open /dev/rtc, Device or resource busy in my syslog file
+ 7.1. I get Could not open /dev/rtc, Device or resource busy in my syslog file
Some other program running on the system may be using the device.
__________________________________________________________________
-9. Solaris-specific issues
+8. Microsoft Windows
- 9.1. I get an error message about not being able to open kvm to change
- dosynctodr
+ 8.1. Does chrony support Windows?
- (The dosynctodr variable controls whether Solaris couples the
- equivalent of its BIOS clock into its system clock at regular
- intervals). The Solaris port of chrony was developed in the Solaris 2.5
- era. Some aspect of the Solaris kernel has changed which prevents the
- same technique working. We no longer have root access to any Solaris
- machines to work on this, and we are reliant on somebody developing the
- patch and testing it.
+ No. The chronyc program (the command-line client used for configuring
+ chronyd while it is running) has been successfully built and run under
+ Cygwin in the past. chronyd is not portable, because part of it is very
+ system-dependent. It needs adapting to work with Windows' equivalent of
+ the adjtimex() call, and it needs to be made to work as a service.
+
+ 8.2. Are there any plans to support Windows?
+
+ We have no plans to do this. Anyone is welcome to pick this work up and
+ contribute it back to the project.
__________________________________________________________________
- Last updated 2015-06-23 16:02:17 CEST
+ Last updated 2015-10-19 11:18:37 CEST
References
1. http://chrony.tuxfamily.org/comparison.html
2. http://chrony.tuxfamily.org/manual.html#Comparison-with-ntpd
+ 3. http://www.pool.ntp.org/
diff --git a/INSTALL b/INSTALL
index 68685b8..bbefcd1 100644
--- a/INSTALL
+++ b/INSTALL
@@ -62,10 +62,10 @@ entered.
make install
- This will install the binaries, plain text manual and manpages.
+ This will install the binaries and manpages.
- To install the HTML and info versions of the manual as well, enter
-the command
+ To install the plain text, HTML and info versions of the manual,
+enter the command
make install-docs
@@ -88,7 +88,7 @@ servers from the pool.ntp.org project as your time reference. A minimal
useful configuration file could be
pool pool.ntp.org iburst
- makestep 10 3
+ makestep 1.0 3
rtcsync
Then, 'chronyd' can be run.
diff --git a/Makefile.in b/Makefile.in
index a031ba3..6ac0c9e 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -38,13 +38,13 @@ DESTDIR=
HASH_OBJ = @HASH_OBJ@
-OBJS = array.o cmdparse.o conf.o local.o logging.o main.o memory.o mkdirpp.o \
+OBJS = array.o cmdparse.o conf.o local.o logging.o main.o memory.o \
reference.o regress.o rtc.o sched.o sources.o sourcestats.o stubs.o \
sys.o smooth.o tempcomp.o util.o $(HASH_OBJ)
EXTRA_OBJS=@EXTRA_OBJECTS@
-CLI_OBJS = client.o nameserv.o getdate.o cmdparse.o \
+CLI_OBJS = array.o client.o cmdparse.o getdate.o memory.o nameserv.o \
pktlength.o util.o $(HASH_OBJ)
ALL_OBJS = $(OBJS) $(EXTRA_OBJS) $(CLI_OBJS)
@@ -82,7 +82,7 @@ clean :
-rm -rf .deps
-rm -rf *.dSYM
-getdate.c :
+getdate.c : getdate.y
bison -o getdate.c getdate.y
# This can be used to force regeneration of getdate.c
@@ -92,15 +92,13 @@ getdate :
# For install, don't use the install command, because its switches
# seem to vary between systems.
-install: chronyd chronyc chrony.txt
+install: chronyd chronyc
[ -d $(DESTDIR)$(SYSCONFDIR) ] || mkdir -p $(DESTDIR)$(SYSCONFDIR)
[ -d $(DESTDIR)$(SBINDIR) ] || mkdir -p $(DESTDIR)$(SBINDIR)
[ -d $(DESTDIR)$(BINDIR) ] || mkdir -p $(DESTDIR)$(BINDIR)
- [ -d $(DESTDIR)$(DOCDIR) ] || mkdir -p $(DESTDIR)$(DOCDIR)
[ -d $(DESTDIR)$(MANDIR)/man1 ] || mkdir -p $(DESTDIR)$(MANDIR)/man1
[ -d $(DESTDIR)$(MANDIR)/man5 ] || mkdir -p $(DESTDIR)$(MANDIR)/man5
[ -d $(DESTDIR)$(MANDIR)/man8 ] || mkdir -p $(DESTDIR)$(MANDIR)/man8
- [ -d $(DESTDIR)$(DOCDIR) ] || mkdir -p $(DESTDIR)$(DOCDIR)
[ -d $(DESTDIR)$(CHRONYVARDIR) ] || mkdir -p $(DESTDIR)$(CHRONYVARDIR)
if [ -f $(DESTDIR)$(SBINDIR)/chronyd ]; then rm -f $(DESTDIR)$(SBINDIR)/chronyd ; fi
if [ -f $(DESTDIR)$(BINDIR)/chronyc ]; then rm -f $(DESTDIR)$(BINDIR)/chronyc ; fi
@@ -108,12 +106,6 @@ install: chronyd chronyc chrony.txt
chmod 755 $(DESTDIR)$(SBINDIR)/chronyd
cp chronyc $(DESTDIR)$(BINDIR)/chronyc
chmod 755 $(DESTDIR)$(BINDIR)/chronyc
- cp chrony.txt $(DESTDIR)$(DOCDIR)/chrony.txt
- chmod 644 $(DESTDIR)$(DOCDIR)/chrony.txt
- cp COPYING $(DESTDIR)$(DOCDIR)/COPYING
- chmod 644 $(DESTDIR)$(DOCDIR)/COPYING
- cp README $(DESTDIR)$(DOCDIR)/README
- chmod 644 $(DESTDIR)$(DOCDIR)/README
cp chronyc.1 $(DESTDIR)$(MANDIR)/man1
chmod 644 $(DESTDIR)$(MANDIR)/man1/chronyc.1
cp chronyd.8 $(DESTDIR)$(MANDIR)/man8
diff --git a/NEWS b/NEWS
index 140fa58..a4e891c 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,37 @@
+New in version 2.2
+==================
+
+Enhancements
+------------
+* Add support for configuration and monitoring over Unix domain socket
+ (accessible by root or chrony user when root privileges are dropped)
+* Add support for system call filtering with seccomp on Linux (experimental)
+* Add support for dropping root privileges on NetBSD
+* Control frequency of system clock on FreeBSD, NetBSD, Solaris
+* Add system leap second handling mode on FreeBSD, NetBSD, Solaris
+* Add dynamic drift removal on Mac OS X
+* Add support for setting real-time priority on Mac OS X
+* Add maxdistance directive to limit source selection by root distance
+ (3 seconds by default)
+* Add refresh command to get new addresses of NTP sources
+* Allow wildcard patterns in include directive
+* Restore time from driftfile with -s option if later than RTC time
+* Add configure option to set default hwclockfile
+* Add -d option to chronyc to enable debug messages
+* Allow multiple addresses to be specified for chronyc with -h option
+ and reconnect when no valid reply is received
+* Make check interval in waitsync command configurable
+
+Bug fixes
+---------
+* Fix building on NetBSD, Solaris
+* Restore time from driftfile with -s option if reading RTC failed
+
+Removed features
+----------------
+* Drop support for authentication with command key (run-time configuration
+ is now allowed only for local users that can access the Unix domain socket)
+
New in version 2.1.1
====================
diff --git a/README b/README
index 3905c55..97be602 100644
--- a/README
+++ b/README
@@ -145,6 +145,9 @@ Alexander Gretencord <arutha@gmx.de>
Changes to installation directory system to make it easier for
package builders.
+Andrew Griffiths <agriffit@redhat.com>
+ Patch to add support for seccomp filter
+
Walter Haidinger <walter.haidinger@gmx.at>
Providing me with login access to a Linux installation where v1.12
wouldn't compile, so I could develop the fixes for v1.13. Also, for
@@ -204,6 +207,9 @@ Kalle Olavi Niemitalo <tosi@stekt.oulu.fi>
Frank Otto <sandwichmacher@web.de>
Handling arbitrary HZ values
+Gautier PHILIPPON <gautier.philippon@ensimag.grenoble-inp.fr>
+ Patch to add refresh command to chronyc
+
Andreas Piesk <apiesk@virbus.de>
Patch to make chronyc use the readline library if available
diff --git a/candm.h b/candm.h
index f3bea3a..e4eafb7 100644
--- a/candm.h
+++ b/candm.h
@@ -31,7 +31,6 @@
#include "sysincl.h"
#include "addressing.h"
-#include "hash.h"
/* This is the default port to use for CANDM, if no alternative is
defined */
@@ -91,7 +90,8 @@
#define REQ_MODIFY_MAKESTEP 50
#define REQ_SMOOTHING 51
#define REQ_SMOOTHTIME 52
-#define N_REQUEST_TYPES 53
+#define REQ_REFRESH 53
+#define N_REQUEST_TYPES 54
/* Special utoken value used to log on with first exchange being the
password. (This time value has long since gone by) */
@@ -336,6 +336,8 @@ typedef struct {
Version 6 : added padding to requests to prevent amplification attack,
changed maximum number of samples in manual list to 16, new commands: modify
makestep, smoothing report, smoothtime command
+
+ Authentication was removed later in version 6.
*/
#define PROTO_VERSION_NUMBER 6
@@ -364,8 +366,8 @@ typedef struct {
(count up from zero for same sequence
number) */
uint32_t sequence; /* Client's sequence number */
- uint32_t utoken; /* Unique token per incarnation of daemon */
- uint32_t token; /* Command token (to prevent replay attack) */
+ uint32_t pad1;
+ uint32_t pad2;
union {
REQ_Null null;
@@ -400,15 +402,10 @@ typedef struct {
REQ_SmoothTime smoothtime;
} data; /* Command specific parameters */
- /* The following fields only set the maximum size of the packet.
- There are no holes between them and the actual data. */
-
- /* Padding used to prevent traffic amplification */
+ /* Padding used to prevent traffic amplification. It only defines the
+ maximum size of the packet, there is no hole after the data field. */
uint8_t padding[MAX_PADDING_LENGTH];
- /* Authentication data */
- uint8_t auth[MAX_HASH_LENGTH];
-
} CMD_Request;
/* ================================================== */
@@ -614,9 +611,9 @@ typedef struct {
uint16_t pad2;
uint16_t pad3;
uint32_t sequence; /* Echo of client's sequence number */
- uint32_t utoken; /* Unique token per incarnation of daemon */
- uint32_t token; /* New command token (only if command was successfully
- authenticated) */
+ uint32_t pad4;
+ uint32_t pad5;
+
union {
RPY_Null null;
RPY_N_Sources n_sources;
@@ -631,10 +628,6 @@ typedef struct {
RPY_Smoothing smoothing;
} data; /* Reply specific parameters */
- /* authentication of the packet, there is no hole after the actual data
- from the data union, this field only sets the maximum auth size */
- uint8_t auth[MAX_HASH_LENGTH];
-
} CMD_Reply;
/* ================================================== */
diff --git a/chrony.conf.5.in b/chrony.conf.5.in
index 44ab753..4432816 100644
--- a/chrony.conf.5.in
+++ b/chrony.conf.5.in
@@ -1,4 +1,4 @@
-.TH chrony.conf 5 "June 2015" "chrony 2.1.1" "Configuration Files"
+.TH chrony.conf 5 "October 2015" "chrony 2.2" "Configuration Files"
.SH NAME
chrony.conf \- chronyd configuration file
@@ -34,7 +34,7 @@ useful configuration file would look something like
server bar.example.net iburst
server baz.example.net iburst
driftfile @CHRONYVARDIR@/drift
- makestep 10 3
+ makestep 1.0 3
rtcsync
.EE
@@ -46,7 +46,7 @@ case look like
.EX
pool pool.ntp.org iburst
driftfile @CHRONYVARDIR@/drift
- makestep 10 3
+ makestep 1.0 3
rtcsync
.EE
diff --git a/chrony.texi.in b/chrony.texi.in
index 908ab95..b56fb81 100644
--- a/chrony.texi.in
+++ b/chrony.texi.in
@@ -3,7 +3,7 @@
@afourwide
@paragraphindent 0
@setfilename chrony.info
-@settitle User guide for the chrony suite
+@settitle User guide for the chrony suite version @CHRONY_VERSION@
@c @setchapternewpage off
@ifinfo
@@ -49,7 +49,6 @@ Copyright @copyright{} 2009-2015 Miroslav Lichvar
* Other time synchronisation packages:: Comparision with other software
* Distribution and warranty:: There is no warranty
* Bug reporting:: How to report bugs and make suggestions
-* Contributing:: Areas where contributions are particularly welcome
@end menu
@c }}}
@c {{{ S:Overview
@@ -120,8 +119,9 @@ different quirks in its behaviour.
The software is known to work on Linux, FreeBSD, NetBSD, Mac OS X and Solaris.
Closely related systems may work too. Porting the software to other systems
-(particularly to those supporting an @code{adjtime} system call) should not be
-difficult, however it requires access to such systems to test out the driver.
+(particularly to those supporting an @code{adjtime} or @code{ntp_adjtime}
+system call) should not be difficult, however it requires access to such
+systems to test out the driver.
@c }}}
@c {{{ S:Other programs
@node Other time synchronisation packages
@@ -137,9 +137,9 @@ The `reference' implementation of the Network Time Protocol is the
program @code{ntpd}, available via
@uref{http://www.ntp.org/, The NTP home page}.
-One of the main differences between @code{ntpd} and @code{chronyd} is in
-the algorithms used to control the computer's clock. Things
-@code{chronyd} can do better than @code{ntpd}:
+One of the main differences between @code{ntpd} and @code{chronyd} is in how
+they control the computer's clock. Things @code{chronyd} can do better than
+@code{ntpd}:
@itemize @bullet
@item
@@ -159,13 +159,16 @@ longer periods of time.
@item
@code{chronyd} in the default configuration never steps the time to not
upset other running programs. @code{ntpd} can be configured to never
-step the time too, but it has to use a different means of adjusting the
-clock, which has some
-disadvantages.
+step the time too, but in that case it has to use a different means of
+adjusting the clock (daemon loop instead of kernel discipline), which may
+have a negative effect on accuracy of the clock.
@item
-@code{chronyd} can adjust the rate of the clock on Linux in a larger
-range, which allows it to operate even on machines with broken or
-unstable clock (e.g. in some virtual machines).
+@code{chronyd} can adjust the rate of the clock in a larger range, which
+allows it to operate even on machines with broken or unstable clock
+(e.g. in some virtual machines).
+@item
+@code{chronyd} is smaller, it uses less memory and it wakes up the CPU only
+when necessary, which is better for power saving.
@end itemize
Things @code{chronyd} can do that @code{ntpd} can't:
@@ -191,21 +194,36 @@ Things @code{ntpd} can do that @code{chronyd} can't:
@itemize @bullet
@item
-@code{ntpd} supports all operating modes from RFC 5905, including
-broadcast, multicast and manycast client / server. It supports the
-orphan mode and it also supports authentication based on public-key
-cryptography described in RFC 5906.
+@code{ntpd} supports all operating modes from RFC 5905, including broadcast,
+multicast, and manycast server/client. However, the broadcast and multicast
+modes are inherently less accurate and less secure (even with authentication)
+than the ordinary server/client mode and should generally be avoided.
@item
-@code{ntpd} has been ported to more types of computer / operating
-system.
+@code{ntpd} supports the Autokey protocol (RFC 5906) to authenticate servers
+with public-key cryptography. Note that the protocol has been shown to be
+insecure and it will be probably replaced with an implementation of the Network
+Time Security (NTS) specification.
@item
-@code{ntpd} includes drivers for many reference clocks. @code{chronyd}
-relies on other programs (e.g. gpsd) to access the data from the
-reference clocks.
+@code{ntpd} supports the orphan mode, which allows synchronisation to a common
+timescale in isolated networks with multiple servers. With @code{chronyd}
+there can be only one master and all other computers have to be directly or
+indirectly synchronised to it.
+
+@item
+@code{ntpd} has been ported to more operating systems.
+
+@item
+@code{ntpd} includes a large number of reference clock drivers. @code{chronyd}
+relies on other programs (e.g. @code{gpsd}) to access the timing data via the
+@code{SHM} or @code{SOCK} driver.
@end itemize
+A comparison of NTP implementations that includes more features and also
+their performance is on the @uref{http://chrony.tuxfamily.org/comparison.html,
+chrony comparison} page.
+
@node Comparison with timed
@subsection timed
@code{timed} is a program that is part of the BSD networking suite. It
@@ -272,39 +290,6 @@ Of course, if you can debug the problem yourself and send us a source code
patch to fix it, we will be very grateful!
@c }}}
-@c {{{ S:Contributions
-@node Contributing
-@section Contributions
-
-Although chrony is now a fairly mature and established project, there are still
-areas that could be improved. If you can program in C and have some expertise
-in these areas, you might be able to fill the gaps.
-
-Particular areas that need addressing are :
-
-@enumerate
-@item Porting to other Unices
-
-This involves creating equivalents of sys_solaris.c, sys_linux.c etc for the
-new system.
-
-@item Porting to Windows NT
-
-A small amount of work on this was done under Cygwin. Only the sorting
-out of the include files has really been achieved so far. The two main
-areas still to address are
-
-@enumerate
-@item The system clock driver.
-@item How to make chronyd into an NT service (i.e. what to replace fork(),
-setsid() etc with so that chronyd can be automatically started in the system
-bootstrap.
-@end enumerate
-
-@item More drivers for reference clock support
-
-@end enumerate
-@c }}}
@c }}}
@c {{{ Ch:Installation
@node Installation
@@ -387,9 +372,10 @@ entered.
make install
@end example
-This will install the binaries, plain text manual and manpages.
+This will install the binaries and manpages.
-To install the HTML and info versions of the manual as well, enter the command
+To install the plain text, HTML and info versions of the manual, enter the
+command
@example
make install-docs
@@ -417,7 +403,7 @@ minimal useful configuration file could be
@example
pool pool.ntp.org iburst
-makestep 10 3
+makestep 1.0 3
rtcsync
@end example
@@ -574,7 +560,7 @@ server foo.example.net iburst
server bar.example.net iburst
server baz.example.net iburst
driftfile @CHRONYVARDIR@/drift
-makestep 10 3
+makestep 1.0 3
rtcsync
@end example
@@ -586,7 +572,7 @@ could in this case look like
@example
pool pool.ntp.org iburst
driftfile @CHRONYVARDIR@/drift
-makestep 10 3
+makestep 1.0 3
rtcsync
@end example
@c }}}
@@ -635,16 +621,9 @@ server bar.example.net offline
server baz.example.net offline
@end example
-The @code{offline} keyword indicates that the servers start
-in an offline state, and that they should not be contacted until @code{chronyd}
-receives notification that the link to the internet is present.
-
-In order to notify @code{chronyd} of the presence of the link, you will need to
-be able to log in to it with the program @code{chronyc}. To do this,
-@code{chronyd} needs to be configured with an administrator password. The
-password is read from a file specified by the @code{keyfile} directive. The
-@code{generatecommandkey} directive can be used to generate a random password
-automatically on the first @code{chronyd} start.
+The @code{offline} keyword indicates that the servers start in an offline
+state, and that they should not be contacted until @code{chronyd} receives
+notification from @code{chronyc} that the link to the internet is present.
The smallest useful configuration file would look something like
@@ -652,10 +631,9 @@ The smallest useful configuration file would look something like
server foo.example.net offline
server bar.example.net offline
server baz.example.net offline
-keyfile @SYSCONFDIR@/chrony.keys
-generatecommandkey
driftfile @CHRONYVARDIR@/drift
-makestep 10 3
+makestep 1.0 3
+rtcsync
@end example
The next section describes how to tell @code{chronyd} when the internet link
@@ -663,28 +641,22 @@ goes up and down.
@node Advising chronyd of internet availability
@subsection How to tell chronyd when the internet link is available.
-To use this option, you will need to configure a command key in
-@code{chronyd's} configuration file @file{@SYSCONFDIR@/chrony.conf}, as described in
-the previous section.
-
To tell @code{chronyd} when to start and finish sampling the servers, the
-@code{online} and @code{offline} commands of chronyc need to be used.
+@code{online} and @code{offline} commands of @code{chronyc} need to be used.
To give an example of their use, we assume that @code{pppd} is the
-program being used to connect to the internet, and that chronyc has been
-installed at its default location @file{@BINDIR@/chronyc}. We
-also assume that the command key has been set up as described in the
-previous section.
+program being used to connect to the internet, and that @code{chronyc} has been
+installed at its default location @file{@BINDIR@/chronyc}.
In the file @file{/etc/ppp/ip-up} we add the command sequence
@example
-@BINDIR@/chronyc -a online
+@BINDIR@/chronyc online
@end example
and in the file @file{/etc/ppp/ip-down} we add the sequence
@example
-@BINDIR@/chronyc -a offline
+@BINDIR@/chronyc offline
@end example
@code{chronyd's} polling of the servers will now only occur whilst the
@@ -707,44 +679,31 @@ support for this, in the form of the @code{manual} directive in the
configuration file and the @code{settime} command in the @code{chronyc}
program.
-If the master is rebooted, @code{chronyd} can re-read the drift rate
-from the drift file. However, the master has no accurate estimate of
-the current time. To get around this, the system can be configured so
-that the master can initially set itself to a `majority-vote' of
-selected clients' times; this allows the clients to `flywheel' the
-master across its outage.
+The @code{smoothtime} directive (@pxref{smoothtime directive}) is useful when
+the clocks of the clients need to stay close together when the local time is
+adjusted by the @code{settime} command. The smoothing process needs to be
+activated by the @code{smoothtime activate} command when the local time is
+ready to be served. After that point, any adjustments will be smoothed out.
-A typical configuration file for the master (called @code{master}) might
-be (assuming the clients are in the 192.168.165.x subnet and that the
-master's address is 192.168.169.170)
+A typical configuration file for the master (called @code{master}) might be
+(assuming the clients are in the 192.168.165.x subnet)
@example
driftfile @CHRONYVARDIR@/drift
-generatecommandkey
-keyfile @SYSCONFDIR@/chrony.keys
-initstepslew 10 client1 client3 client6
local stratum 8
manual
allow 192.168.165
+smoothtime 400 0.01
@end example
-For the clients that have to resynchronise the master when it restarts,
-the configuration file might be
+For the clients the configuration file might be
@example
-server master
+server master iburst
driftfile @CHRONYVARDIR@/drift
logdir /var/log/chrony
log measurements statistics tracking
-keyfile @SYSCONFDIR@/chrony.keys
-generatecommandkey
-local stratum 10
-initstepslew 20 master
-allow 192.168.169.170
@end example
-
-The rest of the clients would be the same, except that the @code{local}
-and @code{allow} directives are not required.
@c }}}
@c {{{ S:Dial-up home PCs
@node Dial-up home PCs
@@ -870,9 +829,7 @@ server baz.example.net maxdelay 0.4 offline
logdir /var/log/chrony
log statistics measurements tracking
driftfile @CHRONYVARDIR@/drift
-keyfile @SYSCONFDIR@/chrony.keys
-generatecommandkey
-makestep 10 3
+makestep 1.0 3
maxupdateskew 100.0
dumponexit
dumpdir @CHRONYVARDIR@
@@ -886,13 +843,13 @@ online and offline respectively.
The relevant part of the @file{/etc/ppp/ip-up} file is
@example
-@BINDIR@/chronyc -a online
+@BINDIR@/chronyc online
@end example
and the relevant part of the @file{/etc/ppp/ip-down} script is
@example
-@BINDIR@/chronyc -a -m offline dump writertc
+@BINDIR@/chronyc -m offline dump writertc
@end example
To start @code{chronyd} during the boot sequence, the following
@@ -989,10 +946,9 @@ used. These histories are created by using the @code{dump} command in
@code{chronyc}, or by setting the @code{dumponexit} directive in the
configuration file. This option is useful if you want to stop and
restart @code{chronyd} briefly for any reason, e.g. to install a new
-version. However, it only makes sense on systems where the kernel can
-maintain clock compensation whilst not under @code{chronyd's} control.
-The only version where this happens so far is Linux. On other systems
-this option should not be used.
+version. However, it should be used only on systems where the kernel
+can maintain clock compensation whilst not under @code{chronyd's}
+control (i.e. Linux, FreeBSD, NetBSD and Solaris).
@item -R
When this option is used, the @code{initstepslew} directive and the
@code{makestep} directive used with a positive limit will be ignored.
@@ -1000,13 +956,9 @@ This option is useful when restarting @code{chronyd} and can be used
in conjunction with the `-r' option.
@item -s
-This option will set the system clock from the computer's real-time
-clock. This is analogous to supplying the `-s' flag to the
-@file{/sbin/hwclock} program during the Linux boot sequence.
-
-Support for real-time clocks is limited at present - the criteria are
-described in the section on the @code{rtcfile} directive (@pxref{rtcfile
-directive}).
+This option will set the system clock from the computer's real-time clock or
+to the last modification time of the file specified by the @code{driftfile}
+directive. Real-time clocks are supported only on Linux.
If used in conjunction with the `-r' flag, @code{chronyd} will attempt
to preserve the old samples after setting the system clock from the real
@@ -1017,15 +969,21 @@ to work well, it relies on @code{chronyd} having been able to determine
accurate statistics for the difference between the RTC and
system clock last time the computer was on.
-If @code{chronyd} doesn't support the RTC on your computer or there is no RTC
-installed, the system clock will be set with this option forward to the time of
-the last modification of the drift file (specified by the @code{driftfile}
-directive) to restore the system time at which @code{chronyd} was previously
-stopped.
+If the last modification time of the drift file is later than the current time
+and the RTC time, the system time will be set to it to restore the time when
+@code{chronyd} was previously stopped. This is useful on computers that have
+no RTC or the RTC is broken (e.g. it has no battery).
@item -u <user>
-This option sets the name of the user to which will @code{chronyd} switch to
-drop root privileges if compiled with Linux capabilities support (default
-@code{@DEFAULT_USER@}).
+This option sets the name of the system user to which @code{chronyd} will
+switch after start in order to drop root privileges. It overrides the
+@code{user} directive (default @code{@DEFAULT_USER@}). It may be set to a
+non-root user only when @code{chronyd} is compiled with support for Linux
+capabilities (libcap) or on NetBSD with the @code{/dev/clockctl} device.
+@item -F <level>
+This option configures a system call filter when @code{chronyd} is compiled with
+support for the Linux secure computing (seccomp) facility. In level 1 the
+process is killed when a forbidden system call is made, in level -1 the SYSSIG
+signal is thrown instead and in level 0 the filter is disabled (default 0).
@item -q
When run in this mode, @code{chronyd} will set the system clock once
and exit. It will not detach from the terminal.
@@ -1036,9 +994,11 @@ not correct the clock.
This option displays @code{chronyd's} version number to the terminal and
exits.
@item -P <priority>
-This option will select the SCHED_FIFO real-time scheduler at the
-specified priority (which must be between 0 and 100). This mode is
-supported only on Linux.
+On Linux, this option will select the SCHED_FIFO real-time scheduler at the
+specified priority (which must be between 0 and 100). On Mac OS X, this option
+must have either a value of 0 (the default) to disable the thread time
+constraint policy or 1 for the policy to be enabled. Other systems do not
+support this option.
@item -m
This option will lock chronyd into RAM so that it will never be paged
out. This mode is only supported on Linux.
@@ -1120,18 +1080,16 @@ the configuration file is ignored.
* bindcmdaddress directive:: Limit network interface used for commands
* broadcast directive:: Make chronyd act as an NTP broadcast server
* clientloglimit directive:: Set client log memory limit
-* cmdallow directive:: Give control access to chronyc on other computers
-* cmddeny directive:: Deny control access to chronyc on other computers
-* cmdport directive:: Set port to use for runtime commanding
+* cmdallow directive:: Give monitoring access to chronyc on other computers
+* cmddeny directive:: Deny monitoring access to chronyc on other computers
+* cmdport directive:: Set port to use for runtime monitoring
* combinelimit directive:: Limit sources included in combining algorithm
-* commandkey directive:: Set runtime command key
* corrtimeratio directive:: Set correction time ratio
* deny directive:: Deny access to NTP clients
* driftfile directive:: Specify location of file containing drift data
* dumpdir directive:: Specify directory for dumping measurements
* dumponexit directive:: Dump measurements when daemon exits
* fallbackdrift directive:: Specify fallback drift intervals
-* generatecommandkey directive:: Generate command key automatically
* hwclockfile directive:: Specify location of hwclock's adjtime file
* include directive:: Include a configuration file
* initstepslew directive:: Trim the system clock on boot-up
@@ -1149,6 +1107,7 @@ the configuration file is ignored.
* manual directive:: Allow manual entry using chronyc's settime cmd
* maxchange directive:: Set maximum allowed offset
* maxclockerror directive:: Set maximum frequency error of local clock
+* maxdistance directive:: Set maximum allowed distance of sources
* maxsamples directive:: Set maximum number of samples per source
* maxslewrate directive:: Set maximum slew rate
* maxupdateskew directive:: Stop bad estimates upsetting machine clock
@@ -1318,9 +1277,15 @@ on multiple network interfaces.
@node bindcmdaddress directive
@subsection bindcmdaddress
The @code{bindcmdaddress} directive allows you to specify the network
-interface to which @code{chronyd} will listen for command packets (issued by
-@code{chronyc}). This provides an additional level of access restriction above
-that available through @code{cmddeny} mechanism.
+interface to which @code{chronyd} will listen for monitoring command packets
+(issued by @code{chronyc}). This provides an additional level of access
+restriction above that available through @code{cmddeny} mechanism.
+
+This directive can also change the path of the Unix domain command socket,
+which is used by @code{chronyc} to send configuration commands. The socket
+must be in a directory that is accessible only by the root or chrony user. The
+directory will be created on start if it doesn't exist. The default path of
+the socket is @code{@CHRONYSOCKDIR@/chronyd.sock}.
By default, @code{chronyd} binds to the loopback interface (with addresses
@code{127.0.0.1} and @code{::1}). This blocks all access except from
@@ -1336,6 +1301,11 @@ to the configuration file.
For each of IPv4 and IPv6 protocols, only one @code{bindcmdaddress}
directive can be specified.
+
+An example that sets the path of the Unix domain command socket is
+@example
+bindcmdaddress /var/run/chrony/chronyd.sock
+@end example
@c }}}
@c {{{ broadcast directive
@node broadcast directive
@@ -1394,14 +1364,15 @@ clientloglimit 1048576
@subsection cmdallow
This is similar to the @code{allow} directive (@pxref{allow directive}), except
-that it allows control access (rather than NTP client access) to a particular
-subnet or host. (By 'control access' is meant that chronyc can be run on those
-hosts and successfully connect to chronyd on this computer.)
+that it allows monitoring access (rather than NTP client access) to a particular
+subnet or host. (By 'monitoring access' is meant that @code{chronyc} can be
+run on those hosts and retrieve monitoring data from @code{chronyd} on this
+computer.)
The syntax is identical to the @code{allow} directive.
There is also a @code{cmdallow all} directive with similar behaviour to the
-@code{allow all} directive (but applying to control access in this case, of
+@code{allow all} directive (but applying to monitoring access in this case, of
course).
Note that @code{chronyd} has to be configured with the @code{bindcmdaddress}
@@ -1413,7 +1384,7 @@ access.
@subsection cmddeny
This is similar to the @code{cmdallow} directive (@pxref{cmdallow directive}),
-except that it denies control access to a particular subnet or host,
+except that it denies monitoring access to a particular subnet or host,
rather than allowing it.
The syntax is identical.
@@ -1426,9 +1397,10 @@ There is also a @code{cmddeny all} directive with similar behaviour to the
@subsection cmdport
The @code{cmdport} directive allows the port that is used for run-time
-command and monitoring (via the program @code{chronyc}) to be altered
+monitoring (via the @code{chronyc} program) to be altered
from its default (323/udp). If set to 0, @code{chronyd} will not open the
-port, this is useful to disable the @code{chronyc} access completely.
+port, this is useful to disable the @code{chronyc} access from the internet.
+(It does not disable the Unix domain command socket.)
An example shows the syntax
@@ -1464,46 +1436,12 @@ The syntax is
combinelimit <limit>
@end example
@c }}}
-@c {{{ commandkey
-@node commandkey directive
-@subsection commandkey
-The commandkey command is used to set the key number used for
-authenticating user commands via the chronyc program at run time.
-This allows certain actions of the chronyc program to be restricted to
-administrators.
-
-An example of the commandkey command is
-
-@example
-commandkey 20
-@end example
-
-By default, the key number is 0.
-
-In the key file (see the keyfile command) there should be a line of
-the form
-
-@example
-20 MD5 HEX:B028F91EA5C38D06C2E140B26C7F41EC
-@end example
-
-When running the chronyc program to perform run-time configuration,
-the command
-
-@example
-password HEX:B028F91EA5C38D06C2E140B26C7F41EC
-@end example
-
-must be entered before any commands affecting the operation of the
-daemon can be entered, or chronyc must be started with the `-a' option to run
-the password command automatically.
-@c }}}
@c {{{ corrtimeratio
@node corrtimeratio directive
@subsection corrtimeratio
-When @code{chronyd} makes a time correction, it controls how quickly
-the system clock is slewed (so far only on Linux). This rate
-affects the frequency error of the system clock.
+When @code{chronyd} is slewing the system clock to correct an offset, the rate
+at which it is slewing adds to the frequency error of the clock. On Linux,
+FreeBSD, NetBSD and Solaris this rate can be controlled.
The @code{corrtimeratio} directive sets the ratio between the
duration in which the clock is slewed for an average correction
@@ -1580,12 +1518,11 @@ driftfile @CHRONYVARDIR@/drift
To compute the rate of gain or loss of time, @code{chronyd} has to store
a measurement history for each of the time sources it uses.
-Certain systems (so far only Linux) have operating system support for
-setting the rate of gain or loss to compensate for known errors. (On
-other systems, @code{chronyd} must simulate such a capability by
-periodically slewing the system clock forwards or backwards by a
-suitable amount to compensate for the error built up since the previous
-slew).
+Certain systems (Linux, FreeBSD, NetBSD, Solaris) have operating system
+support for setting the rate of gain or loss to compensate for known errors.
+(On Mac OS X, @code{chronyd} must simulate such a capability by periodically
+slewing the system clock forwards or backwards by a suitable amount to
+compensate for the error built up since the previous slew).
For such systems, it is possible to save the measurement history across
restarts of @code{chronyd} (assuming no changes are made to the system
@@ -1638,23 +1575,15 @@ By default (or if the specified maximum or minimum is 0), no fallbacks
are used and the clock frequency changes only with new measurements from
NTP, reference clocks or manual input.
@c }}}
-@c {{{ generatecommandkey
-@node generatecommandkey directive
-@subsection generatecommandkey
-With this directive, if the command key is not found on start in the file
-specified by the @code{keyfile} directive, @code{chronyd} will generate a new
-command key from the /dev/urandom file and write it to the key file.
-
-The generated key will use SHA1 if @code{chronyd} is compiled with the support,
-otherwise MD5 will be used.
-@c }}}
@c {{{ hwclockfile
@node hwclockfile directive
@subsection hwclockfile
The @code{hwclockfile} directive sets the location of the adjtime file which is
-used by the @file{/sbin/hwclock} program. With this directive, @code{chronyd}
-will parse the file to find out if the RTC keeps local time or UTC. It
-overrides the @code{rtconutc} directive (@pxref{rtconutc directive}).
+used by the @file{/sbin/hwclock} program on Linux. @code{chronyd} parses the
+file to find out if the RTC keeps local time or UTC. It overrides the
+@code{rtconutc} directive (@pxref{rtconutc directive}).
+
+The default value is @file{@DEFAULT_HWCLOCK_FILE@}.
An example of the command is
@@ -1665,12 +1594,15 @@ hwclockfile /etc/adjtime
@c {{{ include
@node include directive
@subsection include
-The @code{include} directive includes a specified configuration file.
-This is useful when maintaining configuration on multiple hosts to
-keep the differences in a separate file.
+The @code{include} directive includes a specified configuration file or
+multiple configuration files when a wildcard pattern is specified. This can be
+useful when maintaining configuration on multiple hosts to keep the differences
+in separate files.
+
+An example of the command is
@example
-include @SYSCONFDIR@/chrony/local.conf
+include @SYSCONFDIR@/chrony.d/*.conf
@end example
@c }}}
@c {{{ initstepslew
@@ -1743,12 +1675,7 @@ from reading the clock before it's stepped.
@node keyfile directive
@subsection keyfile
This command is used to specify the location of the file containing
-ID/key pairs for the following 2 uses:
-
-@itemize @bullet
-@item Authentication of NTP packets.
-@item Authentication of administrator commands entered via chronyc.
-@end itemize
+ID/key pairs for authentication of NTP packets.
The format of the command is shown in the example below
@@ -1768,24 +1695,27 @@ pairs. The format of the file is shown below
@end example
Each line consists of an ID, a name of authentication hash function (optional)
-and a password. The ID can be any unsigned integer in the range 0 through
-2**32-1, but ID of 0 can be used only for the command key and not for the NTP
-authentication. The hash function is MD5 by default, depending on how was
-@code{chronyd} compiled other allowed hash functions may be SHA1, SHA256,
+and a password. The ID can be any unsigned integer in the range 1 through
+2**32-1. The hash function is MD5 by default, depending on how was
+@code{chronyd} compiled, other allowed hash functions may be SHA1, SHA256,
SHA384, SHA512, RMD128, RMD160, RMD256, RMD320, TIGER and WHIRLPOOL. The
password can be encoded as a string of characters not containing a space with
optional @code{ASCII:} prefix or as a hexadecimal number with @code{HEX:}
prefix.
The password is used with the hash function to generate and verify a message
-authentication code (MAC) in NTP and command packets.
+authentication code (MAC) in NTP packets.
For maximum security, it's recommended to use SHA1 or stronger hash function.
The passwords should be random and they should be as long as the output size of
the configured hash function, e.g. 160 bits with SHA1.
-The ID for the chronyc authentication key is specified with the commandkey
-command (see earlier). The command key can be generated automatically on
-start with the @code{generatecommandkey} directive.
+These shell commands can be used to generate random MD5 and SHA1 keys on
+systems which have the @code{/dev/urandom} device:
+
+@example
+echo "1 MD5 HEX:$(tr -d -c '[:xdigit:]' < /dev/urandom | head -c 32)"
+echo "1 SHA1 HEX:$(tr -d -c '[:xdigit:]' < /dev/urandom | head -c 40)"
+@end example
@c }}}
@c {{{ leapsecmode
@node leapsecmode directive
@@ -1806,8 +1736,8 @@ selects how that error is corrected. There are four options:
When inserting a leap second, the kernel steps the system clock backwards by
one second when the clock gets to 00:00:00 UTC. When deleting a leap second,
it steps forward by one second when the clock gets to 23:59:59 UTC. This is
-the default mode when the system driver supports leap seconds (currently Linux
-only).
+the default mode when the system driver supports leap seconds (i.e. on
+Linux, FreeBSD, NetBSD and Solaris).
@item step
This is similar to the @code{system} mode, except the clock is stepped by
@code{chronyd} instead of the kernel. It can be useful to avoid bugs in the
@@ -2354,6 +2284,10 @@ mailonchange root@@localhost 0.5
This would send a mail message to root if a change of more than 0.5
seconds were applied to the system clock.
+
+This directive can't be used when a system call filter is enabled by the
+@code{-F} option as the @code{chronyd} process will not be allowed to fork
+and execute the sendmail binary.
@c }}}
@c {{{ makestep
@node makestep directive
@@ -2375,10 +2309,10 @@ only with NTP sources.
An example of the use of this directive is
@example
-makestep 1000 10
+makestep 0.1 10
@end example
-This would step system clock if the adjustment is larger than 1000
+This would step system clock if the adjustment is larger than 0.1
seconds, but only in the first ten clock updates.
@c }}}
@c {{{ manual
@@ -2435,6 +2369,27 @@ Typical values for <error-in-ppm> might be 10 for a low quality clock
to 0.1 for a high quality clock using a temperature compensated
crystal oscillator.
@c }}}
+@c {{{ maxdistance
+@node maxdistance directive
+@subsection maxdistance
+The @code{maxdistance} directive sets the maximum allowed root distance of the
+sources to not be rejected by the source selection algorithm. The distance
+includes the accumulated dispersion, which may be large when the source is no
+longer synchronised, and half of the total round-trip delay to the primary
+source.
+
+By default, the maximum root distance is 3 seconds.
+
+Setting @code{maxdistance} to a larger value can be useful to allow
+synchronisation with a server that only has a very infrequent connection to its
+sources and can accumulate a large dispersion between updates of its clock.
+
+The syntax is
+
+@example
+maxdistance <seconds>
+@end example
+@c }}}
@c {{{ maxsamples
@node maxsamples directive
@subsection maxsamples
@@ -2456,10 +2411,16 @@ maxsamples <samples>
The @code{maxslewrate} directive sets the maximum rate at which @code{chronyd}
is allowed to slew the time. It limits the slew rate controlled by the
correction time ratio (@pxref{corrtimeratio directive}) and is effective
-only on systems where @code{chronyd} is able to control the rate (so
-far only Linux).
+only on systems where @code{chronyd} is able to control the rate (i.e.
+Linux, FreeBSD, NetBSD, Solaris).
+
+For each system there is a maximum frequency offset of the clock that
+can be set by the driver. On Linux it's 100000 ppm, on FreeBSD and NetBSD
+it's 5000 ppm and on Solaris it is 32500 ppm. Also, due to a kernel
+limitation, setting @code{maxslewrate} on FreeBSD and NetBSD to a value between
+500 ppm and 5000 ppm will effectively set it to 500 ppm.
-By default, the maximum slew rate is 83333.333 ppm (one twelfth).
+By default, the maximum slew rate is set to 83333.333 ppm (one twelfth).
The syntax is
@@ -2880,19 +2841,21 @@ system time is copied to the real time clock (RTC) every 11 minutes.
This directive is supported only on Linux and cannot be used when the
normal RTC tracking is enabled, i.e. when the @code{rtcfile} directive
-is used.
+is used. On other systems this directive does nothing.
@c }}}
@c {{{ sched_priority
@node sched_priority directive
@subsection sched_priority
-The @code{sched_priority} directive will select the SCHED_FIFO real-time
-scheduler at the specified priority (which must be between 0 and 100).
-This mode is supported only on Linux.
+On Linux, the @code{sched_priority} directive will select the SCHED_FIFO
+real-time scheduler at the specified priority (which must be between 0 and
+100). On Mac OS X, this option must have either a value of 0 (the default) to
+disable the thread time constraint policy or 1 for the policy to be enabled.
+Other systems do not support this option.
-This directive uses the Linux sched_setscheduler() system call to
-instruct the kernel to use the SCHED_FIFO first-in, first-out
-real-time scheduling policy for @code{chronyd} with the specified priority.
+On Linux, this directive uses the sched_setscheduler() system call to instruct
+the kernel to use the SCHED_FIFO first-in, first-out real-time scheduling
+policy for @code{chronyd} with the specified priority.
This means that whenever @code{chronyd} is ready to run it will run,
interrupting whatever else is running unless it is a higher priority
real-time process. This should not impact performance as @code{chronyd's}
@@ -2900,6 +2863,10 @@ resource requirements are modest, but it should result in lower and
more consistent latency since @code{chronyd} will not need to wait for the
scheduler to get around to running it. You should not use this unless
you really need it. The sched_setscheduler man page has more details.
+
+On Mac OS X, this directive uses the thread_policy_set() kernel call to specify
+real-time scheduling. As noted for Linux, you should not use this directive
+unless you really need it.
@c }}}
@c {{{ server
@node server directive
@@ -3199,10 +3166,11 @@ Valid measurements with corresponding compensations are logged to the
@c {{{ user
@node user directive
@subsection user
-The @code{user} directive sets the name of the user to which will
-@code{chronyd} switch on initialisation to drop root privileges.
-So far, it works only on Linux when compiled with capabilities support.
-Setting the name to root will disable it.
+The @code{user} directive sets the name of the system user to which
+@code{chronyd} will switch after start in order to drop root privileges.
+It may be set to a non-root user only when @code{chronyd} is compiled with
+support for Linux capabilities (libcap) or on NetBSD with the
+@code{/dev/clockctl} device.
The default value is @code{@DEFAULT_USER@}.
@c }}}
@@ -3234,7 +3202,7 @@ chronyc
at the command line. The prompt @code{chronyc} is displayed whilst
chronyc is expecting input from the user, when it is being run from a
terminal. If chronyc's input or output are redirected from/to a file,
-the prompt is now shown.
+the prompt is not shown.
When you are finished entering commands, the commands @code{exit} or
@code{quit} will terminate the program. (Entering @key{Control-D} will
@@ -3249,9 +3217,9 @@ Chronyc supports the following command line options.
@item -v
Displays the version number of chronyc on the terminal, and exists.
@item -h <host>
-This option allows the user to specify which host running the
-@code{chronyd} program is to be contacted. This allows for remote
-configuration, without having to ssh to the other host first.
+This option allows the user to specify which host (or comma-separated list of
+addresses) running the @code{chronyd} program is to be contacted. This allows
+for remote monitoring, without having to ssh to the other host first.
The default is to contact @code{chronyd} running on the same host as
that where chronyc is being run.
@@ -3262,6 +3230,9 @@ This defaults to the compiled-in default; there would rarely be a need
to change this.
@item -n
This option disables resolving IP addresses to hostnames.
+@item -d
+This option enables printing of debugging messages (if compiled with debugging
+support).
@item -4
With this option hostnames will be resolved only to IPv4 addresses.
@item -6
@@ -3270,13 +3241,9 @@ With this option hostnames will be resolved only to IPv6 addresses.
With this option multiple commands can be specified on the command line.
Each argument will be interpreted as a whole command.
@item -f <conf-file>
-This option can be used to specify an alternate location of the @code{chronyd}
-configuration file (default @file{@SYSCONFDIR@/chrony.conf}). The configuration file is
-needed for the `-a' option.
+This option is ignored and is provided only for compatibility.
@item -a
-With this option @code{chronyc} will try to authenticate automatically on
-start. It will read the configuration file, read the command key from the
-keyfile and run the authhash and password commands.
+This option is ignored and is provided only for compatibility.
@end table
@c }}}
@c {{{ SS:Security with chronyc
@@ -3285,51 +3252,49 @@ keyfile and run the authhash and password commands.
Many of the commands available through chronyc have a fair amount of
power to reconfigure the run-time behaviour of @code{chronyd}. Consequently,
@code{chronyc} is quite dangerous for the integrity of the target
-system's clock performance. Having access to @code{chronyd} via chronyc is
-more or less equivalent to being able to modify @code{chronyd's} configuration
-file (typically @file{@SYSCONFDIR@/chrony.conf}) and to restart @code{chronyd}.
-
-Chronyc also provides a number of monitoring (as opposed to commanding)
-commands, which will not affect the behaviour of @code{chronyd}. However, you
-may still want to restrict access to these commands.
+system's clock performance. Having access to @code{chronyd} via @code{chronyc}
+is more or less equivalent to being able to modify @code{chronyd's}
+configuration file (typically @file{@SYSCONFDIR@/chrony.conf}) and to restart
+@code{chronyd}.
-In view of this, access to some of the capabilities of chronyc will
-usually be tightly controlled. There are two mechanisms supported:
+@code{chronyc} also provides a number of monitoring (as opposed to
+commanding or configuration) commands, which will not affect the behaviour of
+@code{chronyd}. However, you may still want to restrict access to these
+commands.
-@enumerate 1
-@item
-The set of hosts from which @code{chronyd} will accept commands can be
-restricted. By default, commands will only be accepted from the same
-host that @code{chronyd} is running on.
-@item
-Any command that actually reconfigures some aspect of @code{chronyd's}
-behaviour requires the user of chronyc to know a password. This
-password is specified in @code{chronyd's} keys file (@pxref{keyfile directive})
-and specified via the commandkey option in its configuration file
-(@pxref{commandkey directive}).
-@end enumerate
+There are two ways how @code{chronyc} can access @code{chronyd}. One is the
+Internet Protocol (IPv4 or IPv6) and the other is a Unix domain socket, which
+is accessible only locally by the root or chrony user (by default
+@code{@CHRONYSOCKDIR@/chronyd.sock}).
-Only the following commands can be used @emph{without} providing a
-password:
+Only the following monitoring commands are allowed from the internet:
@itemize @bullet
@item @code{activity}
-@item @code{authhash}
-@item @code{dns}
-@item @code{exit}
-@item @code{help}
-@item @code{password}
-@item @code{quit}
+@item @code{manual list}
@item @code{rtcdata}
@item @code{smoothing}
@item @code{sources}
@item @code{sourcestats}
@item @code{tracking}
-@item @code{waitsync}
+@item @code{waitsync}.
@end itemize
-All other commands require a password to have been specified previously,
-because they affect @code{chronyd's} operation.
+The set of hosts from which @code{chronyd} will accept these commands can be
+restricted. By default, the commands will be accepted only from the localhost
+(127.0.0.1 or ::1).
+
+All other commands are allowed only through the Unix domain socket. When sent
+over the internet, @code{chronyd} will respond with a @code{Not authorised}
+error, even if it's from the localhost.
+
+In @code{chrony} versions before 2.2 the commands had to be authenticated with
+a password and they were allowed from the internet, but that is no longer
+supported.
+
+By default, @code{chronyc} tries to connect to the Unix domain socket first.
+If that fails (e.g. because @code{chronyc} is running under a non-root user),
+it will try to connect to 127.0.0.1 and then ::1.
@c }}}
@c {{{ SS:Chronyc command reference
@node Chronyc command reference
@@ -3346,14 +3311,13 @@ interface.
* add server command:: Add a new NTP server
* allow all command:: Allowing NTP client access
* allow command:: Allowing NTP client access
-* authhash command:: Set the command authentication hash function
* burst command:: Initiating a rapid set of measurements
* clients command:: Show clients that have accessed the server
-* cmdaccheck command:: Verifying command client access
-* cmdallow all command:: Allowing command client access
-* cmdallow command:: Allowing command client access
-* cmddeny all command:: Denying command client access
-* cmddeny command:: Denying command client access
+* cmdaccheck command:: Verifying monitoring client access
+* cmdallow all command:: Allowing monitoring client access
+* cmdallow command:: Allowing monitoring client access
+* cmddeny all command:: Denying monitoring client access
+* cmddeny command:: Denying monitoring client access
* cyclelogs command:: Close and re-open open log files
* delete command:: Remove an NTP server or peer
* deny all command:: Denying NTP client access
@@ -3374,9 +3338,9 @@ interface.
* minstratum command:: Set minimum stratum for a source
* offline command:: Warn that connectivity to a source will be lost
* online command:: Warn that connectivity to a source has been restored
-* password command:: Provide password needed for most commands
* polltarget command:: Set poll target for a source
* quit command:: Exit from chronyc
+* refresh command:: Refresh IP addresses
* reselect command:: Reselect synchronisation source
* reselectdist command:: Set improvement in distance needed to reselect a source
* retries command:: Set maximum number of retries
@@ -3504,24 +3468,6 @@ allow
The effect of each of these examples is the same as that of the @code{allow}
directive in the configuration file.
@c }}}
-@c {{{ authhash
-@node authhash command
-@subsubsection authhash
-This command selects the hash function used for authenticating user commands.
-For successful authentication the hash function has to be the same as the
-function specified for the command key in the keys file on the server
-(@pxref{keyfile directive}). It needs to be selected before the
-@code{password} command is used. The default hash function is MD5.
-
-An example is
-
-@example
-authhash SHA1
-@end example
-
-The authhash command is run automatically on start if @code{chronyc} was
-started with the `-a' option.
-@c }}}
@c {{{ burst
@node burst command
@subsubsection burst
@@ -3614,14 +3560,15 @@ burst 2/10 foo.example.net
@comment node-name, next, previous, up
@subsubsection clients
This command shows a list of all clients that have accessed the server,
-through either the NTP or command/monitoring ports. There are no arguments.
+through either the NTP or command/monitoring ports. It doesn't include
+access to the Unix domain comamnd socket. There are no arguments.
An example of the output is
@example
Hostname Client Peer CmdAuth CmdNorm CmdBad LstN LstC
========================= ====== ====== ====== ====== ====== ==== ====
-localhost 0 0 15 1 0 29y 0
+localhost 0 0 0 1 0 29y 0
aardvark.xxx 4 0 0 0 0 49 29y
badger.xxx 4 0 0 0 0 6 29y
@end example
@@ -3643,9 +3590,9 @@ client mode packet.
The number of times the client has accessed the server using an NTP
symmetric active mode packet.
@item
-The number of authenticated command packets that have been processed
-from the client (i.e. those following a successful @code{password}
-command).
+The number of authenticated command packets that have been processed from the
+client. Authentication is no longer supported in command packets, so the
+number should be always zero.
@item
The number of unauthenticated command packets that have been processed
from the client.
@@ -3665,7 +3612,7 @@ of that type has ever been received.
@node cmdaccheck command
@subsubsection cmdaccheck
This command is similar to the @code{accheck} command, except that it is
-used to check whether command access is permitted from a named host.
+used to check whether monitoring access is permitted from a named host.
Examples of use are as follows:
@@ -3678,30 +3625,30 @@ cmdaccheck 2001:db8::1
@c {{{ cmdallow all
@node cmdallow all command
@subsubsection cmdallow all
-This is similar to the @code{allow all} command, except that it is used to@c {{{
-allow particular hosts or subnets to use the chronyc program to interact@c }}}
-with @code{chronyd} on the current host.
+This is similar to the @code{allow all} command, except that it is used to
+allow particular hosts or subnets to use @code{chronyc} to monitor with
+@code{chronyd} on the current host.
@c }}}
@c {{{ cmdallow
@node cmdallow command
@subsubsection cmdallow
-This is similar to the @code{allow} command, except that it is used to
-allow particular hosts or subnets to use the chronyc program to interact
-with @code{chronyd} on the current host.
+This is similar to the @code{allow} command, except that it is used to allow
+particular hosts or subnets to use @code{chronyc} to monitor with
+@code{chronyd} on the current host.
@c }}}
@c {{{ cmddeny all
@node cmddeny all command
@subsubsection cmddeny all
-This is similar to the @code{deny all} command, except that it is used
-to allow particular hosts or subnets to use the chronyc program to
-interact with @code{chronyd} on the current host.
+This is similar to the @code{deny all} command, except that it is used to allow
+particular hosts or subnets to use @code{chronyc} to monitor @code{chronyd} on
+the current host.
@c }}}
@c {{{ cmddeny
@node cmddeny command
@subsubsection cmddeny
-This is similar to the @code{deny} command, except that it is used to
-allow particular hosts or subnets to use the chronyc program to interact
-with @code{chronyd} on the current host.
+This is similar to the @code{deny} command, except that it is used to allow
+particular hosts or subnets to use @code{chronyc} to monitor @code{chronyd} on
+the current host.
@c }}}
@c {{{ cyclelogs
@node cyclelogs command
@@ -3712,7 +3659,7 @@ periodically purged. An example of how to do this is shown below.
@example
% mv /var/log/chrony/measurements.log /var/log/chrony/measurements1.log
-% chronyc -a cyclelogs
+% chronyc cyclelogs
% ls -l /var/log/chrony
-rw-r--r-- 1 root root 0 Jun 8 18:17 measurements.log
-rw-r--r-- 1 root root 12345 Jun 8 18:17 measurements1.log
@@ -4181,40 +4128,6 @@ particular source or sources has been restored.
The syntax is identical to that of the @code{offline} command, see
@ref{offline command}.
@c }}}
-@c {{{ password
-@node password command
-@subsubsection password
-The password command is used to allow chronyc to send privileged
-commands to @code{chronyd}. The password can either be entered on the command
-line, or can be entered without echoing. The syntax for entering the
-password on the command line is as follows
-
-@example
-password xyzzy
-password ASCII:xyzzy
-password HEX:78797a7a79
-@end example
-
-To enter the password without it being echoed, enter
-
-@example
-password
-@end example
-
-The computer will respond with a @samp{Password:} prompt, at which you
-should enter the password and press return.
-
-The password can be encoded as a string of characters not containing a space
-with optional @code{ASCII:} prefix or as a hexadecimal number with @code{HEX:}
-prefix. It has to match @code{chronyd's} currently defined command key
-(@pxref{commandkey directive}). If the command key was specified with a
-different hash function than MD5, it's necessary to select the hash function
-with the @code{authhash} command (@pxref{authhash command}) before entering the
-password.
-
-The password command is run automatically on start if @code{chronyc} was
-started with the `-a' option.
-@c }}}
@c {{{ polltarget
@node polltarget command
@subsubsection polltarget
@@ -4247,6 +4160,17 @@ to 12.
The quit command exits from chronyc and returns the user to the shell
(same as the exit command).
@c }}}
+@c {{{ refresh command
+@node refresh command
+@subsubsection refresh
+The @code{refresh} command can be used to force @code{chronyd} to resolve the
+names of configured sources to IP addresses again, e.g. after suspending and
+resuming the machine in a different network.
+
+Sources that stop responding will be replaced with newly resolved addresses
+automatically after 8 polling intervals, but this command may still be useful
+to replace them immediately and not wait until they are marked as unreachable.
+@c }}}
@c {{{ reselect command
@node reselect command
@subsubsection reselect
@@ -4587,9 +4511,7 @@ in milliseconds. If no response is received from @code{chronyd}, the timeout is
doubled and the request is resent. The maximum number of retries is configured
with the @code{retries} command (@pxref{retries command}).
-By default, the timeout is 1000 milliseconds or 100 milliseconds if
-@code{chronyc} is contacting localhost (i.e. the `-h' option wasn't specified)
-and @code{chronyd} was compiled with asynchronous name resolving.
+By default, the timeout is 1000 milliseconds.
@c }}}
@c {{{ tracking
@node tracking command
@@ -4649,12 +4571,6 @@ true time (which it reports to NTP clients when it is operating in
server mode). The value reported on this line is the difference due to
this effect.
-On systems other than Linux, @code{chronyd} doesn't
-adjust the fundamental rate of the system clock, so keeps the system
-time correct by periodically making offsets to it as though an error had
-been measured. The build up of these offsets will be observed in this
-report.
-
@item Last offset
This is the estimated local offset on the last clock update.
@@ -4761,10 +4677,10 @@ with the @code{rtcautotrim} directive (@pxref{rtcautotrim directive}).
@subsubsection waitsync
The @code{waitsync} command waits for @code{chronyd} to synchronise.
-Up to three optional arguments can be specified, the first is the maximum
-number of tries in 10 second intervals before giving up and returning a
-non-zero error code. When 0 is specified, or there are no arguments, the
-number of tries will not be limited.
+Up to four optional arguments can be specified, the first is the maximum
+number of tries before giving up and returning a non-zero error code. When 0
+is specified, or there are no arguments, the number of tries will not be
+limited.
The second and third arguments are the maximum allowed remaining correction of
the system clock and the maximum allowed skew (in ppm) as reported by the
@@ -4772,14 +4688,18 @@ the system clock and the maximum allowed skew (in ppm) as reported by the
and @code{Skew} fields. If not specified or zero, the value will not be
checked.
+The fourth argument is the interval in which the check is repeated. The
+interval is 10 seconds by default.
+
An example is
@example
waitsync 60 0.01
@end example
-which will wait up to about 10 minutes for @code{chronyd} to synchronise to a
-source and the remaining correction to be less than 10 milliseconds.
+which will wait up to about 10 minutes (60 times 10 seconds) for @code{chronyd}
+to synchronise to a source and the remaining correction to be less than 10
+milliseconds.
@c }}}
@c {{{ writertc
@node writertc command
diff --git a/chrony.txt b/chrony.txt
deleted file mode 100644
index 32fc461..0000000
--- a/chrony.txt
+++ /dev/null
@@ -1,4608 +0,0 @@
-User guide for the chrony suite
-*******************************
-
-1 Introduction
-**************
-
-1.1 Overview
-============
-
-chrony is a versatile implementation of the Network Time Protocol (NTP).
-It can synchronize the system clock with NTP servers, reference clocks
-(e.g. GPS receiver), and manual input using wristwatch and keyboard.
-It can also operate as an NTPv4 (RFC 5905) server and peer to provide a
-time service to other computers in the network.
-
- It is designed to perform well in a wide range of conditions,
-including intermittent network connections, heavily congested networks,
-changing temperatures (ordinary computer clocks are sensitive to
-temperature), and systems that do not run continuosly, or run on a
-virtual machine.
-
- Typical accuracy between two machines on a LAN is in tens, or a few
-hundreds, of microseconds; over the Internet, accuracy is typically
-within a few milliseconds. With a good hardware reference clock
-sub-microsecond accuracy is possible.
-
- Two programs are included in chrony, 'chronyd' is a daemon that can
-be started at boot time and 'chronyc' is a command-line interface
-program which can be used to monitor 'chronyd''s performance and to
-change various operating parameters whilst it is running.
-
- The IP addresses from which 'chronyc' clients may connect can be
-tightly controlled. The default is just the computer that 'chronyd'
-itself is running on.
-
-1.2 Acknowledgements
-====================
-
-The 'chrony' suite makes use of the algorithm known as _RSA Data
-Security, Inc. MD5 Message-Digest Algorithm_ for authenticating
-messages between different machines on the network.
-
- In writing the 'chronyd' program, extensive use has been made of RFC
-1305 and RFC 5905, written by David Mills. The source code of the NTP
-reference implementation has been used to check details of the protocol.
-
-1.3 Availability
-================
-
-1.3.1 Getting the software
---------------------------
-
-Links on the chrony home page (http://chrony.tuxfamily.org) describe how
-to obtain the software.
-
-1.3.2 Platforms
----------------
-
-Although most of the program is portable between Unix-like systems,
-there are parts that have to be tailored to each specific vendor's
-system. These are the parts that interface with the operating system's
-facilities for adjusting the system clock; different operating systems
-may provide different function calls to achieve this, and even where the
-same function is used it may have different quirks in its behaviour.
-
- The software is known to work on Linux, FreeBSD, NetBSD, Mac OS X and
-Solaris. Closely related systems may work too. Porting the software to
-other systems (particularly to those supporting an 'adjtime' system
-call) should not be difficult, however it requires access to such
-systems to test out the driver.
-
-1.4 Relationship to other software packages
-===========================================
-
-1.4.1 ntpd
-----------
-
-The 'reference' implementation of the Network Time Protocol is the
-program 'ntpd', available via The NTP home page (http://www.ntp.org/).
-
- One of the main differences between 'ntpd' and 'chronyd' is in the
-algorithms used to control the computer's clock. Things 'chronyd' can
-do better than 'ntpd':
-
- * 'chronyd' can perform usefully in an environment where access to
- the time reference is intermittent. 'ntpd' needs regular polling
- of the reference to work well.
- * 'chronyd' can usually synchronise the clock faster and with better
- time accuracy.
- * 'chronyd' quickly adapts to sudden changes in the rate of the clock
- (e.g. due to changes in the temperature of the crystal
- oscillator). 'ntpd' may need a long time to settle down again.
- * 'chronyd' can perform well even when the network is congested for
- longer periods of time.
- * 'chronyd' in the default configuration never steps the time to not
- upset other running programs. 'ntpd' can be configured to never
- step the time too, but it has to use a different means of adjusting
- the clock, which has some disadvantages.
- * 'chronyd' can adjust the rate of the clock on Linux in a larger
- range, which allows it to operate even on machines with broken or
- unstable clock (e.g. in some virtual machines).
-
- Things 'chronyd' can do that 'ntpd' can't:
-
- * 'chronyd' provides support for isolated networks whether the only
- method of time correction is manual entry (e.g. by the
- administrator looking at a clock). 'chronyd' can look at the
- errors corrected at different updates to work out the rate at which
- the computer gains or loses time, and use this estimate to trim the
- computer clock subsequently.
-
- * 'chronyd' provides support to work out the gain or loss rate of the
- 'real-time clock', i.e. the clock that maintains the time when the
- computer is turned off. It can use this data when the system boots
- to set the system time from a corrected version of the real-time
- clock. These real-time clock facilities are only available on
- Linux, so far.
-
- Things 'ntpd' can do that 'chronyd' can't:
-
- * 'ntpd' supports all operating modes from RFC 5905, including
- broadcast, multicast and manycast client / server. It supports the
- orphan mode and it also supports authentication based on public-key
- cryptography described in RFC 5906.
-
- * 'ntpd' has been ported to more types of computer / operating
- system.
-
- * 'ntpd' includes drivers for many reference clocks. 'chronyd'
- relies on other programs (e.g. gpsd) to access the data from the
- reference clocks.
-
-1.4.2 timed
------------
-
-'timed' is a program that is part of the BSD networking suite. It uses
-broadcast packets to find all machines running the daemon within a
-subnet. The machines elect a master which periodically measures the
-system clock offsets of the other computers using ICMP timestamps.
-Corrections are sent to each member as a result of this process.
-
- Problems that may arise with 'timed' are :
-
- * Because it uses broadcasts, it is not possible to isolate its
- functionality to a particular group of computers; there is a risk
- of upsetting other computers on the same network (e.g. where a
- whole company is on the same subnet but different departments are
- independent from the point of view of administering their
- computers.)
- * The update period appears to be 10 minutes. Computers can build up
- significant offsets relative to each other in that time. If a
- computer can estimate its rate of drift it can keep itself closer
- to the other computers between updates by adjusting its clock every
- few seconds. 'timed' does not seem to do this.
- * 'timed' does not have any integrated capability for feeding
- real-time into its estimates, or for estimating the average rate of
- time loss/gain of the machines relative to real-time (unless one of
- the computers in the group has access to an external reference and
- is always appointed as the 'master').
-
- 'timed' does have the benefit over 'chronyd' that for isolated
-networks of computers, they will track the 'majority vote' time. For
-such isolated networks, 'chronyd' requires one computer to be the
-'master' with the others slaved to it. If the master has a particular
-defective clock, the whole set of computers will tend to slip relative
-to real time (but they _will_ stay accurate relative to one another).
-
-1.5 Distribution rights and (lack of) warranty
-==============================================
-
-Chrony may be distributed in accordance with the GNU General Public
-License version 2, reproduced in *Note GPL::.
-
-1.6 Bug reporting and suggestions
-=================================
-
-If you think you've found a bug in chrony, or have a suggestion, please
-let us know. You can join chrony users mailing list by sending a
-message with the subject subscribe to
-<chrony-users-request@chrony.tuxfamily.org>. Only subscribers can post
-to the list.
-
- When you are reporting a bug, please send us all the information you
-can. Unfortunately, chrony has proven to be one of those programs where
-it is very difficult to reproduce bugs in a different environment. So
-we may have to interact with you quite a lot to obtain enough extra
-logging and tracing to pin-point the problem in some cases. Please be
-patient and plan for this!
-
- Of course, if you can debug the problem yourself and send us a source
-code patch to fix it, we will be very grateful!
-
-1.7 Contributions
-=================
-
-Although chrony is now a fairly mature and established project, there
-are still areas that could be improved. If you can program in C and
-have some expertise in these areas, you might be able to fill the gaps.
-
- Particular areas that need addressing are :
-
- 1. Porting to other Unices
-
- This involves creating equivalents of sys_solaris.c, sys_linux.c
- etc for the new system.
-
- 2. Porting to Windows NT
-
- A small amount of work on this was done under Cygwin. Only the
- sorting out of the include files has really been achieved so far.
- The two main areas still to address are
-
- 1. The system clock driver.
- 2. How to make chronyd into an NT service (i.e. what to replace
- fork(), setsid() etc with so that chronyd can be automatically
- started in the system bootstrap.
-
- 3. More drivers for reference clock support
-
-2 Installation
-**************
-
-The software is distributed as source code which has to be compiled.
-The source code is supplied in the form of a gzipped tar file, which
-unpacks to a subdirectory identifying the name and version of the
-program.
-
- After unpacking the source code, change directory into it, and type
-
- ./configure
-
- This is a shell script that automatically determines the system type.
-There is a single optional parameter, '--prefix' which indicates the
-directory tree where the software should be installed. For example,
-
- ./configure --prefix=/opt/free
-
- will install the 'chronyd' daemon into /opt/free/sbin and the
-'chronyc' control program into /opt/free/bin. The default value for the
-prefix is /usr/local.
-
- The configure script assumes you want to use gcc as your compiler.
-If you want to use a different compiler, you can configure this way:
-
- CC=cc CFLAGS=-O ./configure --prefix=/opt/free
-
- for Bourne-family shells, or
-
- setenv CC cc
- setenv CFLAGS -O
- ./configure --prefix=/opt/free
-
- for C-family shells.
-
- If the software cannot (yet) be built on your system, an error
-message will be shown. Otherwise, 'Makefile' will be generated.
-
- If editline or readline library is available, chronyc will be built
-with line editing support. If you don't want this, specify the
--disable-readline flag to configure. Please refer to *note line editing
-support:: for more information.
-
- If a 'timepps.h' header is available (e.g. from the LinuxPPS project
-(http://linuxpps.org/)), 'chronyd' will be built with PPS API reference
-clock driver. If the header is installed in a location that isn't
-normally searched by the compiler, you can add it to the searched
-locations by setting 'CPPFLAGS' variable to '-I/path/to/timepps'.
-
- Now type
-
- make
-
- to build the programs.
-
- If you want to build the manual in plain text, HTML and info
-versions, type
-
- make docs
-
- Once the programs have been successfully compiled, they need to be
-installed in their target locations. This step normally needs to be
-performed by the superuser, and requires the following command to be
-entered.
-
- make install
-
- This will install the binaries, plain text manual and manpages.
-
- To install the HTML and info versions of the manual as well, enter
-the command
-
- make install-docs
-
- If you want chrony to appear in the top level info directory listing,
-you need to run the 'install-info' command manually after this step.
-'install-info' takes 2 arguments. The first is the path to the
-'chrony.info' file you have just installed. This will be the argument
-you gave to -prefix when you configured ('/usr/local' by default), with
-'/share/info/chrony.info' on the end. The second argument is the
-location of the file called 'dir'. This will typically be
-'/usr/share/info/dir'. So the typical command line would be
-
- install-info /usr/local/share/info/chrony.info /usr/share/info/dir
-
- Now that the software is successfully installed, the next step is to
-set up a configuration file. The default location of the file is
-'/etc/chrony.conf'. Several examples of configuration with comments are
-included in the examples directory. Suppose you want to use public NTP
-servers from the pool.ntp.org project as your time reference. A minimal
-useful configuration file could be
-
- pool pool.ntp.org iburst
- makestep 10 3
- rtcsync
-
- Then, 'chronyd' can be run.
-
-2.1 Support for line editing libraries
-======================================
-
-Chronyc can be built with support for line editing, this allows you to
-use the cursor keys to replay and edit old commands. Two libraries are
-supported which provide such functionality, editline and GNU readline.
-
- Please note that readline since version 6.0 is licensed under GPLv3+
-which is incompatible with chrony's license GPLv2. You should use
-editline instead if you don't want to use older readline versions.
-
- The configure script will automatically enable the line editing
-support if one of the supported libraries is available. If they are
-both available, the editline library will be used.
-
- If you don't want to use it (in which case chronyc will use a minimal
-command line interface), invoke configure like this:
-
- ./configure --disable-readline other-options...
-
- If you have editline, readline or ncurses installed in locations that
-aren't normally searched by the compiler and linker, you need to use
-extra options:
-
-'--with-readline-includes=directory_name'
- This defines the name of the directory above the one where
- 'readline.h' is. 'readline.h' is assumed to be in 'editline' or
- 'readline' subdirectory of the named directory.
-
-'--with-readline-library=directory_name'
- This defines the directory containing the 'libedit.a' or
- 'libedit.so' file, or 'libreadline.a' or 'libreadline.so' file.
-
-'--with-ncurses-library=directory_name'
- This defines the directory containing the 'libncurses.a' or
- 'libncurses.so' file.
-
-2.2 Extra options for package builders
-======================================
-
-The configure and make procedures have some extra options that may be
-useful if you are building a distribution package for chrony.
-
- The -infodir=DIR option to configure specifies an install directory
-for the info files. This overrides the 'info' subdirectory of the
-argument to the -prefix option. For example, you might use
-
- ./configure --prefix=/usr --infodir=/usr/share/info
-
- The -mandir=DIR option to configure specifies an install directory
-for the man pages. This overrides the 'man' subdirectory of the
-argument to the -prefix option.
-
- ./configure --prefix=/usr --infodir=/usr/share/info --mandir=/usr/share/man
-
- to set both options together.
-
- The final option is the DESTDIR option to the make command. For
-example, you could use the commands
-
- ./configure --prefix=/usr --infodir=/usr/share/info --mandir=/usr/share/man
- make all docs
- make install DESTDIR=./tmp
- cd tmp
- tar cvf - . | gzip -9 > chrony.tar.gz
-
- to build a package. When untarred within the root directory, this
-will install the files to the intended final locations.
-
-3 Typical operating scenarios
-*****************************
-
-3.1 Computers connected to the internet
-=======================================
-
-In this section we discuss how to configure chrony for computers that
-are connected to the Internet (or to any network containing true NTP
-servers which ultimately derive their time from a reference clock)
-permanently or most of the time.
-
- To operate in this mode, you will need to know the names of the NTP
-server machines you wish to use. You may be able to find names of
-suitable servers by one of the following methods:
-
- * Your institution may already operate servers on its network.
- Contact your system administrator to find out.
-
- * Your ISP probably has one or more NTP servers available for its
- customers.
-
- * Somewhere under the NTP homepage there is a list of public stratum
- 1 and stratum 2 servers. You should find one or more servers that
- are near to you -- check that their access policy allows you to use
- their facilities.
-
- * Use public servers from the pool.ntp.org project
- (http://www.pool.ntp.org/).
-
- Assuming that you have found some servers, you need to set up a
-configuration file to run chrony. The (compiled-in) default location
-for this file is '/etc/chrony.conf'. Assuming that your NTP servers are
-called 'foo.example.net', 'bar.example.net' and 'baz.example.net', your
-'chrony.conf' file could contain as a minimum
-
- server foo.example.net
- server bar.example.net
- server baz.example.net
-
- However, you will probably want to include some of the other
-directives described later. The following directives may be
-particularly useful : 'driftfile', 'makestep', 'rtcsync'. Also, the
-'iburst' server option is useful to speed up the initial
-synchronization. The smallest useful configuration file would look
-something like
-
- server foo.example.net iburst
- server bar.example.net iburst
- server baz.example.net iburst
- driftfile /var/lib/chrony/drift
- makestep 10 3
- rtcsync
-
- When using a pool of NTP servers (one name is used for multiple
-servers which may change over time), it's better to specify them with
-the 'pool' directive instead of multiple 'server' directives. The
-configuration file could in this case look like
-
- pool pool.ntp.org iburst
- driftfile /var/lib/chrony/drift
- makestep 10 3
- rtcsync
-
-3.2 Infrequent connection to true NTP servers
-=============================================
-
-In this section we discuss how to configure chrony for computers that
-have occasional connections to the internet.
-
-3.2.1 Setting up the configuration file for infrequent connections
-------------------------------------------------------------------
-
-As in the previous section, you will need access to NTP servers on the
-internet. The same remarks apply for how to find them.
-
- In this case, you will need some additional configuration to tell
-'chronyd' when the connection to the internet goes up and down. This
-saves the program from continuously trying to poll the servers when they
-are inaccessible.
-
- Again, assuming that your NTP servers are called 'foo.example.net',
-'bar.example.net' and 'baz.example.net', your 'chrony.conf' file would
-need to contain something like
-
- server foo.example.net
- server bar.example.net
- server baz.example.net
-
- However, your computer will keep trying to contact the servers to
-obtain timestamps, even whilst offline. If you operate a dial-on-demand
-system, things are even worse, because the link to the internet will
-keep getting established.
-
- For this reason, it would be better to specify this part of your
-configuration file in the following way:
-
- server foo.example.net offline
- server bar.example.net offline
- server baz.example.net offline
-
- The 'offline' keyword indicates that the servers start in an offline
-state, and that they should not be contacted until 'chronyd' receives
-notification that the link to the internet is present.
-
- In order to notify 'chronyd' of the presence of the link, you will
-need to be able to log in to it with the program 'chronyc'. To do this,
-'chronyd' needs to be configured with an administrator password. The
-password is read from a file specified by the 'keyfile' directive. The
-'generatecommandkey' directive can be used to generate a random password
-automatically on the first 'chronyd' start.
-
- The smallest useful configuration file would look something like
-
- server foo.example.net offline
- server bar.example.net offline
- server baz.example.net offline
- keyfile /etc/chrony.keys
- generatecommandkey
- driftfile /var/lib/chrony/drift
- makestep 10 3
-
- The next section describes how to tell 'chronyd' when the internet
-link goes up and down.
-
-3.2.2 How to tell chronyd when the internet link is available.
---------------------------------------------------------------
-
-To use this option, you will need to configure a command key in
-'chronyd's' configuration file '/etc/chrony.conf', as described in the
-previous section.
-
- To tell 'chronyd' when to start and finish sampling the servers, the
-'online' and 'offline' commands of chronyc need to be used. To give an
-example of their use, we assume that 'pppd' is the program being used to
-connect to the internet, and that chronyc has been installed at its
-default location '/usr/local/bin/chronyc'. We also assume that the
-command key has been set up as described in the previous section.
-
- In the file '/etc/ppp/ip-up' we add the command sequence
-
- /usr/local/bin/chronyc -a online
-
- and in the file '/etc/ppp/ip-down' we add the sequence
-
- /usr/local/bin/chronyc -a offline
-
- 'chronyd's' polling of the servers will now only occur whilst the
-machine is actually connected to the Internet.
-
-3.3 Isolated networks
-=====================
-
-In this section we discuss how to configure chrony for computers that
-never have network conectivity to any computer which ultimately derives
-its time from a reference clock.
-
- In this situation, one computer is selected to be the master
-timeserver. The other computers are either direct clients of the
-master, or clients of clients.
-
- The rate value in the master's drift file needs to be set to the
-average rate at which the master gains or loses time. 'chronyd'
-includes support for this, in the form of the 'manual' directive in the
-configuration file and the 'settime' command in the 'chronyc' program.
-
- If the master is rebooted, 'chronyd' can re-read the drift rate from
-the drift file. However, the master has no accurate estimate of the
-current time. To get around this, the system can be configured so that
-the master can initially set itself to a 'majority-vote' of selected
-clients' times; this allows the clients to 'flywheel' the master across
-its outage.
-
- A typical configuration file for the master (called 'master') might
-be (assuming the clients are in the 192.168.165.x subnet and that the
-master's address is 192.168.169.170)
-
- driftfile /var/lib/chrony/drift
- generatecommandkey
- keyfile /etc/chrony.keys
- initstepslew 10 client1 client3 client6
- local stratum 8
- manual
- allow 192.168.165
-
- For the clients that have to resynchronise the master when it
-restarts, the configuration file might be
-
- server master
- driftfile /var/lib/chrony/drift
- logdir /var/log/chrony
- log measurements statistics tracking
- keyfile /etc/chrony.keys
- generatecommandkey
- local stratum 10
- initstepslew 20 master
- allow 192.168.169.170
-
- The rest of the clients would be the same, except that the 'local'
-and 'allow' directives are not required.
-
-3.4 The home PC with a dial-up connection
-=========================================
-
-3.4.1 Assumptions/how the software works
-----------------------------------------
-
-This section considers the home computer which has a dial-up connection.
-It assumes that Linux is run exclusively on the computer. Dual-boot
-systems may work; it depends what (if anything) the other system does to
-the system's real-time clock.
-
- Much of the configuration for this case is discussed earlier (*note
-Infrequent connection::). This section addresses specifically the case
-of a computer which is turned off between 'sessions'.
-
- In this case, 'chronyd' relies on the computer's real-time clock
-(RTC) to maintain the time between the periods when it is powered up.
-The arrangement is shown in the figure below.
-
- trim if required PSTN
- +---------------------------+ +----------+
- | | | |
- v | | |
- +---------+ +-------+ +-----+ +---+
- | System's| measure error/ |chronyd| |modem| |ISP|
- |real-time|------------------->| |-------| | | |
- | clock | drift rate +-------+ +-----+ +---+
- +---------+ ^ |
- | | |
- +---------------------------+ --o-----o---
- set time at boot up |
- +----------+
- |NTP server|
- +----------+
-
- When the computer is connected to the Internet (via the modem),
-'chronyd' has access to external NTP servers which it makes measurements
-from. These measurements are saved, and straight-line fits are
-performed on them to provide an estimate of the computer's time error
-and rate of gaining/losing time.
-
- When the computer is taken offline from the Internet, the best
-estimate of the gain/loss rate is used to free-run the computer until it
-next goes online.
-
- Whilst the computer is running, 'chronyd' makes measurements of the
-real-time clock (RTC) (via the '/dev/rtc' interface, which must be
-compiled into the kernel). An estimate is made of the RTC error at a
-particular RTC second, and the rate at which the RTC gains or loses time
-relative to true time.
-
- On 2.6 and later kernels, if your motherboard has a HPET, you need to
-enable the 'HPET_EMULATE_RTC' option in your kernel configuration.
-Otherwise, chrony will not be able to interact with the RTC device and
-will give up using it.
-
- When the computer is powered down, the measurement histories for all
-the NTP servers are saved to files (if the 'dumponexit' directive is
-specified in the configuration file), and the RTC tracking information
-is also saved to a file (if the 'rtcfile' directive has been specified).
-These pieces of information are also saved if the 'dump' and 'writertc'
-commands respectively are issued through 'chronyc'.
-
- When the computer is rebooted, 'chronyd' reads the current RTC time
-and the RTC information saved at the last shutdown. This information is
-used to set the system clock to the best estimate of what its time would
-have been now, had it been left running continuously. The measurement
-histories for the servers are then reloaded.
-
- The next time the computer goes online, the previous sessions'
-measurements can contribute to the line-fitting process, which gives a
-much better estimate of the computer's gain/loss rate.
-
- One problem with saving the measurements and RTC data when the
-machine is shut down is what happens if there is a power failure; the
-most recent data will not be saved. Although 'chronyd' is robust enough
-to cope with this, some performance may be lost. (The main danger
-arises if the RTC has been changed during the session, with the
-'trimrtc' command in 'chronyc'. Because of this, 'trimrtc' will make
-sure that a meaningful RTC file is saved out after the change is
-completed).
-
- The easiest protection against power failure is to put the 'dump' and
-'writertc' commands in the same place as the 'offline' command is issued
-to take 'chronyd' offline; because 'chronyd' free-runs between online
-sessions, no parameters will change significantly between going offline
-from the Internet and any power failure.
-
- A final point regards home computers which are left running for
-extended periods and where it is desired to spin down the hard disc when
-it is not in use (e.g. when not accessed for 15 minutes). 'chronyd'
-has been planned so it supports such operation; this is the reason why
-the RTC tracking parameters are not saved to disc after every update,
-but only when the user requests such a write, or during the shutdown
-sequence. The only other facility that will generate periodic writes to
-the disc is the 'log rtc' facility in the configuration file; this
-option should not be used if you want your disc to spin down.
-
-3.4.2 Typical configuration files.
-----------------------------------
-
-To illustrate how a dial-up home computer might be configured, example
-configuration files are shown in this section.
-
- For the '/etc/chrony.conf' file, the following can be used as an
-example.
-
- server foo.example.net maxdelay 0.4 offline
- server bar.example.net maxdelay 0.4 offline
- server baz.example.net maxdelay 0.4 offline
- logdir /var/log/chrony
- log statistics measurements tracking
- driftfile /var/lib/chrony/drift
- keyfile /etc/chrony.keys
- generatecommandkey
- makestep 10 3
- maxupdateskew 100.0
- dumponexit
- dumpdir /var/lib/chrony
- rtcfile /var/lib/chrony/rtc
-
- 'pppd' is used for connecting to the internet. This runs two scripts
-'/etc/ppp/ip-up' and '/etc/ppp/ip-down' when the link goes online and
-offline respectively.
-
- The relevant part of the '/etc/ppp/ip-up' file is
-
- /usr/local/bin/chronyc -a online
-
- and the relevant part of the '/etc/ppp/ip-down' script is
-
- /usr/local/bin/chronyc -a -m offline dump writertc
-
- To start 'chronyd' during the boot sequence, the following is in
-'/etc/rc.d/rc.local' (this is a Slackware system)
-
- if [ -f /usr/local/sbin/chronyd -a -f /etc/chrony.conf ]; then
- /usr/local/sbin/chronyd -r -s
- echo "Start chronyd"
- fi
-
- The placement of this command may be important on some systems. In
-particular, 'chronyd' may need to be started before any software that
-depends on the system clock not jumping or moving backwards, depending
-on the directives in 'chronyd's' configuration file.
-
- For the system shutdown, 'chronyd' should receive a SIGTERM several
-seconds before the final SIGKILL; the SIGTERM causes the measurement
-histories and RTC information to be saved out.
-
-3.5 Other important configuration options
-=========================================
-
-The most common option to include in the configuration file is the
-'driftfile' option. One of the major tasks of 'chronyd' is to work out
-how fast or how slow the system clock runs relative to real time - e.g.
-in terms of seconds gained or lost per day. Measurements over a long
-period are usually required to refine this estimate to an acceptable
-degree of accuracy. Therefore, it would be bad if 'chronyd' had to work
-the value out each time it is restarted, because the system clock would
-not run so accurately whilst the determination is taking place.
-
- To avoid this problem, 'chronyd' allows the gain or loss rate to be
-stored in a file, which can be read back in when the program is
-restarted. This file is called the drift file, and might typically be
-stored in '/var/lib/chrony/drift'. By specifying an option like the
-following
-
- driftfile /var/lib/chrony/drift
-
- in the configuration file ('/etc/chrony.conf'), the drift file
-facility will be activated.
-
-4 Usage reference
-*****************
-
-4.1 Starting chronyd
-====================
-
-If 'chronyd' has been installed to its default location
-'/usr/local/sbin/chronyd', starting it is simply a matter of entering
-the command
-
- /usr/local/sbin/chronyd
-
- Information messages and warnings will be logged to syslog.
-
- If no configuration commands are specified on the command line,
-'chronyd' will read the commands from the configuration file (default
-'/etc/chrony.conf').
-
- The command line options supported are as follows:
-
-'-n'
- When run in this mode, the program will not detach itself from the
- terminal.
-'-d'
- When run in this mode, the program will not detach itself from the
- terminal, and all messages will be sent to the terminal instead of
- to syslog. When 'chronyd' was compiled with debugging support,
- this option can be used twice to print also debugging messages.
-'-f <conf-file>'
- This option can be used to specify an alternate location for the
- configuration file (default '/etc/chrony.conf').
-'-r'
- This option will reload sample histories for each of the servers
- and refclocks being used. These histories are created by using the
- 'dump' command in 'chronyc', or by setting the 'dumponexit'
- directive in the configuration file. This option is useful if you
- want to stop and restart 'chronyd' briefly for any reason, e.g. to
- install a new version. However, it only makes sense on systems
- where the kernel can maintain clock compensation whilst not under
- 'chronyd's' control. The only version where this happens so far is
- Linux. On other systems this option should not be used.
-'-R'
- When this option is used, the 'initstepslew' directive and the
- 'makestep' directive used with a positive limit will be ignored.
- This option is useful when restarting 'chronyd' and can be used in
- conjunction with the '-r' option.
-
-'-s'
- This option will set the system clock from the computer's real-time
- clock. This is analogous to supplying the '-s' flag to the
- '/sbin/hwclock' program during the Linux boot sequence.
-
- Support for real-time clocks is limited at present - the criteria
- are described in the section on the 'rtcfile' directive (*note
- rtcfile directive::).
-
- If used in conjunction with the '-r' flag, 'chronyd' will attempt
- to preserve the old samples after setting the system clock from the
- real time clock (RTC). This can be used to allow 'chronyd' to
- perform long term averaging of the gain or loss rate across system
- reboots, and is useful for dial-up systems that are shut down when
- not in use. For this to work well, it relies on 'chronyd' having
- been able to determine accurate statistics for the difference
- between the RTC and system clock last time the computer was on.
-
- If 'chronyd' doesn't support the RTC on your computer or there is
- no RTC installed, the system clock will be set with this option
- forward to the time of the last modification of the drift file
- (specified by the 'driftfile' directive) to restore the system time
- at which 'chronyd' was previously stopped.
-'-u <user>'
- This option sets the name of the user to which will 'chronyd'
- switch to drop root privileges if compiled with Linux capabilities
- support (default 'root').
-'-q'
- When run in this mode, 'chronyd' will set the system clock once and
- exit. It will not detach from the terminal.
-'-Q'
- This option is similar to '-q', but it will only print the offset
- and not correct the clock.
-'-v'
- This option displays 'chronyd's' version number to the terminal and
- exits.
-'-P <priority>'
- This option will select the SCHED_FIFO real-time scheduler at the
- specified priority (which must be between 0 and 100). This mode is
- supported only on Linux.
-'-m'
- This option will lock chronyd into RAM so that it will never be
- paged out. This mode is only supported on Linux.
-'-4'
- With this option hostnames will be resolved only to IPv4 addresses
- and only IPv4 sockets will be created.
-'-6'
- With this option hostnames will be resolved only to IPv6 addresses
- and only IPv6 sockets will be created.
-
- On systems that support an '/etc/rc.local' file for starting programs
-at boot time, 'chronyd' can be started from there.
-
- On systems with a System V style initialisation, a suitable
-start/stop script might be as shown below. This might be placed in the
-file '/etc/rc2.d/S83chrony'.
-
- #!/bin/sh
- # This file should have uid root, gid sys and chmod 744
- #
-
- killproc() { # kill the named process(es)
- pid=`/usr/bin/ps -e |
- /usr/bin/grep -w $1 |
- /usr/bin/sed -e 's/^ *//' -e 's/ .*//'`
- [ "$pid" != "" ] && kill $pid
- }
-
- case "$1" in
-
- 'start')
- if [ -f /opt/free/sbin/chronyd -a -f /etc/chrony.conf ]; then
- /opt/free/sbin/chronyd
- fi
- ;;
- 'stop')
- killproc chronyd
- ;;
- *)
- echo "Usage: /etc/rc2.d/S83chrony { start | stop }"
- ;;
- esac
-
- (In both cases, you may want to bear in mind that 'chronyd' can step
-the time when it starts. There may be other programs started at boot
-time that could be upset by this, so you may need to consider the
-ordering carefully. However, 'chronyd' will need to start after daemons
-providing services that it may require, e.g. the domain name service.)
-
-4.2 The chronyd configuration file
-==================================
-
-The configuration file is normally called '/etc/chrony.conf'; in fact,
-this is the compiled-in default. However, other locations can be
-specified with a command line option.
-
- Each command in the configuration file is placed on a separate line.
-The following sections describe each of the commands in turn. The
-directives can occur in any order in the file and they are not
-case-sensitive.
-
- The configuration commands can also be specified directly on the
-'chronyd' command line, each argument is parsed as a line and the
-configuration file is ignored.
-
-4.2.1 Comments in the configuration file
-----------------------------------------
-
-The configuration file may contain comment lines. A comment line is any
-line that starts with zero or more spaces followed by any one of the
-following characters:
- * !
- * ;
- * #
- * %
- Any line with this format will be ignored.
-
-4.2.2 acquisitionport
----------------------
-
-By default, 'chronyd' uses a separate client socket for each configured
-server and their source port is chosen arbitrarily by the operating
-system. However, you can use the 'acquisitionport' directive to
-explicitly specify a port and use only one socket (per IPv4/IPv6 address
-family) for all configured servers. This may be useful for getting
-through firewalls. If set to 0, the source port of the socket will be
-chosen arbitrarily.
-
- It may be set to the same port as used by the NTP server (*note port
-directive::) to use only one socket for all NTP packets.
-
- An example of the 'acquisitionport' command is
-
- acquisitionport 1123
-
- This would change the source port used for client requests to
-udp/1123. You could then persuade the firewall administrator to let
-that port through.
-
-4.2.3 allow
------------
-
-The 'allow' command is used to designate a particular subnet from which
-NTP clients are allowed to access the computer as an NTP server.
-
- The default is that no clients are allowed access, i.e. 'chronyd'
-operates purely as an NTP client. If the 'allow' directive is used,
-'chronyd' will be both a client of its servers, and a server to other
-clients.
-
- Examples of use of the command are as follows:
-
- allow foo.example.net
- allow 1.2
- allow 3.4.5
- allow 6.7.8/22
- allow 6.7.8.9/22
- allow 2001:db8::/32
- allow 0/0
- allow ::/0
- allow
-
- The first command allows the named node to be an NTP client of this
-computer. The second command allows any node with an IPv4 address of
-the form 1.2.x.y (with x and y arbitrary) to be an NTP client of this
-computer. Likewise, the third command allows any node with an IPv4
-address of the form 3.4.5.x to have client NTP access. The fourth and
-fifth forms allow access from any node with an IPv4 address of the form
-6.7.8.x, 6.7.9.x, 6.7.10.x or 6.7.11.x (with x arbitrary), i.e. the
-value 22 is the number of bits defining the specified subnet. (In the
-fifth form, the final byte is ignored). The sixth form is used for IPv6
-addresses. The seventh and eighth forms allow access by any IPv4 and
-IPv6 node respectively. The ninth forms allows access by any node (IPv4
-or IPv6).
-
- A second form of the directive, 'allow all', has a greater effect,
-depending on the ordering of directives in the configuration file. To
-illustrate the effect, consider the two examples
-
- allow 1.2.3.4
- deny 1.2.3
- allow 1.2
-
- and
-
- allow 1.2.3.4
- deny 1.2.3
- allow all 1.2
-
- In the first example, the effect is the same regardles of what order
-the three directives are given in. So the 1.2.x.y subnet is allowed
-access, except for the 1.2.3.x subnet, which is denied access, however
-the host 1.2.3.4 is allowed access.
-
- In the second example, the 'allow all 1.2' directives overrides the
-effect of _any_ previous directive relating to a subnet within the
-specified subnet. Within a configuration file this capability is
-probably rather moot; however, it is of greater use for reconfiguration
-at run-time via 'chronyc' (*note allow all command::).
-
- Note, if the 'initstepslew' directive (*note initstepslew
-directive::) is used in the configuration file, each of the computers
-listed in that directive must allow client access by this computer for
-it to work.
-
-4.2.4 bindacqaddress
---------------------
-
-The 'bindacqaddress' directive sets the network interface to which will
-'chronyd' bind its NTP client sockets. The syntax is similar to the
-'bindaddress' and 'bindcmdaddress' directives.
-
- For each of IPv4 and IPv6 protocols, only one 'bindacqaddress'
-directive can be specified.
-
-4.2.5 bindaddress
------------------
-
-The 'bindaddress' directive allows you to restrict the network interface
-to which 'chronyd' will listen for NTP requests. This provides an
-additional level of access restriction above that available through the
-'deny' mechanism.
-
- Suppose you have a local ethernet with addresses in the 192.168.1.0
-subnet together with an internet connection. The ethernet interface's
-IP address is 192.168.1.1. Suppose you want to block all access through
-the internet connection. You could add the line
-
- bindaddress 192.168.1.1
-
- to the configuration file.
-
- For each of IPv4 and IPv6 protocols, only one 'bindaddress' directive
-can be specified. Therefore, it's not useful on computers which should
-serve NTP on multiple network interfaces.
-
-4.2.6 bindcmdaddress
---------------------
-
-The 'bindcmdaddress' directive allows you to specify the network
-interface to which 'chronyd' will listen for command packets (issued by
-'chronyc'). This provides an additional level of access restriction
-above that available through 'cmddeny' mechanism.
-
- By default, 'chronyd' binds to the loopback interface (with addresses
-'127.0.0.1' and '::1'). This blocks all access except from localhost.
-To listen for command packets on all interfaces, you can add the lines
-
- bindcmdaddress 0.0.0.0
- bindcmdaddress ::
-
- to the configuration file.
-
- For each of IPv4 and IPv6 protocols, only one 'bindcmdaddress'
-directive can be specified.
-
-4.2.7 broadcast
----------------
-
-The 'broadcast' directive is used to declare a broadcast address to
-which chronyd should send packets in NTP broadcast mode (i.e. make
-chronyd act as a broadcast server). Broadcast clients on that subnet
-will be able to synchronise.
-
- The syntax is as follows
-
- broadcast 30 192.168.1.255
- broadcast 60 192.168.2.255 12123
- broadcast 60 ff02::101
-
- In the first example, the destination port defaults to 123/udp (the
-normal NTP port). In the second example, the destionation port is
-specified as 12123. The first parameter in each case (30 or 60
-respectively) is the interval in seconds between broadcast packets being
-sent. The second parameter in each case is the broadcast address to
-send the packet to. This should correspond to the broadcast address of
-one of the network interfaces on the computer where chronyd is running.
-
- You can have more than 1 'broadcast' directive if you have more than
-1 network interface onto which you wish to send NTP broadcast packets.
-
- 'chronyd' itself cannot currently act as a broadcast client; it must
-always be configured as a point-to-point client by defining specific NTP
-servers and peers. This broadcast server feature is intended for
-providing a time source to other NTP software (e.g. various MS Windows
-clients).
-
- If ntpd is used as the broadcast client, it will try to use a
-point-to-point client/server NTP access to measure the round-trip delay.
-Thus, the broadcast subnet should also be the subject of an 'allow'
-directive (*note allow directive::).
-
-4.2.8 clientloglimit
---------------------
-
-This directive specifies the maximum size of the memory allocated to log
-client accesses. When the limit is reached, only information for
-clients that have already been logged will be updated. If 0 is
-specified, the memory size will be unlimited. The default is 524288
-bytes.
-
- An example of the use of this directive is
-
- clientloglimit 1048576
-
-4.2.9 cmdallow
---------------
-
-This is similar to the 'allow' directive (*note allow directive::),
-except that it allows control access (rather than NTP client access) to
-a particular subnet or host. (By 'control access' is meant that chronyc
-can be run on those hosts and successfully connect to chronyd on this
-computer.)
-
- The syntax is identical to the 'allow' directive.
-
- There is also a 'cmdallow all' directive with similar behaviour to
-the 'allow all' directive (but applying to control access in this case,
-of course).
-
- Note that 'chronyd' has to be configured with the 'bindcmdaddress'
-directive to not listen only on the loopback interface to actually allow
-remote access.
-
-4.2.10 cmddeny
---------------
-
-This is similar to the 'cmdallow' directive (*note cmdallow
-directive::), except that it denies control access to a particular
-subnet or host, rather than allowing it.
-
- The syntax is identical.
-
- There is also a 'cmddeny all' directive with similar behaviour to the
-'cmdallow all' directive.
-
-4.2.11 cmdport
---------------
-
-The 'cmdport' directive allows the port that is used for run-time
-command and monitoring (via the program 'chronyc') to be altered from
-its default (323/udp). If set to 0, 'chronyd' will not open the port,
-this is useful to disable the 'chronyc' access completely.
-
- An example shows the syntax
-
- cmdport 257
-
- This would make 'chronyd' use 257/udp as its command port.
-('chronyc' would need to be run with the '-p 257' switch to
-inter-operate correctly).
-
-4.2.12 combinelimit
--------------------
-
-When 'chronyd' has multiple sources available for synchronization, it
-has to select one source as the synchronization source. The measured
-offsets and frequencies of the system clock relative to the other
-sources, however, can be combined with the selected source to improve
-the accuracy of the system clock.
-
- The 'combinelimit' directive limits which sources are included in the
-combining algorithm. Their synchronization distance has to be shorter
-than the distance of the selected source multiplied by the value of the
-limit. Also, their measured frequencies have to be close to the
-frequency of the selected source.
-
- By default, the limit is 3. Setting the limit to 0 effectively
-disables the source combining algorithm and only the selected source
-will be used to control the system clock.
-
- The syntax is
-
- combinelimit <limit>
-
-4.2.13 commandkey
------------------
-
-The commandkey command is used to set the key number used for
-authenticating user commands via the chronyc program at run time. This
-allows certain actions of the chronyc program to be restricted to
-administrators.
-
- An example of the commandkey command is
-
- commandkey 20
-
- By default, the key number is 0.
-
- In the key file (see the keyfile command) there should be a line of
-the form
-
- 20 MD5 HEX:B028F91EA5C38D06C2E140B26C7F41EC
-
- When running the chronyc program to perform run-time configuration,
-the command
-
- password HEX:B028F91EA5C38D06C2E140B26C7F41EC
-
- must be entered before any commands affecting the operation of the
-daemon can be entered, or chronyc must be started with the '-a' option
-to run the password command automatically.
-
-4.2.14 corrtimeratio
---------------------
-
-When 'chronyd' makes a time correction, it controls how quickly the
-system clock is slewed (so far only on Linux). This rate affects the
-frequency error of the system clock.
-
- The 'corrtimeratio' directive sets the ratio between the duration in
-which the clock is slewed for an average correction according to the
-source history and the interval in which the corrections are done
-(usually the NTP polling interval). Corrections larger than the average
-take less time and smaller corrections take more time, the amount of the
-correction and the correction time are inversely proportional.
-
- Increasing 'corrtimeratio' improves the overall frequency error of
-the system clock, but increases the overall time error as the
-corrections take longer.
-
- By default, the ratio is set to 3, the time accuracy of the clock is
-preferred over its frequency accuracy.
-
- The syntax is
-
- corrtimeratio 100
-
- The maximum allowed slew rate can be set by the 'maxslewrate'
-directive (*note maxslewrate directive::. The current remaining
-correction is shown in the 'tracking' report (*note tracking command::)
-as the 'System time' value.
-
-4.2.15 deny
------------
-
-This is similar to the 'allow' directive (*note allow directive::),
-except that it denies NTP client access to a particular subnet or host,
-rather than allowing it.
-
- The syntax is identical.
-
- There is also a 'deny all' directive with similar behaviour to the
-'allow all' directive.
-
-4.2.16 driftfile
-----------------
-
-One of the main activities of the 'chronyd' program is to work out the
-rate at which the system clock gains or loses time relative to real
-time.
-
- Whenever 'chronyd' computes a new value of the gain/loss rate, it is
-desirable to record it somewhere. This allows 'chronyd' to begin
-compensating the system clock at that rate whenever it is restarted,
-even before it has had a chance to obtain an equally good estimate of
-the rate during the new run. (This process may take many minutes, at
-least).
-
- The driftfile command allows a file to be specified into which
-'chronyd' can store the rate information. Two parameters are recorded
-in the file. The first is the rate at which the system clock gains or
-loses time, expressed in parts per million, with gains positive.
-Therefore, a value of 100.0 indicates that when the system clock has
-advanced by a second, it has gained 100 microseconds on reality (so the
-true time has only advanced by 999900 microseconds). The second is an
-estimate of the error bound around the first value in which the true
-rate actually lies.
-
- An example of the driftfile command is
-
- driftfile /var/lib/chrony/drift
-
-4.2.17 dumpdir
---------------
-
-To compute the rate of gain or loss of time, 'chronyd' has to store a
-measurement history for each of the time sources it uses.
-
- Certain systems (so far only Linux) have operating system support for
-setting the rate of gain or loss to compensate for known errors. (On
-other systems, 'chronyd' must simulate such a capability by periodically
-slewing the system clock forwards or backwards by a suitable amount to
-compensate for the error built up since the previous slew).
-
- For such systems, it is possible to save the measurement history
-across restarts of 'chronyd' (assuming no changes are made to the system
-clock behaviour whilst it is not running). If this capability is to be
-used (via the dumponexit command in the configuration file, or the dump
-command in chronyc), the dumpdir command should be used to define the
-directory where the measurement histories are saved.
-
- An example of the command is
-
- dumpdir /var/lib/chrony
-
- A source whose reference id (the IP address for IPv4 sources) is
-1.2.3.4 would have its measurement history saved in the file
-'/var/lib/chrony/1.2.3.4.dat'.
-
-4.2.18 dumponexit
------------------
-
-If this command is present, it indicates that 'chronyd' should save the
-measurement history for each of its time sources recorded whenever the
-program exits. (See the dumpdir command above).
-
-4.2.19 fallbackdrift
---------------------
-
-Fallback drifts are long-term averages of the system clock drift
-calculated over exponentially increasing intervals. They are used when
-the clock is no longer synchronised to avoid quickly drifting away from
-true time if there was a short-term deviation in the drift before the
-synchronisation was lost.
-
- The directive specifies the minimum and maximum interval since last
-clock update to switch between fallback drifts. They are defined as a
-power of 2 (in seconds). The syntax is as follows
-
- fallbackdrift 16 19
-
- In this example, the minimum interval is 16 (18 hours) and maximum
-interval is 19 (6 days). The system clock frequency will be set to the
-first fallback 18 hours after last clock update, to the second after 36
-hours, etc. This might be a good setting to cover daily and weekly
-temperature fluctuations.
-
- By default (or if the specified maximum or minimum is 0), no
-fallbacks are used and the clock frequency changes only with new
-measurements from NTP, reference clocks or manual input.
-
-4.2.20 generatecommandkey
--------------------------
-
-With this directive, if the command key is not found on start in the
-file specified by the 'keyfile' directive, 'chronyd' will generate a new
-command key from the /dev/urandom file and write it to the key file.
-
- The generated key will use SHA1 if 'chronyd' is compiled with the
-support, otherwise MD5 will be used.
-
-4.2.21 hwclockfile
-------------------
-
-The 'hwclockfile' directive sets the location of the adjtime file which
-is used by the '/sbin/hwclock' program. With this directive, 'chronyd'
-will parse the file to find out if the RTC keeps local time or UTC. It
-overrides the 'rtconutc' directive (*note rtconutc directive::).
-
- An example of the command is
-
- hwclockfile /etc/adjtime
-
-4.2.22 include
---------------
-
-The 'include' directive includes a specified configuration file. This
-is useful when maintaining configuration on multiple hosts to keep the
-differences in a separate file.
-
- include /etc/chrony/local.conf
-
-4.2.23 initstepslew
--------------------
-
-In normal operation, 'chronyd' slews the time when it needs to adjust
-the system clock. For example, to correct a system clock which is 1
-second slow, 'chronyd' slightly increases the amount by which the system
-clock is advanced on each clock interrupt, until the error is removed.
-(Actually, this is done by calling the 'adjtime()' or similar system
-function which does it for us.) Note that at no time does time run
-backwards with this method.
-
- On most Unix systems it is not desirable to step the system clock,
-because many programs rely on time advancing monotonically forwards.
-
- When the 'chronyd' daemon is initially started, it is possible that
-the system clock is considerably in error. Attempting to correct such
-an error by slewing may not be sensible, since it may take several hours
-to correct the error by this means.
-
- The purpose of the 'initstepslew' directive is to allow 'chronyd' to
-make a rapid measurement of the system clock error at boot time, and to
-correct the system clock by stepping before normal operation begins.
-Since this would normally be performed only at an appropriate point in
-the system boot sequence, no other software should be adversely affected
-by the step.
-
- If the correction required is less than a specified threshold, a slew
-is used instead. This makes it easier to restart 'chronyd' whilst the
-system is in normal operation.
-
- The 'initstepslew' directive takes a threshold and a list of NTP
-servers as arguments. Each of the servers is rapidly polled several
-times, and a majority voting mechanism used to find the most likely
-range of system clock error that is present. A step (or slew) is
-applied to the system clock to correct this error. 'chronyd' then
-enters its normal operating mode.
-
- An example of use of the command is
-
- initstepslew 30 foo.example.net bar.example.net
-
- where 2 NTP servers are used to make the measurement. The '30'
-indicates that if the system's error is found to be 30 seconds or less,
-a slew will be used to correct it; if the error is above 30 seconds, a
-step will be used.
-
- The 'initstepslew' directive can also be used in an isolated LAN
-environment, where the clocks are set manually. The most stable
-computer is chosen as the master, and the other computers are slaved to
-it. If each of the slaves is configured with the local option (see
-below), the master can be set up with an 'initstepslew' directive which
-references some or all of the slaves. Then, if the master machine has
-to be rebooted, the slaves can be relied on to 'flywheel' the time for
-the master.
-
- The 'initstepslew' directive is functionally similar to a combination
-of the 'makestep' and 'server' directives with the 'iburst' option. The
-main difference is that the 'initstepslew' servers are used only before
-normal operation begins and that the foreground 'chronyd' process waits
-for 'initstepslew' to finish before exiting. This is useful to prevent
-programs started in the boot sequence after 'chronyd' from reading the
-clock before it's stepped.
-
-4.2.24 keyfile
---------------
-
-This command is used to specify the location of the file containing
-ID/key pairs for the following 2 uses:
-
- * Authentication of NTP packets.
- * Authentication of administrator commands entered via chronyc.
-
- The format of the command is shown in the example below
-
- keyfile /etc/chrony.keys
-
- The argument is simply the name of the file containing the ID/key
-pairs. The format of the file is shown below
-
- 10 tulip
- 11 hyacinth
- 20 MD5 ASCII:crocus
- 25 SHA1 HEX:1dc764e0791b11fa67efc7ecbc4b0d73f68a070c
- ...
-
- Each line consists of an ID, a name of authentication hash function
-(optional) and a password. The ID can be any unsigned integer in the
-range 0 through 2**32-1, but ID of 0 can be used only for the command
-key and not for the NTP authentication. The hash function is MD5 by
-default, depending on how was 'chronyd' compiled other allowed hash
-functions may be SHA1, SHA256, SHA384, SHA512, RMD128, RMD160, RMD256,
-RMD320, TIGER and WHIRLPOOL. The password can be encoded as a string of
-characters not containing a space with optional 'ASCII:' prefix or as a
-hexadecimal number with 'HEX:' prefix.
-
- The password is used with the hash function to generate and verify a
-message authentication code (MAC) in NTP and command packets. For
-maximum security, it's recommended to use SHA1 or stronger hash
-function. The passwords should be random and they should be as long as
-the output size of the configured hash function, e.g. 160 bits with
-SHA1.
-
- The ID for the chronyc authentication key is specified with the
-commandkey command (see earlier). The command key can be generated
-automatically on start with the 'generatecommandkey' directive.
-
-4.2.25 leapsecmode
-------------------
-
-A leap second is an adjustment that is occasionally applied to UTC to
-keep it close to the mean solar time. When a leap second is inserted,
-the last day of June or December has an extra second 23:59:60.
-
- For computer clocks that is a problem. The Unix time is defined as
-number of seconds since 00:00:00 UTC on 1 January 1970 without leap
-seconds. The system clock cannot have time 23:59:60, every minute has
-60 seconds and every day has 86400 seconds by definition. The inserted
-leap second is skipped and the clock is suddenly ahead of UTC by one
-second. The 'leapsecmode' directive selects how that error is
-corrected. There are four options:
-
-'system'
- When inserting a leap second, the kernel steps the system clock
- backwards by one second when the clock gets to 00:00:00 UTC. When
- deleting a leap second, it steps forward by one second when the
- clock gets to 23:59:59 UTC. This is the default mode when the
- system driver supports leap seconds (currently Linux only).
-'step'
- This is similar to the 'system' mode, except the clock is stepped
- by 'chronyd' instead of the kernel. It can be useful to avoid bugs
- in the kernel code that would be executed in the 'system' mode.
- This is the default mode when the system driver doesn't support
- leap seconds.
-'slew'
- The clock is corrected by slewing started at 00:00:00 UTC when a
- leap second is inserted or 23:59:59 UTC when a leap second is
- deleted. This may be preferred over the 'system' and 'step' modes
- when applications running on the system are sensitive to jumps in
- the system time and it's acceptable that the clock will be off for
- a longer time. On Linux with the default 'maxslewrate' value
- (*note maxslewrate directive::) the correction takes 12 seconds.
-'ignore'
- No correction is applied to the clock for the leap second. The
- clock will be corrected later in normal operation when new
- measurements are made and the estimated offset includes the one
- second error.
-
- An example of the command is
-
- leapsecmode slew
-
- When serving time to NTP clients that can't be configured to correct
-their clocks for a leap second by slewing or they would correct them at
-slightly different rates when it's necessary to keep them close
-together, the 'slew' mode can be combined with the 'smoothtime'
-directive (*note smoothtime directive::) to enable a server leap smear.
-
- When smearing a leap second, the leap status is suppressed on the
-server and the served time is corrected slowly be slewing instead of
-stepping. The clients don't need any special configuration as they
-don't know there is any leap second and they follow the server time
-which eventually brings them back to UTC. Care must be taken to ensure
-they use for synchronization only NTP servers which smear the leap
-second in exactly the same way.
-
- This feature needs to be used carefully, because the server is
-intentionally not serving its best estimate of the true time.
-
- A recommended configuration to enable a server leap smear is:
-
- leapsecmode slew
- maxslewrate 1000
- smoothtime 400 0.001 leaponly
-
- The first directive is necessary to disable the clock step which
-would reset the smoothing process. The second directive limits the
-slewing rate of the local clock to 1000 ppm, which improves the
-stability of the smoothing process when the local correction starts and
-ends. The third directive enables the server time smoothing process.
-It will start when the clock gets to 00:00:00 UTC and it will take 17
-hours 34 minutes to finish. The frequency offset will be changing by
-0.001 ppm per second and will reach maximum of 31.623 ppm. The
-'leaponly' option makes the duration of the leap smear constant and
-allows the clients to safely synchronise with multiple identically
-configured leap smearing servers.
-
-4.2.26 leapsectz
-----------------
-
-This directive is used to set the name of the timezone in the system tz
-database which 'chronyd' can use to find out when will the next leap
-second occur. It will periodically check if the times 23:59:59 and
-23:59:60 are valid on Jun 30 and Dec 31 in the timezone. A useful
-timezone is 'right/UTC'. This is mainly useful with reference clocks
-which don't provide the leap second information. It is not necessary to
-restart 'chronyd' if the tz database is updated with a new leap second
-at least 12 hours before the event.
-
- An example of the command is
-
- leapsectz right/UTC
-
- The following shell command verifies that the timezone contains leap
-seconds and can be used with this directive
-
- $ TZ=right/UTC date -d 'Dec 31 2008 23:59:60'
- Wed Dec 31 23:59:60 UTC 2008
-
-4.2.27 local
-------------
-
-The local keyword is used to allow 'chronyd' to appear synchronised to
-real time (from the viewpoint of clients polling it), even if it has no
-current synchronisation source.
-
- This option is normally used on computers in an isolated network,
-where several computers are required to synchronise to one other, this
-being the "master" which is kept vaguely in line with real time by
-manual input.
-
- An example of the command is
-
- local stratum 10
-
- The value 10 may be substituted with other values in the range 1
-through 15. Stratum 1 indicates a computer that has a true real-time
-reference directly connected to it (e.g. GPS, atomic clock etc) &ndash;
-such computers are expected to be very close to real time. Stratum 2
-computers are those which have a stratum 1 server; stratum 3 computers
-have a stratum 2 server and so on.
-
- A large value of 10 indicates that the clock is so many hops away
-from a reference clock that its time is fairly unreliable. Put another
-way, if the computer ever has access to another computer which is
-ultimately synchronised to a reference clock, it will almost certainly
-be at a stratum less than 10. Therefore, the choice of a high value
-like 10 for the local command prevents the machine's own time from ever
-being confused with real time, were it ever to leak out to clients that
-have visibility of real servers.
-
-4.2.28 lock_all
----------------
-
-The 'lock_all' directive will lock chronyd into RAM so that it will
-never be paged out. This mode is only supported on Linux. This
-directive uses the Linux mlockall() system call to prevent 'chronyd'
-from ever being swapped out. This should result in lower and more
-consistent latency. It should not have significant impact on
-performance as 'chronyd's' memory usage is modest. The mlockall man
-page has more details.
-
-4.2.29 log
-----------
-
-The log command indicates that certain information is to be logged.
-
-'measurements'
- This option logs the raw NTP measurements and related information
- to a file called measurements.log.
-
-'statistics'
- This option logs information about the regression processing to a
- file called statistics.log.
-
-'tracking'
- This option logs changes to the estimate of the system's gain or
- loss rate, and any slews made, to a file called tracking.log.
-
-'rtc'
- This option logs information about the system's real-time clock.
-
-'refclocks'
- This option logs the raw and filtered reference clock measurements
- to a file called refclocks.log.
-'tempcomp'
- This option logs the temperature measurements and system rate
- compensations to a file called tempcomp.log.
-
- The files are written to the directory specified by the logdir
-command.
-
- An example of the command is
-
- log measurements statistics tracking
-
-4.2.29.1 Measurements log file format
-.....................................
-
-An example line (which actually appears as a single line in the file)
-from the measurements log file is shown below.
-
- 2014-10-13 05:40:50 158.152.1.76 N 2 111 111 1111 10 10 1.0 \
- -4.966e-03 2.296e-01 1.577e-05 1.615e-01 7.446e-03
-
- The columns are as follows (the quantities in square brackets are the
-values from the example line above) :
-
- 1. Date [2014-10-13]
- 2. Hour:Minute:Second [05:40:50]. Note that the date/time pair is
- expressed in UTC, not the local time zone.
- 3. IP address of server/peer from which measurement comes
- [158.152.1.76]
- 4. Leap status ('N' means normal, '+' means that the last minute of
- the current month has 61 seconds, '-' means that the last minute of
- the month has 59 seconds, '?' means the remote computer is not
- currently synchronised.) [N]
- 5. Stratum of remote computer. [2]
- 6. RFC 5905 tests 1 through 3 (1=pass, 0=fail) [111]
- 7. RFC 5905 tests 5 through 7 (1=pass, 0=fail) [111]
- 8. Tests for maximum delay, maximum delay ratio and maximum delay dev
- ratio, against defined parameters, and a test for synchronisation
- loop (1=pass, 0=fail) [1111]
- 9. Local poll [10]
- 10. Remote poll [10]
- 11. 'Score' (an internal score within each polling level used to
- decide when to increase or decrease the polling level. This is
- adjusted based on number of measurements currently being used for
- the regression algorithm). [1.0]
- 12. The estimated local clock error ('theta' in RFC 5905). Positive
- indicates that the local clock is slow of the remote source.
- [-4.966e-03].
- 13. The peer delay ('delta' in RFC 5905). [2.296e-01]
- 14. The peer dispersion ('epsilon' in RFC 5905). [1.577e-05]
- 15. The root delay ('DELTA' in RFC 5905). [1.615e-01]
- 16. The root dispersion ('EPSILON' in RFC 5905). [7.446e-03]
-
- A banner is periodically written to the log file to indicate the
-meanings of the columns.
-
-4.2.29.2 Statistics log file format
-...................................
-
-An example line (which actually appears as a single line in the file)
-from the statistics log file is shown below.
-
- 1998-07-22 05:40:50 158.152.1.76 6.261e-03 -3.247e-03 \
- 2.220e-03 1.874e-06 1.080e-06 7.8e-02 16 0 8
-
- The columns are as follows (the quantities in square brackets are the
-values from the example line above) :
-
- 1. Date [1998-07-22]
- 2. Hour:Minute:Second [05:40:50]. Note that the date/time pair is
- expressed in UTC, not the local time zone.
- 3. IP address of server/peer from which measurement comes
- [158.152.1.76]
- 4. The estimated standard deviation of the measurements from the
- source (in seconds). [6.261e-03]
- 5. The estimated offset of the source (in seconds, positive means the
- local clock is estimated to be fast, in this case). [-3.247e-03]
- 6. The estimated standard deviation of the offset estimate (in
- seconds). [2.220e-03]
- 7. The estimated rate at which the local clock is gaining or losing
- time relative to the source (in seconds per second, positive means
- the local clock is gaining). This is relative to the compensation
- currently being applied to the local clock, _not_ to the local
- clock without any compensation. [1.874e-06]
- 8. The estimated error in the rate value (in seconds per second).
- [1.080e-06].
- 9. The ration of |old_rate - new_rate| / old_rate_error. Large values
- indicate the statistics are not modelling the source very well.
- [7.8e-02]
- 10. The number of measurements currently being used for the regression
- algorithm. [16]
- 11. The new starting index (the oldest sample has index 0; this is the
- method used to prune old samples when it no longer looks like the
- measurements fit a linear model). [0, i.e. no samples discarded
- this time]
- 12. The number of runs. The number of runs of regression residuals
- with the same sign is computed. If this is too small it indicates
- that the measurements are no longer represented well by a linear
- model and that some older samples need to be discarded. The number
- of runs for the data that is being retained is tabulated. Values
- of approximately half the number of samples are expected. [8]
-
- A banner is periodically written to the log file to indicate the
-meanings of the columns.
-
-4.2.29.3 Tracking log file format
-.................................
-
-An example line (which actually appears as a single line in the file)
-from the tracking log file is shown below.
-
- 2012-02-23 05:40:50 158.152.1.76 3 340.529 1.606 1.046e-03 N \
- 4 6.849e-03 -4.670e-04
-
- The columns are as follows (the quantities in square brackets are the
-values from the example line above) :
-
- 1. Date [2012-02-03]
- 2. Hour:Minute:Second [05:40:50]. Note that the date/time pair is
- expressed in UTC, not the local time zone.
- 3. The IP address of the server/peer to which the local system is
- synchronised. [158.152.1.76]
- 4. The stratum of the local system. [3]
- 5. The local system frequency (in ppm, positive means the local system
- runs fast of UTC). [340.529]
- 6. The error bounds on the frequency (in ppm) [1.606]
- 7. The estimated local offset at the epoch (which is rapidly corrected
- by slewing the local clock. (In seconds, positive indicates the
- local system is fast of UTC). [1.046e-3]
- 8. Leap status ('N' means normal, '+' means that the last minute of
- this month has 61 seconds, '-' means that the last minute of the
- month has 59 seconds, '?' means the clock is not currently
- synchronised.) [N]
- 9. The number of combined sources. [4]
- 10. The estimated standard deviation of the combined offset (in
- seconds). [6.849e-03]
- 11. The remaining offset correction from the previous update (in
- seconds, positive means the system clock is slow of UTC).
- [-4.670e-04]
-
- A banner is periodically written to the log file to indicate the
-meanings of the columns.
-
-4.2.29.4 Real-time clock log file format
-........................................
-
-An example line (which actually appears as a single line in the file)
-from the measurements log file is shown below.
-
- 1998-07-22 05:40:50 -0.037360 1 -0.037434\
- -37.948 12 5 120
-
- The columns are as follows (the quantities in square brackets are the
-values from the example line above) :
-
- 1. Date [1998-07-22]
- 2. Hour:Minute:Second [05:40:50]. Note that the date/time pair is
- expressed in UTC, not the local time zone.
- 3. The measured offset between the system's real time clock and the
- system ('gettimeofday()') time. In seconds, positive indicates
- that the RTC is fast of the system time. [-0.037360].
- 4. Flag indicating whether the regression has produced valid
- coefficients. (1 for yes, 0 for no). [1]
- 5. Offset at the current time predicted by the regression process. A
- large difference between this value and the measured offset tends
- to indicate that the measurement is an outlier with a serious
- measurement error. [-0.037434].
- 6. The rate at which the RTC is losing or gaining time relative to the
- system clock. In ppm, with positive indicating that the RTC is
- gaining time. [-37.948]
- 7. The number of measurements used in the regression. [12]
- 8. The number of runs of regression residuals of the same sign. Low
- values indicate that a straight line is no longer a good model of
- the measured data and that older measurements should be discarded.
- [5]
- 9. The measurement interval used prior to the measurement being made
- (in seconds). [120]
-
- A banner is periodically written to the log file to indicate the
-meanings of the columns.
-
-4.2.29.5 Refclocks log file format
-..................................
-
-An example line (which actually appears as a single line in the file)
-from the refclocks log file is shown below.
-
- 2009-11-30 14:33:27.000000 PPS2 7 N 1 4.900000e-07 -6.741777e-07 1.000e-06
-
- The columns are as follows (the quantities in square brackets are the
-values from the example line above) :
-
- 1. Date [2009-11-30]
- 2. Hour:Minute:Second.Microsecond [14:33:27.000000]. Note that the
- date/time pair is expressed in UTC, not the local time zone.
- 3. Reference ID of refclock from which measurement comes. [PPS2]
- 4. Sequence number of driver poll within one polling interval for raw
- samples, or '-' for filtered samples. [7]
- 5. Leap status ('N' means normal, '+' means that the last minute of
- the current month has 61 seconds, '-' means that the last minute of
- the month has 59 seconds). [N]
- 6. Flag indicating whether the sample comes from PPS source. (1 for
- yes, 0 for no, or '-' for filtered sample). [1]
- 7. Local clock error measured by refclock driver, or '-' for filtered
- sample. [4.900000e-07]
- 8. Local clock error with applied corrections. Positive indicates
- that the local clock is slow. [-6.741777e-07]
- 9. Assumed dispersion of the sample. [1.000e-06]
-
- A banner is periodically written to the log file to indicate the
-meanings of the columns.
-
-4.2.29.6 Tempcomp log file format
-.................................
-
-An example line (which actually appears as a single line in the file)
-from the tempcomp log file is shown below.
-
- 2010-04-19 10:39:48 2.8000e+04 3.6600e-01
-
- The columns are as follows (the quantities in square brackets are the
-values from the example line above) :
-
- 1. Date [2010-04-19]
- 2. Hour:Minute:Second [10:39:48]. Note that the date/time pair is
- expressed in UTC, not the local time zone.
- 3. Temperature read from tempcomp file. [2.8000e+04]
- 4. Applied compensation in ppm, positive means the system clock is
- running faster than it would be without the compensation.
- [3.6600e-01]
-
- A banner is periodically written to the log file to indicate the
-meanings of the columns.
-
-4.2.30 logbanner
-----------------
-
-A banner is periodically written to the log files enabled by the 'log'
-directive to indicate the meanings of the columns.
-
- The 'logbanner' directive specifies after how many entries in the log
-file should be the banner written. The default is 32, and 0 can be used
-to disable it entirely.
-
-4.2.31 logchange
-----------------
-
-This directive forces 'chronyd' to send a message to syslog if it makes
-a system clock adjustment larger than a threshold value. An example of
-use is
-
- logchange 0.5
-
- which would cause a syslog message to be generated a system clock
-error of over 0.5 seconds starts to be compensated.
-
- Clock errors detected either via NTP packets or via timestamps
-entered via the 'settime' command of 'chronyc' are logged.
-
- This directive assumes that syslog messages are appearing where
-somebody can see them. This allows that person to see if a large error
-has arisen, e.g. because of a fault, or because of faulty timezone
-handling, for example when summer time (daylight saving) starts or ends.
-
-4.2.32 logdir
--------------
-
-This directive allows the directory where log files are written to be
-specified.
-
- An example of the use of this directive is
-
- logdir /var/log/chrony
-
-4.2.33 mailonchange
--------------------
-
-This directive defines an email address to which mail should be sent if
-chronyd applies a correction exceeding a particular threshold to the
-system clock.
-
- An example of use of this directive is
-
- mailonchange root@localhost 0.5
-
- This would send a mail message to root if a change of more than 0.5
-seconds were applied to the system clock.
-
-4.2.34 makestep
----------------
-
-Normally chronyd will cause the system to gradually correct any time
-offset, by slowing down or speeding up the clock as required. In
-certain situations, the system clock may be so far adrift that this
-slewing process would take a very long time to correct the system clock.
-
- This directive forces 'chronyd' to step system clock if the
-adjustment is larger than a threshold value, but only if there were no
-more clock updates since 'chronyd' was started than a specified limit (a
-negative value can be used to disable the limit).
-
- This is particularly useful when using reference clocks, because the
-'initstepslew' directive (*note initstepslew directive::) works only
-with NTP sources.
-
- An example of the use of this directive is
-
- makestep 1000 10
-
- This would step system clock if the adjustment is larger than 1000
-seconds, but only in the first ten clock updates.
-
-4.2.35 manual
--------------
-
-The 'manual' directive enables support at run-time for the 'settime'
-command in chronyc (*note settime command::). If no 'manual' directive
-is included, any attempt to use the 'settime' command in chronyc will be
-met with an error message.
-
- Note that the 'settime' command can be enabled at run-time using the
-'manual' command in chronyc (*note manual command::). (The idea of the
-two commands is that the 'manual' command controls the manual clock
-driver's behaviour, whereas the 'settime' command allows samples of
-manually entered time to be provided).
-
-4.2.36 maxchange
-----------------
-
-This directive sets the maximum allowed offset corrected on a clock
-update. The check is performed only after the specified number of
-updates to allow a large initial adjustment of the system clock. When
-an offset larger than the specified maximum occurs, it will be ignored
-for the specified number of times and then 'chronyd' will give up and
-exit (a negative value can be used to never exit). In both cases a
-message is sent to syslog.
-
- An example of the use of this directive is
-
- maxchange 1000 1 2
-
- After the first clock update, 'chronyd' will check the offset on
-every clock update, it will ignore two adjustments larger than 1000
-seconds and exit on another one.
-
-4.2.37 maxclockerror
---------------------
-
-The 'maxclockerror' directive sets the maximum assumed frequency error
-of the local clock. This is a frequency stability of the clock, not an
-absolute frequency error.
-
- By default, the maximum assumed error is set to 1 ppm.
-
- The syntax is
-
- maxclockerror <error-in-ppm>
-
- Typical values for <error-in-ppm> might be 10 for a low quality clock
-to 0.1 for a high quality clock using a temperature compensated crystal
-oscillator.
-
-4.2.38 maxsamples
------------------
-
-The 'maxsamples' directive sets the default maximum number of samples
-'chronyd' should keep for each source. This setting can be overriden
-for individual sources in the 'server' and 'refclock' directives (*note
-server directive::, *note refclock directive::). The default value is
-0, which disables the configurable limit. The useful range is 4 to 64.
-
- The syntax is
-
- maxsamples <samples>
-
-4.2.39 maxslewrate
-------------------
-
-The 'maxslewrate' directive sets the maximum rate at which 'chronyd' is
-allowed to slew the time. It limits the slew rate controlled by the
-correction time ratio (*note corrtimeratio directive::) and is effective
-only on systems where 'chronyd' is able to control the rate (so far only
-Linux).
-
- By default, the maximum slew rate is 83333.333 ppm (one twelfth).
-
- The syntax is
-
- maxslewrate <rate-in-ppm>
-
-4.2.40 maxupdateskew
---------------------
-
-One of 'chronyd's' tasks is to work out how fast or slow the computer's
-clock runs relative to its reference sources. In addition, it computes
-an estimate of the error bounds around the estimated value.
-
- If the range of error is too large, it probably indicates that the
-measurements have not settled down yet, and that the estimated gain or
-loss rate is not very reliable.
-
- The 'maxupdateskew' parameter allows the threshold for determining
-whether an estimate may be so unreliable that it should not be used. By
-default, the threshold is 1000 ppm.
-
- The syntax is
-
- maxupdateskew <skew-in-ppm>
-
- Typical values for <skew-in-ppm> might be 100 for a dial-up
-connection to servers over a phone line, and 5 or 10 for a computer on a
-LAN.
-
- It should be noted that this is not the only means of protection
-against using unreliable estimates. At all times, 'chronyd' keeps track
-of both the estimated gain or loss rate, and the error bound on the
-estimate. When a new estimate is generated following another
-measurement from one of the sources, a weighted combination algorithm is
-used to update the master estimate. So if 'chronyd' has an existing
-highly-reliable master estimate and a new estimate is generated which
-has large error bounds, the existing master estimate will dominate in
-the new master estimate.
-
-4.2.41 minsamples
------------------
-
-The 'minsamples' directive sets the default minimum number of samples
-'chronyd' should keep for each source. This setting can be overriden
-for individual sources in the 'server' and 'refclock' directives (*note
-server directive::, *note refclock directive::). The default value is
-0. The useful range is 4 to 64.
-
- The syntax is
-
- minsamples <samples>
-
-4.2.42 minsources
------------------
-
-The 'minsources' directive sets the minimum number of sources that need
-to be considered as selectable in the source selection algorithm before
-the local clock is updated. The default value is 1.
-
- Setting this option to a larger number can be used to improve the
-reliability. More sources will have to agree with each other and the
-clock will not be updated when only one source (which could be serving
-wrong time) is reachable.
-
- The syntax is
-
- minsources <sources>
-
-4.2.43 noclientlog
-------------------
-
-This directive, which takes no arguments, specifies that client accesses
-are not to be logged. Normally they are logged, allowing statistics to
-be reported using the 'clients' command in 'chronyc'.
-
-4.2.44 peer
------------
-
-The syntax of this directive is identical to that for the 'server'
-directive (*note server directive::), except that it is used to specify
-an NTP peer rather than an NTP server.
-
- Please note that NTP peers that are not configured with a key to
-enable authentication are vulnerable to a denial-of-service attack. An
-attacker knowing that NTP hosts A and B are peering with each other can
-send a packet with random timestamps to host A with source address of B
-which will set the NTP state variables on A to the values sent by the
-attacker. Host A will then send on its next poll to B a packet with
-originate timestamp that doesn't match the transmit timestamp of B and
-the packet will be dropped. If the attacker does this periodically for
-both hosts, they won't be able to synchronize to each other.
-
- This attack can be prevented by enabling authentication with the key
-option, or using the 'server' directive on both sides to specify the
-other host as a server instead of peer, the only drawback is that it
-will double the network traffic between the two hosts.
-
-4.2.45 pidfile
---------------
-
-chronyd always writes its process ID (pid) to a file, and checks this
-file on startup to see if another chronyd may already be running on the
-system. By default, the file used is '/var/run/chronyd.pid'. The
-'pidfile' directive allows the name to be changed, e.g.
-
- pidfile /var/tmp/chronyd.pid
-
-4.2.46 pool
------------
-
-The syntax of this directive is similar to that for the 'server'
-directive (*note server directive::), except that it is used to specify
-a pool of NTP servers rather than a single NTP server. The pool name is
-expected to resolve to multiple addresses which may change over time.
-
- All options valid in the 'server' directive can be used in this
-directive too. There is one option specific to 'pool' directive:
-'maxsources' sets the maximum number of sources that can be used from
-the pool, the default value is 4.
-
- On start, when the pool name is resolved, 'chronyd' will add up to 16
-sources, one for each resolved address. When the number of sources from
-which at least one valid reply was received reaches 'maxsources', the
-other sources will be removed. When a pool source is unreachable or
-marked as falseticker, 'chronyd' will try to replace the source with a
-newly resolved address of the pool.
-
- An example of the pool directive is
-
- pool pool.ntp.org iburst maxsources 3
-
-4.2.47 port
------------
-
-This option allows you to configure the port on which 'chronyd' will
-listen for NTP requests. The port will be open only when an address is
-allowed by the 'allow' directive or command, an NTP peer is configured,
-or the broadcast server mode is enabled.
-
- The compiled in default is udp/123, the standard NTP port. If set to
-0, 'chronyd' will never open the server port and will operate strictly
-in a client-only mode. The source port used in NTP client requests can
-be set by the 'acquisitionport' directive.
-
- An example of the port command is
-
- port 11123
-
- This would change the NTP port served by 'chronyd' on the computer to
-udp/11123.
-
-4.2.48 refclock
----------------
-
-Reference clocks allows very accurate synchronisation and 'chronyd' can
-function as a stratum 1 server. They are specified by the 'refclock'
-directive. It has two mandatory parameters, a refclock driver name and
-a driver specific parameter.
-
- There are currently four drivers included:
-
-'PPS'
- PPSAPI (pulse per second) driver. The parameter is the path to a
- PPS device. Assert events are used by default. Driver option
- ':clear' can be appended to the path if clear events should be used
- instead.
-
- As PPS refclock gets only sub-second time information, it needs
- another source (NTP or non-PPS refclock) or local directive (*note
- local directive::) enabled to work. For example:
-
- refclock PPS /dev/pps0 lock NMEA
- refclock SHM 0 offset 0.5 delay 0.2 refid NMEA noselect
-
-'SHM'
- NTP shared memory driver. This driver uses a shared memory segment
- to receive data from another daemon which communicates with an
- actual reference clock. The parameter is the number of a shared
- memory segment, usually 0, 1, 2 or 3. For example:
-
- refclock SHM 1 poll 3 refid GPS1
-
- A driver option in form ':perm=NNN' can be appended to the segment
- number to create the segment with permissions other than the
- default '0600'.
-
- Some examples of applications that can be used as SHM sources are
- 'gpsd' (http://catb.org/gpsd/), 'shmpps' and 'radioclk'
- (http://www.buzzard.me.uk/jonathan/radioclock.html).
-'SOCK'
- Unix domain socket driver. It is similar to the SHM driver, but
- uses a different format and uses a socket instead of shared memory.
- It does not require polling and it supports transmitting of PPS
- data. The parameter is a path to the socket which will be created
- by 'chronyd' and used to receive the messages. The format of
- messages sent over the socket is described in the 'refclock_sock.c'
- file.
-
- Recent versions of the 'gpsd' daemon include support for the SOCK
- protocol. The path where the socket should be created is described
- in the 'gpsd(8)' man page. For example:
-
- refclock SOCK /var/run/chrony.ttyS0.sock
-
-'PHC'
- PTP hardware clock (PHC) driver. The parameter is the path to the
- device of the PTP clock, which can be synchronised by a PTP daemon
- (e.g. 'ptp4l' from the Linux PTP project
- (http://linuxptp.sourceforge.net/). The PTP clocks are typically
- kept in TAI instead of UTC. The 'offset' option can be used to
- compensate for the current UTC/TAI offset. For example:
-
- refclock PHC /dev/ptp0 poll 3 dpoll -2 offset -35
-
- The 'refclock' command also supports a number of subfields (which may
-be defined in any order):
-
-'poll'
- Timestamps produced by refclock drivers are not used immediately,
- but they are stored and processed by a median filter in the polling
- interval specified by this option. This is defined as a power of 2
- and may be negative to specify a sub-second interval. The default
- is 4 (16 seconds). A shorter interval allows 'chronyd' to react
- faster to changes in clock frequency, but it may decrease the
- accuracy if the source is too noisy.
-'dpoll'
- Some drivers don't listen for external events and try to produce
- samples in their own polling interval. This is defined as a power
- of 2 and may be negative to specify a sub-second interval. The
- default is 0 (1 second).
-'refid'
- This option is used to specify a reference id of the refclock, as
- up to four ASCII characters. By default, first three characters
- from driver name and the number of the refclock are used as refid.
- Each refclock must have an unique refid.
-'filter'
- This option sets the length of the median filter which is used to
- reduce noise. With each poll about 40 percent of the stored
- samples is discarded and one final sample is calculated as average
- of the remaining samples. If the length is 4 or above, at least 4
- samples have to be collected between polls. For lengths below 4,
- the filter has to be full. The default is 64.
-'rate'
- PPS signal frequency (in Hz). This option only controls how the
- received pulses are aligned. To actually receive more than one
- pulse per second, a negative 'dpoll' has to be specified (-3 for
- 5Hz signal). The default is 1.
-'lock'
- This option can be used to lock a PPS refclock to another refclock
- whose reference id is specified by this option. In this mode
- received pulses are aligned directly to unfiltered samples from the
- refclock. By default, pulses are aligned to local clock, but only
- when it is well synchronised.
-'offset'
- This option can be used to compensate a constant error. The
- specified offset (in seconds) is applied to all samples produced by
- the refclock. The default is 0.0.
-'delay'
- This option sets the NTP delay of the source (in seconds). Half of
- this value is included in the maximum assumed error which is used
- in the source selection algorithm. Increasing the delay is useful
- to avoid having no majority in the algorithm or to make it prefer
- other sources. The default is 1e-9 (1 nanosecond).
-'precision'
- Refclock precision (in seconds). The default is 1e-6 (1
- microsecond) for SHM refclock, and 1e-9 (1 nanosecond) for SOCK,
- PPS and PHC refclocks.
-'maxdispersion'
- Maximum allowed dispersion for filtered samples (in seconds).
- Samples with larger estimated dispersion are ignored. By default,
- this limit is disabled.
-'prefer'
- Prefer this source over sources without prefer option.
-'noselect'
- Never select this source. This is useful for monitoring or with
- sources which are not very accurate, but are locked with a PPS
- refclock.
-'minsamples'
- Set the minimum number of samples kept for this source. This
- overrides the 'minsamples' directive (*note minsamples
- directive::).
-'maxsamples'
- Set the maximum number of samples kept for this source. This
- overrides the 'maxsamples' directive (*note maxsamples
- directive::).
-
-4.2.49 reselectdist
--------------------
-
-When 'chronyd' selects synchronisation source from available sources, it
-will prefer the one with minimum synchronisation distance. However, to
-avoid frequent reselecting when there are sources with similar distance,
-a fixed distance is added to the distance for sources that are currently
-not selected. This can be set with the 'reselectdist' option. By
-default, the distance is 100 microseconds.
-
- The syntax is
-
- reselectdist <dist-in-seconds>
-
-4.2.50 rtcautotrim
-------------------
-
-The 'rtcautotrim' directive is used to keep the real time clock (RTC)
-close to the system clock automatically. When the system clock is
-synchronized and the estimated error between the two clocks is larger
-than the specified threshold, 'chronyd' will trim the RTC as if the
-'trimrtc' (*note trimrtc command::) command was issued.
-
- This directive is effective only with the 'rtcfile' directive.
-
- An example of the use of this directive is
-
- rtcautotrim 30
-
- This would set the threshold error to 30 seconds.
-
-4.2.51 rtcdevice
-----------------
-
-The 'rtcdevice' directive defines the name of the device file for
-accessing the real time clock. By default this is '/dev/rtc', unless
-the directive is used to set a different value. This applies to Linux
-systems with devfs. An example of use is
-
- rtcdevice /dev/misc/rtc
-
-4.2.52 rtcfile
---------------
-
-The 'rtcfile' directive defines the name of the file in which 'chronyd'
-can save parameters associated with tracking the accuracy of the
-system's real-time clock (RTC).
-
- The syntax is illustrated in the following example
-
- rtcfile /var/lib/chrony/rtc
-
- 'chronyd' saves information in this file when it exits and when the
-'writertc' command is issued in 'chronyc'. The information saved is the
-RTC's error at some epoch, that epoch (in seconds since January 1 1970),
-and the rate at which the RTC gains or loses time.
-
- So far, the support for real-time clocks is limited - their code is
-even more system-specific than the rest of the software. You can only
-use the real time clock facilities (the 'rtcfile' directive and the '-s'
-command line option to 'chronyd') if the following three conditions
-apply:
-
- 1. You are running Linux version 2.2.x or later.
-
- 2. You have compiled the kernel with extended real-time clock support
- (i.e. the '/dev/rtc' device is capable of doing useful things).
-
- 3. You don't have other applications that need to make use of
- '/dev/rtc' at all.
-
-4.2.53 rtconutc
----------------
-
-'chronyd' assumes by default that the real time clock (RTC) keeps local
-time (including any daylight saving changes). This is convenient on PCs
-running Linux which are dual-booted with DOS or Windows.
-
- NOTE : IF YOU KEEP THE REAL TIME CLOCK ON LOCAL TIME AND YOUR
-COMPUTER IS OFF WHEN DAYLIGHT SAVING (SUMMER TIME) STARTS OR ENDS, THE
-COMPUTER'S SYSTEM TIME WILL BE ONE HOUR IN ERROR WHEN YOU NEXT BOOT AND
-START CHRONYD.
-
- An alternative is for the RTC to keep Universal Coordinated Time
-(UTC). This does not suffer from the 1 hour problem when daylight saving
-starts or ends.
-
- If the 'rtconutc' directive appears, it means the RTC is required to
-keep UTC. The directive takes no arguments. It is equivalent to
-specifying the '-u' switch to the Linux '/sbin/hwclock' program.
-
- Note that this setting is overriden when the 'hwclockfile' directive
-(*note hwclockfile directive::) is used.
-
-4.2.54 rtcsync
---------------
-
-The 'rtcsync' directive will enable a kernel mode where the system time
-is copied to the real time clock (RTC) every 11 minutes.
-
- This directive is supported only on Linux and cannot be used when the
-normal RTC tracking is enabled, i.e. when the 'rtcfile' directive is
-used.
-
-4.2.55 sched_priority
----------------------
-
-The 'sched_priority' directive will select the SCHED_FIFO real-time
-scheduler at the specified priority (which must be between 0 and 100).
-This mode is supported only on Linux.
-
- This directive uses the Linux sched_setscheduler() system call to
-instruct the kernel to use the SCHED_FIFO first-in, first-out real-time
-scheduling policy for 'chronyd' with the specified priority. This means
-that whenever 'chronyd' is ready to run it will run, interrupting
-whatever else is running unless it is a higher priority real-time
-process. This should not impact performance as 'chronyd's' resource
-requirements are modest, but it should result in lower and more
-consistent latency since 'chronyd' will not need to wait for the
-scheduler to get around to running it. You should not use this unless
-you really need it. The sched_setscheduler man page has more details.
-
-4.2.56 server
--------------
-
-The 'server' directive allows NTP servers to be specified. The
-client/server relationship is strictly hierarchical : a client may
-synchronise its system time to that of the server, but the server's
-system time will never be influenced by that of a client.
-
- The 'server' directive is immediately followed by either the name of
-the server, or its IP address. The server command also supports a
-number of subfields (which may be defined in any order):
-
-'port'
- This option allows the UDP port on which the server understands NTP
- requests to be specified. For normal servers this option should
- not be required (the default is 123, the standard NTP port).
-'minpoll'
- Although 'chronyd' will trim the rate at which it samples the
- server during normal operation, the user may wish to constrain the
- minimum polling interval. This is always defined as a power of 2,
- so 'minpoll 5' would mean that the polling interval cannot drop
- below 32 seconds. The default is 6 (64 seconds).
-'maxpoll'
- In a similar way, the user may wish to constrain the maximum
- polling interval. Again this is specified as a power of 2,
- 'maxpoll 9' indicates that the polling interval must stay at or
- below 512 seconds. The default is 10 (1024 seconds).
-'maxdelay'
- 'chronyd' uses the network round-trip delay to the server to
- determine how accurate a particular measurement is likely to be.
- Long round-trip delays indicate that the request, or the response,
- or both were delayed. If only one of the messages was delayed the
- measurement error is likely to be substantial.
-
- For small variations in round trip delay, 'chronyd' uses a
- weighting scheme when processing the measurements. However, beyond
- a certain level of delay the measurements are likely to be so
- corrupted as to be useless. (This is particularly so on dial-up or
- other slow links, where a long delay probably indicates a highly
- asymmetric delay caused by the response waiting behind a lot of
- packets related to a download of some sort).
-
- If the user knows that round trip delays above a certain level
- should cause the measurement to be ignored, this level can be
- defined with the maxdelay command. For example, 'maxdelay 0.3'
- would indicate that measurements with a round-trip delay of 0.3
- seconds or more should be ignored. The default value is 3 seconds.
-
-'maxdelayratio'
- This option is similar to the maxdelay option above. 'chronyd'
- keeps a record of the minimum round-trip delay amongst the previous
- measurements that it has buffered. If a measurement has a round
- trip delay that is greater than the maxdelayratio times the minimum
- delay, it will be rejected.
-
-'maxdelaydevratio'
- If a measurement has ratio of the increase in round-trip delay from
- the minimum delay amongst the previous measurements to the standard
- deviation of the previous measurements that is greater than
- maxdelaydevratio, it will be rejected. The default is 10.0.
-
-'presend'
- If the timing measurements being made by 'chronyd' are the only
- network data passing between two computers, you may find that some
- measurements are badly skewed due to either the client or the
- server having to do an ARP lookup on the other party prior to
- transmitting a packet. This is more of a problem with long
- sampling intervals, which may be similar in duration to the
- lifetime of entries in the ARP caches of the machines.
-
- In order to avoid this problem, the 'presend' option may be used.
- It takes a single integer argument, which is the smallest polling
- interval for which an extra pair of NTP packets will be exchanged
- between the client and the server prior to the actual measurement.
- For example, with the following option included in a 'server'
- directive :
-
- presend 9
-
- when the polling interval is 512 seconds or more, an extra NTP
- client packet will be sent to the server a short time (currently 4
- seconds) before making the actual measurement.
-
-'key'
- The NTP protocol supports the inclusion of checksums in the
- packets, to prevent computers having their system time upset by
- rogue packets being sent to them. The checksums are generated as a
- function of a password, using the cryptographic hash function set
- in the key file.
-
- The association between key numbers and passwords is contained in
- the keys file, defined by the keyfile command.
-
- If the key option is present, 'chronyd' will attempt to use
- authenticated packets when communicating with this server. The key
- number used will be the single argument to the key option (an
- unsigned integer in the range 1 through 2**32-1). The server must
- have the same password for this key number configured, otherwise no
- relationship between the computers will be possible.
-
-'offline'
- If the server will not be reachable when 'chronyd' is started, the
- offline option may be specified. 'chronyd' will not try to poll
- the server until it is enabled to do so (by using the online option
- of 'chronyc').
-
-'auto_offline'
- If this option is set, the server will be assumed to have gone
- offline when 2 requests have been sent to it without receiving a
- response. This option avoids the need to run the 'offline' (*note
- offline command::) command from chrony when disconnecting the
- dial-up link. (It will still be necessary to use chronyc's
- 'online' (*note online command::) command when the link has been
- established, to enable measurements to start.)
-
-'iburst'
- On start, make four measurements over a short duration (rather than
- the usual periodic measurements).
-
-'minstratum'
- When the synchronisation source is selected from available sources,
- sources with lower stratum are normally preferred. This option can
- be used to increase stratum of the source to the specified minimum,
- so 'chronyd' will avoid selecting that source. This is useful with
- low stratum sources that are known to be unrealiable or inaccurate
- and which should be used only when other sources are unreachable.
-
-'polltarget'
- Target number of measurements to use for the regression algorithm
- which 'chronyd' will try to maintain by adjusting polling interval
- between 'minpoll' and 'maxpoll'. A higher target makes 'chronyd'
- prefer shorter polling intervals. The default is 6 and a useful
- range is 6 to 60.
-
-'version'
- This option sets the NTP version number used in packets sent to the
- server. This can be useful when the server runs an old NTP
- implementation that doesn't respond to newer versions. The default
- version number is 4.
-
-'prefer'
- Prefer this source over sources without prefer option.
-
-'noselect'
- Never select this source. This is particularly useful for
- monitoring.
-
-'minsamples'
- Set the minimum number of samples kept for this source. This
- overrides the 'minsamples' directive (*note minsamples
- directive::).
-
-'maxsamples'
- Set the maximum number of samples kept for this source. This
- overrides the 'maxsamples' directive (*note maxsamples
- directive::).
-
-4.2.57 smoothtime
------------------
-
-The 'smoothtime' directive can be used to enable smoothing of the time
-that 'chronyd' serves to its clients to make it easier for them to track
-it and keep their clocks close together even when large offset or
-frequency corrections are applied to the server's clock, for example
-after being offline for a longer time.
-
- BE WARNED - the server is intentionally not serving its best estimate
-of the true time. If a large offset has been accumulated, it may take a
-very long time to smooth it out. This directive should be used only
-when the clients are not configured to poll also another NTP server,
-because they could reject this server as a falseticker or fail to select
-a source completely.
-
- The smoothing process is implemented with a quadratic spline function
-with two or three pieces. It's independent from any slewing applied to
-the local system clock, but the accumulated offset and frequency will be
-reset when the clock is corrected by stepping, e.g. by the 'makestep'
-directive or command. The process can be reset without stepping the
-clock by the 'smoothtime reset' command (*note smoothtime command::).
-
- The first two arguments of the directive are the maximum frequency
-offset of the smoothed time to the tracked NTP time (in ppm) and the
-maximum rate at which the frequency offset is allowed to change (in ppm
-per second). 'leaponly' is an optional third argument which enables a
-mode where only leap seconds are smoothed out and normal
-offset/frequency changes are ignored. The 'leaponly' option is useful
-in a combination with the 'leapsecmode slew' option (*note leapsecmode
-directive::) to allow clients use multiple time smoothing servers
-safely.
-
- The smoothing process is activated automatically when 1/10000 of the
-estimated skew of the local clock falls below the maximum rate of
-frequency change. It can be also activated manually by the 'smoothtime
-activate' command, which is particularly useful when the clock is
-synchronized only with manual input and the skew is always larger than
-the threshold. The 'smoothing' command (*note smoothing command::) can
-be used to monitor the process.
-
- An example suitable for clients using 'ntpd' and 1024 second polling
-interval could be
-
- smoothtime 400 0.001
-
- An example suitable for clients using 'chronyd' on Linux could be
-
- smoothtime 50000 0.01
-
-4.2.58 stratumweight
---------------------
-
-The 'stratumweight' directive sets how much distance should be added per
-stratum to the synchronisation distance when 'chronyd' selects the
-synchronisation source from available sources.
-
- The syntax is
-
- stratumweight <dist-in-seconds>
-
- By default, the weight is 0.001 seconds. This means that stratum of
-the sources in the selection process matters only when the differences
-between the distances are in milliseconds.
-
-4.2.59 tempcomp
----------------
-
-Normally, changes in the rate of drift of the system clock are caused
-mainly by changes in the temperature of the crystal oscillator on the
-mainboard.
-
- If there are temperature measurements available from a sensor close
-to the oscillator, the 'tempcomp' directive can be used to compensate
-for the changes in the temperature and improve the stability and
-accuracy of the clock.
-
- The result depends on many factors, including the resolution of the
-sensor, the amount of noise in the measurements, the polling interval of
-the time source, the compensation update interval, how well is the
-compensation specified, and how close is the sensor to the oscillator.
-When it's working well, the frequency reported in the 'tracking.log'
-file is more stable and the maximum reached offset is smaller.
-
- There are two forms of the directive. The first one has six
-parameters: a path to the file containing the current temperature from
-the sensor (in text format), the compensation update interval (in
-seconds), and temperature coefficients T0, k0, k1, k2.
-
- The frequency compensation is calculated (in ppm) as
-
- 'k0 + (T - T0) * k1 + (T - T0)^2 * k2'
-
- The result has to be between -10 ppm and 10 ppm, otherwise the
-measurement is considered invalid and will be ignored. The k0
-coefficient can be used to get the results in that range.
-
- An example of use is
-
- tempcomp /sys/class/hwmon/hwmon0/temp2_input 30 26000 0.0 0.000183 0.0
-
- The measured temperature will be read from the file in the Linux
-sysfs filesystem every 30 seconds. When the temperature is 26000 (26
-degrees Celsius), the frequency correction will be zero. When it is
-27000 (27 degrees Celsius), the clock will be set to run 0.183ppm
-faster, etc.
-
- The second form has three parameters, the path to the sensor file,
-the update interval and a path to a file containing a list of
-(temperature, compensation) points, from which the compensation is
-linearly interpolated or extrapolated.
-
- An example is
-
- tempcomp /sys/class/hwmon/hwmon0/temp2_input 30 /etc/chrony.tempcomp
-
- where the 'chrony.tempcomp' file could have
-
- 20000 1.0
- 21000 0.64
- 22000 0.36
- 23000 0.16
- 24000 0.04
- 25000 0.0
- 26000 0.04
- 27000 0.16
- 28000 0.36
- 29000 0.64
- 30000 1.0
-
- Valid measurements with corresponding compensations are logged to the
-'tempcomp.log' file if enabled by the 'log tempcomp' directive.
-
-4.2.60 user
------------
-
-The 'user' directive sets the name of the user to which will 'chronyd'
-switch on initialisation to drop root privileges. So far, it works only
-on Linux when compiled with capabilities support. Setting the name to
-root will disable it.
-
- The default value is 'root'.
-
-4.3 Running chronyc
-===================
-
-Chronyc is the program that can be used to reconfigure options within
-the 'chronyd' program whilst it is running. Chronyc can also be used to
-generate status reports about the operation of 'chronyd'.
-
-4.3.1 Basic use
----------------
-
-The program chronyc is run by entering
-
- chronyc
-
- at the command line. The prompt 'chronyc' is displayed whilst
-chronyc is expecting input from the user, when it is being run from a
-terminal. If chronyc's input or output are redirected from/to a file,
-the prompt is now shown.
-
- When you are finished entering commands, the commands 'exit' or
-'quit' will terminate the program. (Entering <Control-D> will also
-terminate the program.)
-
-4.3.2 Command line options
---------------------------
-
-Chronyc supports the following command line options.
-
-'-v'
- Displays the version number of chronyc on the terminal, and exists.
-'-h <host>'
- This option allows the user to specify which host running the
- 'chronyd' program is to be contacted. This allows for remote
- configuration, without having to ssh to the other host first.
-
- The default is to contact 'chronyd' running on the same host as
- that where chronyc is being run.
-'-p <port>'
- This option allows the user to specify the UDP port number which
- the target 'chronyd' is using for its command & monitoring
- connections. This defaults to the compiled-in default; there would
- rarely be a need to change this.
-'-n'
- This option disables resolving IP addresses to hostnames.
-'-4'
- With this option hostnames will be resolved only to IPv4 addresses.
-'-6'
- With this option hostnames will be resolved only to IPv6 addresses.
-'-m'
- With this option multiple commands can be specified on the command
- line. Each argument will be interpreted as a whole command.
-'-f <conf-file>'
- This option can be used to specify an alternate location of the
- 'chronyd' configuration file (default '/etc/chrony.conf'). The
- configuration file is needed for the '-a' option.
-'-a'
- With this option 'chronyc' will try to authenticate automatically
- on start. It will read the configuration file, read the command
- key from the keyfile and run the authhash and password commands.
-
-4.3.3 Security with chronyc
----------------------------
-
-Many of the commands available through chronyc have a fair amount of
-power to reconfigure the run-time behaviour of 'chronyd'. Consequently,
-'chronyc' is quite dangerous for the integrity of the target system's
-clock performance. Having access to 'chronyd' via chronyc is more or
-less equivalent to being able to modify 'chronyd's' configuration file
-(typically '/etc/chrony.conf') and to restart 'chronyd'.
-
- Chronyc also provides a number of monitoring (as opposed to
-commanding) commands, which will not affect the behaviour of 'chronyd'.
-However, you may still want to restrict access to these commands.
-
- In view of this, access to some of the capabilities of chronyc will
-usually be tightly controlled. There are two mechanisms supported:
-
- 1. The set of hosts from which 'chronyd' will accept commands can be
- restricted. By default, commands will only be accepted from the
- same host that 'chronyd' is running on.
- 2. Any command that actually reconfigures some aspect of 'chronyd's'
- behaviour requires the user of chronyc to know a password. This
- password is specified in 'chronyd's' keys file (*note keyfile
- directive::) and specified via the commandkey option in its
- configuration file (*note commandkey directive::).
-
- Only the following commands can be used _without_ providing a
-password:
-
- * 'activity'
- * 'authhash'
- * 'dns'
- * 'exit'
- * 'help'
- * 'password'
- * 'quit'
- * 'rtcdata'
- * 'smoothing'
- * 'sources'
- * 'sourcestats'
- * 'tracking'
- * 'waitsync'
-
- All other commands require a password to have been specified
-previously, because they affect 'chronyd's' operation.
-
-4.3.4 Command reference
------------------------
-
-This section describes each of the commands available within the chronyc
-program. Chronyc offers the user a simple command-line driven
-interface.
-
-4.3.4.1 accheck
-...............
-
-This command allows you to check whether client NTP access is allowed
-from a particular host.
-
- Examples of use, showing a named host and a numeric IP address, are
-as follows:
-
- accheck foo.example.net
- accheck 1.2.3.4
- accheck 2001:db8::1
-
- This command can be used to examine the effect of a series of
-'allow', 'allow all', 'deny' and 'deny all' commands specified either
-via chronyc, or in 'chronyd's' configuration file.
-
-4.3.4.2 activity
-................
-
-This command reports the number of servers/peers that are online and
-offline. If the auto_offline option is used in specifying some of the
-servers/peers, the 'activity' command may be useful for detecting when
-all of them have entered the offline state after the PPP link has been
-disconnected.
-
- The report shows the number of servers/peers in 5 states:
- * 'online' : the server/peer is currently online (i.e. assumed by
- chronyd to be reachable)
- * 'offline' : the server/peer is currently offline (i.e. assumed by
- chronyd to be unreachable, and no measurements from it will be
- attempted.)
- * 'burst_online' : a burst command has been initiated for the
- server/peer and is being performed; after the burst is complete,
- the server/peer will be returned to the online state.
- * 'burst_offline' : a burst command has been initiated for the
- server/peer and is being performed; after the burst is complete,
- the server/peer will be returned to the offline state.
- * 'unresolved' : the name of the server/peer wasn't resolved to an
- address yet; this server is not visible in the 'sources' and
- 'sourcestats' reports.
-
-4.3.4.3 add peer
-................
-
-The 'add peer' command allows a new NTP peer to be added whilst
-'chronyd' is running.
-
- Following the words 'add peer', the syntax of the following
-parameters and options is similar to that for the 'peer' directive in
-the configuration file (*note peer directive::). The following peer
-options can be set in the command: 'port', 'minpoll', 'maxpoll',
-'presend', 'maxdelayratio', 'maxdelay', 'key'
-
- An example of using this command is shown below.
-
- add peer foo.example.net minpoll 6 maxpoll 10 key 25
-
-4.3.4.4 add server
-..................
-
-The 'add server' command allows a new NTP server to be added whilst
-'chronyd' is running.
-
- Following the words 'add server', the syntax of the following
-parameters and options is similar to that for the 'server' directive in
-the configuration file (*note server directive::). The following server
-options can be set in the command: 'port', 'minpoll', 'maxpoll',
-'presend', 'maxdelayratio', 'maxdelay', 'key'
-
- An example of using this command is shown below.
-
- add server foo.example.net minpoll 6 maxpoll 10 key 25
-
-4.3.4.5 allow all
-.................
-
-The effect of the allow command is identical to the 'allow all'
-directive in the configuration file (*note allow directive::).
-
-4.3.4.6 allow
-.............
-
-The effect of the allow command is identical to the 'allow' directive in
-the configuration file (*note allow directive::).
-
- The syntax is illustrated in the following examples:
-
- allow foo.example.net
- allow 1.2
- allow 3.4.5
- allow 6.7.8/22
- allow 6.7.8.9/22
- allow 2001:db8:789a::/48
- allow 0/0
- allow ::/0
- allow
-
- The effect of each of these examples is the same as that of the
-'allow' directive in the configuration file.
-
-4.3.4.7 authhash
-................
-
-This command selects the hash function used for authenticating user
-commands. For successful authentication the hash function has to be the
-same as the function specified for the command key in the keys file on
-the server (*note keyfile directive::). It needs to be selected before
-the 'password' command is used. The default hash function is MD5.
-
- An example is
-
- authhash SHA1
-
- The authhash command is run automatically on start if 'chronyc' was
-started with the '-a' option.
-
-4.3.4.8 burst
-.............
-
-The 'burst' command tells 'chronyd' to make a set of measurements to
-each of its NTP sources over a short duration (rather than the usual
-periodic measurements that it makes). After such a burst, 'chronyd'
-will revert to the previous state for each source. This might be either
-online, if the source was being periodically measured in the normal way,
-or offline, if the source had been indicated as being offline.
-(Switching a source between the online and offline states is described
-in *note online command::, *note offline command::).
-
- The syntax of the burst command is as follows
-
- burst <n-good-measurements>/<max-measurements> [<mask>/<masked-address>]
- burst <n-good-measurements>/<max-measurements> [<masked-address>/<masked-bits>]
- burst <n-good-measurements>/<max-measurements> [<address>]
-
- The mask and masked-address arguments are optional, in which case
-'chronyd' will initiate a burst for all of its currently defined
-sources.
-
- The arguments have the following meaning and format.
-
-'n-good-measurements'
- This defines the number of good measurements that 'chronyd' will
- want to obtain from each source. A measurement is good if it
- passes certain tests, for example, the round trip time to the
- source must be acceptable. (This allows 'chronyd' to reject
- measurements that are likely to be bogus.)
-
-'max-measurements'
- This defines the maximum number of measurements that 'chronyd' will
- attempt to make, even if the required number of good measurements
- has not been obtained.
-
-'mask'
- This is an IP address with which the IP address of each of
- 'chronyd''s sources is to be masked.
-
-'masked-address'
- This is an IP address. If the masked IP address of a source
- matches this value then the burst command is applied to that
- source.
-
-'masked-bits'
- This can be used with 'masked-address' for CIDR notation, which is
- a shorter alternative to the form with mask.
-
-'address'
- This is an IP address or a hostname. The burst command is applied
- only to that source.
-
- If no mask or masked address arguments are provided, every source
-will be matched.
-
- An example of the two-argument form of the command is
-
- burst 2/10
-
- This will cause 'chronyd' to attempt to get two good measurements
-from each source, stopping after two have been obtained, but in no event
-will it try more than ten probes to the source.
-
- Examples of the four-argument form of the command are
-
- burst 2/10 255.255.0.0/1.2.0.0
- burst 2/10 2001:db8:789a::/48
-
- In the first case, the two out of ten sampling will only be applied
-to sources whose IPv4 addresses are of the form '1.2.x.y', where x and y
-are arbitrary. In the second case, the sampling will be applied to
-sources whose IPv6 addresses have first 48 bits equal to
-'2001:db8:789a'.
-
- Example of the three-argument form of the command is
-
- burst 2/10 foo.example.net
-
-4.3.4.9 clients
-...............
-
-This command shows a list of all clients that have accessed the server,
-through either the NTP or command/monitoring ports. There are no
-arguments.
-
- An example of the output is
-
- Hostname Client Peer CmdAuth CmdNorm CmdBad LstN LstC
- ========================= ====== ====== ====== ====== ====== ==== ====
- localhost 0 0 15 1 0 29y 0
- aardvark.xxx 4 0 0 0 0 49 29y
- badger.xxx 4 0 0 0 0 6 29y
-
- Each row shows the data for a single host. Only hosts that have
-passed the host access checks (set with the 'allow', 'deny', 'cmdallow'
-and 'cmddeny' commands or configuration file directives) are logged.
-
- The columns are as follows:
-
- 1. The hostname of the client
- 2. The number of times the client has accessed the server using an NTP
- client mode packet.
- 3. The number of times the client has accessed the server using an NTP
- symmetric active mode packet.
- 4. The number of authenticated command packets that have been
- processed from the client (i.e. those following a successful
- 'password' command).
- 5. The number of unauthenticated command packets that have been
- processed from the client.
- 6. The number of bad command packets received from the client (not all
- forms of bad packet are logged).
- 7. Time since the last NTP packet was received
- 8. Time since the last command packet was received
-
- The last two entries will be shown as the time since 1970 if no
-packet of that type has ever been received.
-
-4.3.4.10 cmdaccheck
-...................
-
-This command is similar to the 'accheck' command, except that it is used
-to check whether command access is permitted from a named host.
-
- Examples of use are as follows:
-
- cmdaccheck foo.example.net
- cmdaccheck 1.2.3.4
- cmdaccheck 2001:db8::1
-
-4.3.4.11 cmdallow all
-.....................
-
-This is similar to the 'allow all' command, except that it is used
-toallow particular hosts or subnets to use the chronyc program to
-interactwith 'chronyd' on the current host.
-
-4.3.4.12 cmdallow
-.................
-
-This is similar to the 'allow' command, except that it is used to allow
-particular hosts or subnets to use the chronyc program to interact with
-'chronyd' on the current host.
-
-4.3.4.13 cmddeny all
-....................
-
-This is similar to the 'deny all' command, except that it is used to
-allow particular hosts or subnets to use the chronyc program to interact
-with 'chronyd' on the current host.
-
-4.3.4.14 cmddeny
-................
-
-This is similar to the 'deny' command, except that it is used to allow
-particular hosts or subnets to use the chronyc program to interact with
-'chronyd' on the current host.
-
-4.3.4.15 cyclelogs
-..................
-
-The 'cyclelogs' command causes all of 'chronyd's' open log files to be
-closed and re-opened. This allows them to be renamed so that they can
-be periodically purged. An example of how to do this is shown below.
-
- % mv /var/log/chrony/measurements.log /var/log/chrony/measurements1.log
- % chronyc -a cyclelogs
- % ls -l /var/log/chrony
- -rw-r--r-- 1 root root 0 Jun 8 18:17 measurements.log
- -rw-r--r-- 1 root root 12345 Jun 8 18:17 measurements1.log
- % rm -f measurements1.log
-
-4.3.4.16 delete
-...............
-
-The 'delete' command allows an NTP server or peer to be removed from the
-current set of sources.
-
- The syntax is illustrated in the examples below.
-
- delete foo.example.net
- delete 1.2.3.4
- delete 2001:db8::1
-
- There is one parameter, the name or IP address of the server or peer
-to be deleted.
-
-4.3.4.17 deny all
-.................
-
-The effect of the allow command is identical to the 'deny all' directive
-in the configuration file (*note deny directive::).
-
-4.3.4.18 deny
-.............
-
-The effect of the allow command is identical to the 'deny' directive in
-the configuration file (*note deny directive::).
-
- The syntax is illustrated in the following examples:
-
- deny foo.example.net
- deny 1.2
- deny 3.4.5
- deny 6.7.8/22
- deny 6.7.8.9/22
- deny 2001:db8:789a::/48
- deny 0/0
- deny ::/0
- deny
-
-4.3.4.19 dns
-............
-
-The 'dns' command configures how are hostnames and IP addresses resolved
-in 'chronyc'. IP addresses can be resolved to hostnames when printing
-results of 'sources', 'sourcestats', 'tracking' and 'clients' commands.
-Hostnames are resolved in commands that take an address as argument.
-
- There are five forms of the command:
-
-'dns -n'
- Disables resolving IP addresses to hostnames. Raw IP addresses
- will be displayed.
-'dns +n'
- Enables resolving IP addresses to hostnames. This is the default
- unless 'chronyc' was started with '-n' option.
-'dns -4'
- Resolves hostnames only to IPv4 addresses.
-'dns -6'
- Resolves hostnames only to IPv6 addresses.
-'dns -46'
- Resolves hostnames to both address families. This is the default
- unless 'chronyc' was started with '-4' or '-6' option.
-
-4.3.4.20 dump
-.............
-
-The 'dump' command causes 'chronyd' to write its current history of
-measurements for each of its sources to dump files, either for
-inspection or to support the '-r' option when 'chronyd' is restarted.
-
- The 'dump' command is somewhat equivalent to the 'dumponexit'
-directive in the chrony configuration file. *Note dumponexit
-directive::.
-
- To use the 'dump', you probably want to configure the name of the
-directory into which the dump files will be written. This can only be
-done in the configuration file, see *note dumpdir directive::.
-
-4.3.4.21 exit
-.............
-
-The exit command exits from chronyc and returns the user to the shell
-(same as the quit command).
-
-4.3.4.22 help
-.............
-
-The help command displays a summary of the commands and their arguments.
-
-4.3.4.23 local
-..............
-
-The 'local' command allows 'chronyd' to be told that it is to appear as
-a reference source, even if it is not itself properly synchronised to an
-external source. (This can be used on isolated networks, to allow one
-computer to be a master time server with the other computers slaving to
-it.) The 'local' command is somewhat equivalent to the 'local'
-directive in the configuration file, see *note local directive::.
-
- The syntax is as shown in the following examples.
-
- local stratum 10
- local off
-
- The first example enables the local reference mode on the host, and
-sets the stratum at which it should claim to be synchronised.
-
- The second example disables the local reference mode.
-
-4.3.4.24 makestep
-.................
-
-Normally chronyd will cause the system to gradually correct any time
-offset, by slowing down or speeding up the clock as required. In
-certain situations, the system clock may be so far adrift that this
-slewing process would take a very long time to correct the system clock.
-
- The 'makestep' command can be used in this situation. There are two
-forms of the command. The first form has no parameters. It tells
-'chronyd' to cancel any remaining correction that was being slewed and
-jump the system clock by the equivalent amount, making it correct
-immediately.
-
- The second form configures the automatic stepping, similarly to the
-'makestep' directive (*note makestep directive::). It has two
-parameters, stepping threshold (in seconds) and number of future clock
-updates for which will be the threshold active. This can be used with
-the 'burst' command to quickly make a new measurement and correct the
-clock by stepping if needed, without waiting for 'chronyd' to complete
-the measurement and update the clock.
-
- makestep 0.1 1
- burst 1/2
-
- BE WARNED - certain software will be seriously affected by such jumps
-to the system time. (That is the reason why chronyd uses slewing
-normally.)
-
-4.3.4.25 manual
-...............
-
-The manual command enables and disables use of the 'settime' command
-(*note settime command::), and is used to modify the behaviour of the
-manual clock driver.
-
- Examples of the command are shown below.
-
- manual on
- manual off
- manual delete 1
- manual list
- manual reset
-
- The 'on' form of the command enables use of the 'settime' command.
-
- The 'off' form of the command disables use of the 'settime' command.
-
- The 'list' form of the command lists all the samples currently stored
-in 'chronyd'. The output is illustrated below.
-
- 210 n_samples = 1
- # Date Time(UTC) Slewed Original Residual
- ====================================================
- 0 27Jan99 22:09:20 0.00 0.97 0.00
-
- The columns as as follows :
-
- 1. The sample index (used for the 'manual delete' command)
- 2. The date and time of the sample
- 3. The system clock error when the timestamp was entered, adjusted to
- allow for changes made to the system clock since.
- 4. The system clock error when the timestamp was entered, as it
- originally was (without allowing for changes to the system clock
- since).
- 5. The regression residual at this point, in seconds. This allows
- 'outliers' to be easily spotted, so that they can be deleted using
- the 'manual delete' command.
-
- The 'delete' form of the command deletes a single sample. The
-parameter is the index of the sample, as shown in the first column of
-the output from 'manual list'. Following deletion of the data point,
-the current error and drift rate are re-estimated from the remaining
-data points and the system clock trimmed if necessary. This option is
-intended to allow 'outliers' to be discarded, i.e. samples where the
-administrator realises he/she has entered a very poor timestamp.
-
- The 'reset' form of the command deletes all samples at once. The
-system clock is left running as it was before the command was entered.
-
-4.3.4.26 maxdelay
-.................
-
-This allows the 'maxdelay' option for one of the sources to be modified,
-in the same way as specifying the 'maxdelay' option for the 'server'
-directive in the configuration file (*note server directive::).
-
- The following examples illustrate the syntax
-
- maxdelay foo.example.net 0.3
- maxdelay 1.2.3.4 0.0015
- maxdelay 2001:db8::1 0.0015
-
- The first example sets the maximum network delay allowed for a
-measurement to the host 'foo.example.net' to 0.3 seconds. The second
-and third examples set the maximum network delay for a measurement to
-the host with IPv4 address '1.2.3.4' and the host with IPv6 address
-'2001:db8::1' to 1.5 milliseconds.
-
- (Any measurement whose network delay exceeds the specified value is
-discarded.)
-
-4.3.4.27 maxdelaydevratio
-.........................
-
-This allows the 'maxdelaydevratio' option for one of the sources to be
-modified, in the same way as specifying the 'maxdelaydevratio' option
-for the 'server' directive in the configuration file (*note server
-directive::).
-
- The following examples illustrate the syntax
-
- maxdelaydevratio foo.example.net 0.1
- maxdelaydevratio 1.2.3.4 1.0
- maxdelaydevratio 2001:db8::1 100.0
-
-4.3.4.28 maxdelayratio
-......................
-
-This allows the 'maxdelayratio' option for one of the sources to be
-modified, in the same way as specifying the 'maxdelayratio' option for
-the 'server' directive in the configuration file (*note server
-directive::).
-
- The following examples illustrate the syntax
-
- maxdelayratio foo.example.net 1.5
- maxdelayratio 1.2.3.4 2.0
- maxdelayratio 2001:db8::1 2.0
-
- The first example sets the maximum network delay for a measurement to
-the host 'foo.example.net' to be 1.5 times the minimum delay found
-amongst the previous measurements that have been retained. The second
-and third examples set the maximum network delay for a measurement to
-the host with IPv4 address '1.2.3.4' and the host with IPv6 address
-'2001:db8::1' to be double the retained minimum.
-
- As for 'maxdelay', any measurement whose network delay is too large
-will be discarded.
-
-4.3.4.29 maxpoll
-................
-
-The 'maxpoll' command is used to modify the minimum polling interval for
-one of the current set of sources. It is equivalent to the 'maxpoll'
-option in the 'server' directive in the configuration file (*note server
-directive::).
-
- The syntax is as follows
-
- maxpoll <host> <new-maxpoll>
-
- where the host can be specified as either a machine name or IP
-address. The new minimum poll is specified as a base-2 logarithm of the
-number of seconds between polls (e.g. specify 6 for 64 second
-sampling).
-
- An example is
-
- maxpoll foo.example.net 10
-
- which sets the maximum polling interval for the host
-'foo.example.net' to 1024 seconds.
-
- Note that the new maximum polling interval only takes effect after
-the next measurement has been made.
-
-4.3.4.30 maxupdateskew
-......................
-
-This command has the same effect as the 'maxupdateskew' directive in the
-configuration file, see *note maxupdateskew directive::.
-
-4.3.4.31 minpoll
-................
-
-The 'minpoll' command is used to modify the minimum polling interval for
-one of the current set of sources. It is equivalent to the 'minpoll'
-option in the 'server' directive in the configuration file (*note server
-directive::).
-
- The syntax is as follows
-
- minpoll <host> <new-minpoll>
-
- where the host can be specified as either a machine name or IP
-address. The new minimum poll is specified as a base-2 logarithm of the
-number of seconds between polls (e.g. specify 6 for 64 second
-sampling).
-
- An example is
-
- minpoll foo.example.net 5
-
- which sets the minimum polling interval for the host
-'foo.example.net' to 32 seconds.
-
- Note that the new minimum polling interval only takes effect after
-the next measurement has been made.
-
-4.3.4.32 minstratum
-...................
-
-The 'minstratum' command is used to modify the minimum stratum for one
-of the current set of sources. It is equivalent to the 'minstratum'
-option in the 'server' directive in the configuration file (*note server
-directive::).
-
- The syntax is as follows
-
- minstratum <host> <new-min-stratum>
-
- where the host can be specified as either a machine name or IP
-address.
-
- An example is
-
- minpoll foo.example.net 5
-
- which sets the minimum stratum for the host 'foo.example.net' to 5.
-
- Note that the new minimum stratum only takes effect after the next
-measurement has been made.
-
-4.3.4.33 offline
-................
-
-The 'offline' command is used to warn 'chronyd' that the network
-connection to a particular host or hosts is about to be lost. It should
-be used on computers with a dial-up or similar connection to their time
-sources, to warn 'chronyd' that the connection is about to be broken.
-
- An example of how to use 'offline' in this case is shown in *note
-Advising chronyd of internet availability::.
-
- Another case where 'offline' could be used is where a computer serves
-time to a local group of computers, and has a permanant connection to
-true time servers outside the organisation. However, the external
-connection is heavily loaded at certain times of the day and the
-measurements obtained are less reliable at those times. In this case,
-it is probably most useful to determine the gain/loss rate during the
-quiet periods and let the whole network coast through the loaded
-periods. The 'offline' and 'online' commands can be used to achieve
-this. The situation is shown in the figure below.
-
- +----------+
- |Ext source|
- +----------+
- |
- |
- |/| <-- Link with variable
- | reliability
- |
- +-------------------+
- |Local master server|
- +-------------------+
- |
- +---+---+-----+-----+----+----+
- | | | | | | |
- Local clients
-
- If the source to which 'chronyd' is currently synchronised is
-indicated offline in this way, 'chronyd' will continue to treat it as
-the synchronisation source. If the network connection were broken
-without the 'offline' command being used, 'chronyd' would assume that
-the source had failed and would attempt to pick another synchronisation
-source.
-
- There are four forms of the 'offline' command. The first form is a
-wildcard, meaning all sources. The second form allows an IP address
-mask and a masked address to be specified. The third form uses the CIDR
-notation. The fourth form uses an IP address or a hostname. These
-forms are illustrated below.
-
- offline
- offline 255.255.255.0/1.2.3.0
- offline 2001:db8:789a::/48
- offline foo.example.net
-
- The second form means that the 'offline' command is to be applied to
-any source whose IPv4 address is in the '1.2.3' subnet. (The host's
-address is logically and-ed with the mask, and if the result matches the
-masked-address the host is processed). The third form means that the
-command is to be applied to all sources whose IPv6 addresses have first
-48 bits equal to '2001:db8:789a'. The fourth form means that the
-command is to be applied only to that one source.
-
- The wildcard form of the address is actually equivalent to
-
- offline 0.0.0.0/0.0.0.0
- offline ::/0
-
-4.3.4.34 online
-...............
-
-The 'online' command is opposite in function to the 'offline' command.
-It is used to advise 'chronyd' that network connectivity to a particular
-source or sources has been restored.
-
- The syntax is identical to that of the 'offline' command, see *note
-offline command::.
-
-4.3.4.35 password
-.................
-
-The password command is used to allow chronyc to send privileged
-commands to 'chronyd'. The password can either be entered on the
-command line, or can be entered without echoing. The syntax for
-entering the password on the command line is as follows
-
- password xyzzy
- password ASCII:xyzzy
- password HEX:78797a7a79
-
- To enter the password without it being echoed, enter
-
- password
-
- The computer will respond with a 'Password:' prompt, at which you
-should enter the password and press return.
-
- The password can be encoded as a string of characters not containing
-a space with optional 'ASCII:' prefix or as a hexadecimal number with
-'HEX:' prefix. It has to match 'chronyd's' currently defined command
-key (*note commandkey directive::). If the command key was specified
-with a different hash function than MD5, it's necessary to select the
-hash function with the 'authhash' command (*note authhash command::)
-before entering the password.
-
- The password command is run automatically on start if 'chronyc' was
-started with the '-a' option.
-
-4.3.4.36 polltarget
-...................
-
-The 'polltarget' command is used to modify the poll target for one of
-the current set of sources. It is equivalent to the 'polltarget' option
-in the 'server' directive in the configuration file (*note server
-directive::).
-
- The syntax is as follows
-
- polltarget <host> <new-poll-target>
-
- where the host can be specified as either a machine name or IP
-address.
-
- An example is
-
- polltarget foo.example.net 12
-
- which sets the poll target for the host 'foo.example.net' to 12.
-
-4.3.4.37 quit
-.............
-
-The quit command exits from chronyc and returns the user to the shell
-(same as the exit command).
-
-4.3.4.38 reselect
-.................
-
-To avoid excessive switching between sources, 'chronyd' may stay
-synchronised to a source even when it is not currently the best one
-among the available sources.
-
- The 'reselect' command can be used to force 'chronyd' to reselect the
-best synchronisation source.
-
-4.3.4.39 reselectdist
-.....................
-
-The 'reselectdist' command sets the reselect distance. It is equivalent
-to the 'reselectdist' directive in the configuration file (*note
-reselectdist directive::).
-
-4.3.4.40 retries
-................
-
-The 'retries' command sets the maximum number of retries for 'chronyc'
-requests before giving up. The response timeout is controlled by
-'timeout' command (*note timeout command::).
-
- The default is 2.
-
-4.3.4.41 rtcdata
-................
-
-The 'rtcdata' command displays the current real time clock RTC
-parameters.
-
- An example output is shown below.
-
- RTC ref time (GMT) : Sat May 30 07:25:56 1998
- Number of samples : 10
- Number of runs : 5
- Sample span period : 549
- RTC is fast by : -1.632736 seconds
- RTC gains time at : -107.623 ppm
-
- The fields have the following meaning
-
-'RTC ref time (GMT)'
- This is the RTC reading the last time its error was measured.
-'Number of samples'
- This is the number of previous measurements being used to determine
- the RTC gain/loss rate.
-'Number of runs'
- This is the number of runs of residuals of the same sign following
- the regression fit for (RTC error) versus (RTC time). A value
- which is small indicates that the measurements are not well
- approximated by a linear model, and that the algorithm will tend to
- delete the older measurements to improve the fit.
-'Sample span period'
- This is the period that the measurements span (from the oldest to
- the newest). Without a unit the value is in seconds; suffixes 'm'
- for minutes, 'h' for hours, 'd' for days or 'y' for years may be
- used.
-'RTC is fast by'
- This is the estimate of how many seconds fast the RTC when it
- thought the time was at the reference time (above). If this value
- is large, you may (or may not) want to use the 'trimrtc' command to
- bring the RTC into line with the system clock. (Note, a large
- error will not affect 'chronyd's' operation, unless it becomes so
- big as to start causing rounding errors.
-'RTC gains time at'
- This is the amount of time gained (positive) or lost (negative) by
- the real time clock for each second that it ticks. It is measured
- in parts per million. So if the value shown was +1, suppose the
- RTC was exactly right when it crosses a particular second boundary.
- Then it would be 1 microsecond fast when it crosses its next second
- boundary.
-
-4.3.4.42 settime
-................
-
-The 'settime' command allows the current time to be entered manually, if
-this option has been configured into 'chronyd'. (It may be configured
-either with the 'manual' directive in the configuration file (*note
-manual directive::), or with the 'manual' command of chronyc (*note
-manual command::).
-
- It should be noted that the computer's sense of time will only be as
-accurate as the reference you use for providing this input (e.g. your
-watch), as well as how well you can time the press of the return key.
-
- Providing your computer's time zone is set up properly, you will be
-able to enter a local time (rather than UTC).
-
- The response to a successful 'settime' command indicates the amount
-that the computer's clock was wrong. It should be apparent from this if
-you have entered the time wrongly, e.g. with the wrong time zone.
-
- The rate of drift of the system clock is estimated by a regression
-process using the entered measurement and all previous measurements
-entered during the present run of 'chronyd'. However, the entered
-measurement is used for adjusting the current clock offset (rather than
-the estimated intercept from the regression, which is ignored).
-Contrast what happens with the 'manual delete' command, where the
-intercept is used to set the current offset (since there is no
-measurement that has just been typed in in that case).
-
- The time is parsed by the public domain 'getdate' algorithm.
-Consequently, you can only specify time to the nearest second.
-
- Examples of inputs that are valid are shown below.
-
- settime 16:30
- settime 16:30:05
- settime Nov 21, 1997 16:30:05
-
- For a full description of 'getdate', get hold of the getdate
-documentation (bundled, for example, with the source for GNU tar).
-
-4.3.4.43 smoothing
-..................
-
-The 'smoothing' command displays the current state of the NTP server
-time smoothing. An example of the output is shown below.
-
- Active : Yes
- Offset : +1.000268817 seconds
- Frequency : -0.142859 ppm
- Wander : -0.010000 ppm per second
- Last update : 17.8 seconds ago
- Remaining time : 19988.4 seconds
-
- The fields are explained as follows.
-
-'Active'
- This shows if the server time smoothing is currently active.
- Possible values are 'Yes' and 'No'. If the 'leaponly' option is
- included in the 'smoothtime' directive, '(leap second only)' will
- be shown on the line.
-
-'Offset'
- This is the current offset applied to the time sent to NTP clients.
- Positive value means the clients are getting time that's ahead of
- true time.
-
-'Frequency'
- The current frequency offset of the served time. Negative value
- means the time observed by clients is running slower than true
- time.
-
-'Wander'
- The current frequency wander of the served time. Negative value
- means the time observed by clients is slowing down.
-
-'Last update'
- This field shows how long ago was the time smoothing process
- updated, e.g. 'chronyd' accumulated a new measurement.
-
-'Remaining time'
- The time it would take for the smoothing process to get to zero
- offset and frequency if there were no more updates.
-
-4.3.4.44 smoothtime
-...................
-
-The 'smoothtime' command can be used to reset or activate the server
-time smoothing process if it is configured with the 'smoothtime'
-directive (*note smoothtime directive::).
-
- The syntax is as follows
-
- smoothtime reset
- smoothtime activate
-
-4.3.4.45 sources
-................
-
-This command displays information about the current time sources that
-'chronyd' is accessing.
-
- The optional argument '-v' can be specified, meaning _verbose_. In
-this case, extra caption lines are shown as a reminder of the meanings
-of the columns.
-
- 210 Number of sources = 3
- MS Name/IP address Stratum Poll Reach LastRx Last sample
- ===============================================================================
- #* GPS0 0 4 377 11 -479ns[ -621ns] +/- 134ns
- ^? foo.example.net 2 6 377 23 -923us[ -924us] +/- 43ms
- ^+ bar.example.net 1 6 377 21 -2629us[-2619us] +/- 86ms
-
- The columns are as follows:
-
-'M'
- This indicates the mode of the source. '^' means a server, '='
- means a peer and '#' indicates a locally connected reference clock.
-
-'S'
- This column indicates the state of the sources. '*' indicates the
- source to which 'chronyd' is currently synchronised. '+' indicates
- acceptable sources which are combined with the selected source.
- '-' indicates acceptable sources which are excluded by the
- combining algorithm. '?' indicates sources to which connectivity
- has been lost or whose packets don't pass all tests. 'x' indicates
- a clock which 'chronyd' thinks is is a falseticker (i.e. its time
- is inconsistent with a majority of other sources). '~' indicates a
- source whose time appears to have too much variability. The '?'
- condition is also shown at start-up, until at least 3 samples have
- been gathered from it.
-
-'Name/IP address'
- This shows the name or the IP address of the source, or refid for
- reference clocks.
-
-'Stratum'
- This shows the stratum of the source, as reported in its most
- recently received sample. Stratum 1 indicates a computer with a
- locally attached reference clock. A computer that is synchronised
- to a stratum 1 computer is at stratum 2. A computer that is
- synchronised to a stratum 2 computer is at stratum 3, and so on.
-
-'Poll'
- This shows the rate at which the source is being polled, as a
- base-2 logarithm of the interval in seconds. Thus, a value of 6
- would indicate that a measurement is being made every 64 seconds.
-
- 'chronyd' automatically varies the polling rate in response to
- prevailing conditions.
-
-'Reach'
- This shows the source's reachability register printed as octal
- number. The register has 8 bits and is updated on every received
- or missed packet from the source. A value of 377 indicates that a
- valid reply was received for all from the last eight transmissions.
-
-'LastRx'
- This column shows how long ago the last sample was received from
- the source. This is normally in seconds. The letters 'm', 'h',
- 'd' or 'y' indicate minutes, hours, days or years. A value of 10
- years indicates there were no samples received from this source
- yet.
-
-'Last sample'
- This column shows the offset between the local clock and the source
- at the last measurement. The number in the square brackets shows
- the actual measured offset. This may be suffixed by 'ns'
- (indicating nanoseconds), 'us' (indicating microseconds), 'ms'
- (indicating milliseconds), or 's' (indicating seconds). The number
- to the left of the square brackets shows the original measurement,
- adjusted to allow for any slews applied to the local clock since.
- The number following the '+/-' indicator shows the margin of error
- in the measurement.
-
- Positive offsets indicate that the local clock is fast of the
- source.
-
-4.3.4.46 sourcestats
-....................
-
-The 'sourcestats' command displays information about the drift rate and
-offset estimatation process for each of the sources currently being
-examined by 'chronyd'.
-
- The optional argument '-v' can be specified, meaning _verbose_. In
-this case, extra caption lines are shown as a reminder of the meanings
-of the columns.
-
- An example report is
-
- 210 Number of sources = 1
- Name/IP Address NP NR Span Frequency Freq Skew Offset Std Dev
- ===============================================================================
- abc.def.ghi 11 5 46m -0.001 0.045 1us 25us
-
- The columns are as follows
-
-'Name/IP Address'
- This is the name or IP address of the NTP server (or peer) or refid
- of the refclock to which the rest of the line relates.
-
-'NP'
- This is the number of sample points currently being retained for
- the server. The drift rate and current offset are estimated by
- performing a linear regression through these points.
-
-'NR'
- This is the number of runs of residuals having the same sign
- following the last regression. If this number starts to become too
- small relative to the number of samples, it indicates that a
- straight line is no longer a good fit to the data. If the number
- of runs is too low, 'chronyd' discards older samples and re-runs
- the regression until the number of runs becomes acceptable.
-
-'Span'
- This is the interval between the oldest and newest samples. If no
- unit is shown the value is in seconds. In the example, the
- interval is 46 minutes.
-
-'Frequency'
- This is the estimated residual frequency for the server, in parts
- per million. In this case, the computer's clock is estimated to be
- running 1 part in 10**9 slow relative to the server.
-
-'Freq Skew'
- This is the estimated error bounds on 'Freq' (again in parts per
- million).
-
-'Offset'
- This is the estimated offset of the source.
-
-'Std Dev'
- This is the estimated sample standard deviation.
-
-4.3.4.47 timeout
-................
-
-The 'timeout' command sets the initial timeout for 'chronyc' requests in
-milliseconds. If no response is received from 'chronyd', the timeout is
-doubled and the request is resent. The maximum number of retries is
-configured with the 'retries' command (*note retries command::).
-
- By default, the timeout is 1000 milliseconds or 100 milliseconds if
-'chronyc' is contacting localhost (i.e. the '-h' option wasn't
-specified) and 'chronyd' was compiled with asynchronous name resolving.
-
-4.3.4.48 tracking
-.................
-
-The 'tracking' command displays parameters about the system's clock
-performance. An example of the output is shown below.
-
- Reference ID : 1.2.3.4 (foo.example.net)
- Stratum : 3
- Ref time (UTC) : Fri Feb 3 15:00:29 2012
- System time : 0.000001501 seconds slow of NTP time
- Last offset : -0.000001632 seconds
- RMS offset : 0.000002360 seconds
- Frequency : 331.898 ppm fast
- Residual freq : 0.004 ppm
- Skew : 0.154 ppm
- Root delay : 0.373169 seconds
- Root dispersion : 0.024780 seconds
- Update interval : 64.2 seconds
- Leap status : Normal
-
-
- The fields are explained as follows.
-
-'Reference ID'
- This is the refid and name (or IP address) if available, of the
- server to which the computer is currently synchronised. If this is
- '127.127.1.1' it means the computer is not synchronised to any
- external source and that you have the 'local' mode operating (via
- the 'local' command in 'chronyc' (*note local command::), or the
- 'local' directive in the '/etc/chrony.conf' file (*note local
- directive::)).
-
-'Stratum'
- The stratum indicates how many hops away from a computer with an
- attached reference clock we are. Such a computer is a stratum-1
- computer, so the computer in the example is two hops away (i.e.
- 'foo.example.net' is a stratum-2 and is synchronised from a
- stratum-1).
-
-'Ref time'
- This is the time (UTC) at which the last measurement from the
- reference source was processed.
-
-'System time'
- In normal operation, 'chronyd' _never_ steps the system clock,
- because any jump in the timescale can have adverse consequences for
- certain application programs. Instead, any error in the system
- clock is corrected by slightly speeding up or slowing down the
- system clock until the error has been removed, and then returning
- to the system clock's normal speed. A consequence of this is that
- there will be a period when the system clock (as read by other
- programs using the 'gettimeofday()' system call, or by the 'date'
- command in the shell) will be different from 'chronyd's' estimate
- of the current true time (which it reports to NTP clients when it
- is operating in server mode). The value reported on this line is
- the difference due to this effect.
-
- On systems other than Linux, 'chronyd' doesn't adjust the
- fundamental rate of the system clock, so keeps the system time
- correct by periodically making offsets to it as though an error had
- been measured. The build up of these offsets will be observed in
- this report.
-
-'Last offset'
- This is the estimated local offset on the last clock update.
-
-'RMS offset'
- This is a long-term average of the offset value.
-
-'Frequency'
- The 'frequency' is the rate by which the system's clock would be
- would be wrong if 'chronyd' was not correcting it. It is expressed
- in ppm (parts per million). For example, a value of 1ppm would
- mean that when the system's clock thinks it has advanced 1 second,
- it has actually advanced by 1.000001 seconds relative to true time.
-
- As you can see in the example, the clock in the computer is not a
- very good one - it gains about 30 seconds per day!
-
-'Residual freq'
- This shows the 'residual frequency' for the currently selected
- reference source. This reflects any difference between what the
- measurements from the reference source indicate the frequency
- should be and the frequency currently being used.
-
- The reason this is not always zero is that a smoothing procedure is
- applied to the frequency. Each time a measurement from the
- reference source is obtained and a new residual frequency computed,
- the estimated accuracy of this residual is compared with the
- estimated accuracy (see 'skew' next) of the existing frequency
- value. A weighted average is computed for the new frequency, with
- weights depending on these accuracies. If the measurements from
- the reference source follow a consistent trend, the residual will
- be driven to zero over time.
-
-'Skew'
- This is the estimated error bound on the the frequency.
-
-'Root delay'
- This is the total of the network path delays to the stratum-1
- computer from which the computer is ultimately synchronised.
-
-'Root dispersion'
- This is the total dispersion accumulated through all the computers
- back to the stratum-1 computer from which the computer is
- ultimately synchronised. Dispersion is due to system clock
- resolution, statistical measurement variations etc.
-
- An absolute bound on the computer's clock accuracy (assuming the
- stratum-1 computer is correct) is given by
-
- clock_error <= root_dispersion + (0.5 * |root_delay|)
-
-'Update interval'
- This is the interval between the last two clock updates.
-
-'Leap status'
- This is the leap status, which can be 'Normal', 'Insert second',
- 'Delete second' or 'Not synchronised'.
-
-4.3.4.49 trimrtc
-................
-
-The 'trimrtc' command is used to correct the system's real time clock
-(RTC) to the main system clock. It has no effect if the error between
-the two clocks is currently estimated at less than a second (the
-resolution of the RTC is only 1 second).
-
- The command takes no arguments. It performs the following steps (if
-the RTC is more than 1 second away from the system clock):
-
- 1. Remember the currently estimated gain/loss rate of the RTC and
- flush the previous measurements.
- 2. Step the real time clock to bring it within a second of the system
- clock.
- 3. Make several measurements to accurately determine the new offset
- between the RTC and the system clock (i.e. the remaining fraction
- of a second error)
- 4. Save the RTC parameters to the RTC file (specified with the
- 'rtcfile' directive in the configuration file (*note rtcfile
- directive::).
-
- The last step is done as a precaution against the computer suffering
-a power failure before either the daemon exits or the 'writertc' command
-is issued.
-
- 'chronyd' will still work perfectly well both whilst operating and
-across machine reboots even if the 'trimrtc' command is never used (and
-the RTC is allowed to drift away from true time). The 'trimrtc' command
-is provided as a method by which it can be corrected, in a manner
-compatible with 'chronyd' using it to maintain accurate time across
-machine reboots.
-
- The 'trimrtc' command can be executed automatically by 'chronyd' with
-the 'rtcautotrim' directive (*note rtcautotrim directive::).
-
-4.3.4.50 waitsync
-.................
-
-The 'waitsync' command waits for 'chronyd' to synchronise.
-
- Up to three optional arguments can be specified, the first is the
-maximum number of tries in 10 second intervals before giving up and
-returning a non-zero error code. When 0 is specified, or there are no
-arguments, the number of tries will not be limited.
-
- The second and third arguments are the maximum allowed remaining
-correction of the system clock and the maximum allowed skew (in ppm) as
-reported by the 'tracking' command (*note tracking command::) in the
-'System time' and 'Skew' fields. If not specified or zero, the value
-will not be checked.
-
- An example is
-
- waitsync 60 0.01
-
- which will wait up to about 10 minutes for 'chronyd' to synchronise
-to a source and the remaining correction to be less than 10
-milliseconds.
-
-4.3.4.51 writertc
-.................
-
-The 'writertc' command writes the currently estimated error and
-gain/loss rate parameters for the RTC to the RTC file (specified with
-the 'rtcfile' directive (*note rtcfile directive::)). This information
-is also written automatically when 'chronyd' is killed (with SIGHUP,
-SIGINT, SIGQUIT or SIGTERM) or when the 'trimrtc' command is issued.
-
-Appendix A GNU General Public License
-*************************************
-
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin
-Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to
-copy and distribute verbatim copies of this license document, but
-changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your freedom
-to share and change it. By contrast, the GNU General Public License is
-intended to guarantee your freedom to share and change free software-to
-make sure the software is free for all its users. This General Public
-License applies to most of the Free Software Foundation's software and
-to any other program whose authors commit to using it. (Some other Free
-Software Foundation software is covered by the GNU Lesser General Public
-License instead.) You can apply it to your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it if
-you want it, that you can change the software or use pieces of it in new
-free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software,
-and (2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING,
-DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it, either
-verbatim or with modifications and/or translated into another language.
-(Hereinafter, translation is included without limitation in the term
-"modification".) Each licensee is addressed as "you".
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of running
-the Program is not restricted, and the output from the Program is
-covered only if its contents constitute a work based on the Program
-(independent of having been made by running the Program). Whether that
-is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the notices
-that refer to this License and to the absence of any warranty; and give
-any other recipients of the Program a copy of this License along with
-the Program.
-
- You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and distribute
-such modifications or work under the terms of Section 1 above, provided
-that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
-stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
-whole or in part contains or is derived from the Program or any part
-thereof, to be licensed as a whole at no charge to all third parties
-under the terms of this License.
-
- c) If the modified program normally reads commands interactively when
-run, you must cause it, when started running for such interactive use in
-the most ordinary way, to print or display an announcement including an
-appropriate copyright notice and a notice that there is no warranty (or
-else, saying that you provide a warranty) and that users may
-redistribute the program under these conditions, and telling the user
-how to view a copy of this License. (Exception: if the Program itself
-is interactive but does not normally print such an announcement, your
-work based on the Program is not required to print an announcement.)
-
- These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program, and
-can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based on
-the Program, the distribution of the whole must be on the terms of this
-License, whose permissions for other licensees extend to the entire
-whole, and thus to each and every part regardless of who wrote it.
-
- Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
- In addition, mere aggregation of another work not based on the
-Program with the Program (or with a work based on the Program) on a
-volume of a storage or distribution medium does not bring the other work
-under the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
-source code, which must be distributed under the terms of Sections 1 and
-2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three years,
-to give any third party, for a charge no more than your cost of
-physically performing source distribution, a complete machine-readable
-copy of the corresponding source code, to be distributed under the terms
-of Sections 1 and 2 above on a medium customarily used for software
-interchange; or,
-
- c) Accompany it with the information you received as to the offer to
-distribute corresponding source code. (This alternative is allowed only
-for noncommercial distribution and only if you received the program in
-object code or executable form with such an offer, in accord with
-Subsection b above.)
-
- The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to control
-compilation and installation of the executable. However, as a special
-exception, the source code distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies the
-executable.
-
- If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent access
-to copy the source code from the same place counts as distribution of
-the source code, even though third parties are not compelled to copy the
-source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt otherwise
-to copy, modify, sublicense or distribute the Program is void, and will
-automatically terminate your rights under this License. However,
-parties who have received copies, or rights, from you under this License
-will not have their licenses terminated so long as such parties remain
-in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and all
-its terms and conditions for copying, distributing or modifying the
-Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further restrictions
-on the recipients' exercise of the rights granted herein. You are not
-responsible for enforcing compliance by third parties to this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent license
-would not permit royalty-free redistribution of the Program by all those
-who receive copies directly or indirectly through you, then the only way
-you could satisfy both it and this License would be to refrain entirely
-from distribution of the Program.
-
- If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
- It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is implemented
-by public license practices. Many people have made generous
-contributions to the wide range of software distributed through that
-system in reliance on consistent application of that system; it is up to
-the author/donor to decide if he or she is willing to distribute
-software through any other system and a licensee cannot impose that
-choice.
-
- This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License may
-add an explicit geographical distribution limitation excluding those
-countries, so that distribution is permitted only in or among countries
-not thus excluded. In such case, this License incorporates the
-limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new
-versions of the General Public License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies a version number of this License which applies to it
-and "any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Program does not specify a version
-number of this License, you may choose any version ever published by the
-Free Software Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the
-author to ask for permission. For software which is copyrighted by the
-Free Software Foundation, write to the Free Software Foundation; we
-sometimes make exceptions for this. Our decision will be guided by the
-two goals of preserving the free status of all derivatives of our free
-software and of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND,
-EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
-ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH
-YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
-NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
-DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
-DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
-(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
-INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF
-THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR
-OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these
-terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it
-does.> Copyright (C) <year> <name of author>
-
- This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by the
-Free Software Foundation; either version 2 of the License, or (at your
-option) any later version.
-
- This program is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
-Public License for more details.
-
- You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software Foundation,
-Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
- Also add information on how to contact you by electronic and paper
-mail.
-
- If the program is interactive, make it output a short notice like
-this when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author Gnomovision
-comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is
-free software, and you are welcome to redistribute it under certain
-conditions; type 'show c' for details.
-
- The hypothetical commands 'show w' and 'show c' should show the
-appropriate parts of the General Public License. Of course, the
-commands you use may be called something other than 'show w' and 'show
-c'; they could even be mouse-clicks or menu items-whatever suits your
-program.
-
- You should also get your employer (if you work as a programmer) or
-your school, if any, to sign a "copyright disclaimer" for the program,
-if necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
-program 'Gnomovision' (which makes passes at compilers) written by James
-Hacker.
-
- <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice
-
- This General Public License does not permit incorporating your
-program into proprietary programs. If your program is a subroutine
-library, you may consider it more useful to permit linking proprietary
-applications with the library. If this is what you want to do, use the
-GNU Lesser General Public License instead of this License.
-
-1 Introduction
- 1.1 Overview
- 1.2 Acknowledgements
- 1.3 Availability
- 1.3.1 Getting the software
- 1.3.2 Platforms
- 1.4 Relationship to other software packages
- 1.4.1 ntpd
- 1.4.2 timed
- 1.5 Distribution rights and (lack of) warranty
- 1.6 Bug reporting and suggestions
- 1.7 Contributions
-2 Installation
- 2.1 Support for line editing libraries
- 2.2 Extra options for package builders
-3 Typical operating scenarios
- 3.1 Computers connected to the internet
- 3.2 Infrequent connection to true NTP servers
- 3.2.1 Setting up the configuration file for infrequent connections
- 3.2.2 How to tell chronyd when the internet link is available.
- 3.3 Isolated networks
- 3.4 The home PC with a dial-up connection
- 3.4.1 Assumptions/how the software works
- 3.4.2 Typical configuration files.
- 3.5 Other important configuration options
-4 Usage reference
- 4.1 Starting chronyd
- 4.2 The chronyd configuration file
- 4.2.1 Comments in the configuration file
- 4.2.2 acquisitionport
- 4.2.3 allow
- 4.2.4 bindacqaddress
- 4.2.5 bindaddress
- 4.2.6 bindcmdaddress
- 4.2.7 broadcast
- 4.2.8 clientloglimit
- 4.2.9 cmdallow
- 4.2.10 cmddeny
- 4.2.11 cmdport
- 4.2.12 combinelimit
- 4.2.13 commandkey
- 4.2.14 corrtimeratio
- 4.2.15 deny
- 4.2.16 driftfile
- 4.2.17 dumpdir
- 4.2.18 dumponexit
- 4.2.19 fallbackdrift
- 4.2.20 generatecommandkey
- 4.2.21 hwclockfile
- 4.2.22 include
- 4.2.23 initstepslew
- 4.2.24 keyfile
- 4.2.25 leapsecmode
- 4.2.26 leapsectz
- 4.2.27 local
- 4.2.28 lock_all
- 4.2.29 log
- 4.2.29.1 Measurements log file format
- 4.2.29.2 Statistics log file format
- 4.2.29.3 Tracking log file format
- 4.2.29.4 Real-time clock log file format
- 4.2.29.5 Refclocks log file format
- 4.2.29.6 Tempcomp log file format
- 4.2.30 logbanner
- 4.2.31 logchange
- 4.2.32 logdir
- 4.2.33 mailonchange
- 4.2.34 makestep
- 4.2.35 manual
- 4.2.36 maxchange
- 4.2.37 maxclockerror
- 4.2.38 maxsamples
- 4.2.39 maxslewrate
- 4.2.40 maxupdateskew
- 4.2.41 minsamples
- 4.2.42 minsources
- 4.2.43 noclientlog
- 4.2.44 peer
- 4.2.45 pidfile
- 4.2.46 pool
- 4.2.47 port
- 4.2.48 refclock
- 4.2.49 reselectdist
- 4.2.50 rtcautotrim
- 4.2.51 rtcdevice
- 4.2.52 rtcfile
- 4.2.53 rtconutc
- 4.2.54 rtcsync
- 4.2.55 sched_priority
- 4.2.56 server
- 4.2.57 smoothtime
- 4.2.58 stratumweight
- 4.2.59 tempcomp
- 4.2.60 user
- 4.3 Running chronyc
- 4.3.1 Basic use
- 4.3.2 Command line options
- 4.3.3 Security with chronyc
- 4.3.4 Command reference
- 4.3.4.1 accheck
- 4.3.4.2 activity
- 4.3.4.3 add peer
- 4.3.4.4 add server
- 4.3.4.5 allow all
- 4.3.4.6 allow
- 4.3.4.7 authhash
- 4.3.4.8 burst
- 4.3.4.9 clients
- 4.3.4.10 cmdaccheck
- 4.3.4.11 cmdallow all
- 4.3.4.12 cmdallow
- 4.3.4.13 cmddeny all
- 4.3.4.14 cmddeny
- 4.3.4.15 cyclelogs
- 4.3.4.16 delete
- 4.3.4.17 deny all
- 4.3.4.18 deny
- 4.3.4.19 dns
- 4.3.4.20 dump
- 4.3.4.21 exit
- 4.3.4.22 help
- 4.3.4.23 local
- 4.3.4.24 makestep
- 4.3.4.25 manual
- 4.3.4.26 maxdelay
- 4.3.4.27 maxdelaydevratio
- 4.3.4.28 maxdelayratio
- 4.3.4.29 maxpoll
- 4.3.4.30 maxupdateskew
- 4.3.4.31 minpoll
- 4.3.4.32 minstratum
- 4.3.4.33 offline
- 4.3.4.34 online
- 4.3.4.35 password
- 4.3.4.36 polltarget
- 4.3.4.37 quit
- 4.3.4.38 reselect
- 4.3.4.39 reselectdist
- 4.3.4.40 retries
- 4.3.4.41 rtcdata
- 4.3.4.42 settime
- 4.3.4.43 smoothing
- 4.3.4.44 smoothtime
- 4.3.4.45 sources
- 4.3.4.46 sourcestats
- 4.3.4.47 timeout
- 4.3.4.48 tracking
- 4.3.4.49 trimrtc
- 4.3.4.50 waitsync
- 4.3.4.51 writertc
-Appendix A GNU General Public License
diff --git a/chronyc.1.in b/chronyc.1.in
index f738b28..df8ca9f 100644
--- a/chronyc.1.in
+++ b/chronyc.1.in
@@ -1,4 +1,4 @@
-.TH CHRONYC 1 "June 2015" "chrony 2.1.1" "User's Manual"
+.TH CHRONYC 1 "October 2015" "chrony 2.2" "User's Manual"
.SH NAME
chronyc \- command-line interface for chronyd
@@ -24,7 +24,8 @@ A summary of the options supported by \fBchronyc\fR is included below.
.TP
\fB\-h\fR \fIhostname\fR
-specify hostname (default 127.0.0.1)
+specify hostname or comma-separated list of addresses
+(default @CHRONYSOCKDIR@/chronyd.sock,127.0.0.1,::1)
.TP
\fB\-p\fR \fIport-number\fR
specify port-number
@@ -32,6 +33,9 @@ specify port-number
\fB\-n\fR
display raw IP addresses (don't attempt to look up hostnames)
.TP
+\fB\-d\fR
+print debugging messages (if compiled with debugging support)
+.TP
\fB\-4\fR
resolve hostnames only to IPv4 addresses
.TP
@@ -43,14 +47,10 @@ allow multiple commands to be specified on the command line. Each argument
will be interpreted as a whole command.
.TP
\fB\-f\fR \fIconf-file\fR
-This option can be used to specify an alternate location for the
-configuration file (default \fI@SYSCONFDIR@/chrony.conf\fR). The configuration file is
-needed for the \fB-a\fR option.
+this option is ignored and is provided only for compatibility.
.TP
\fB\-a\fR
-With this option chronyc will try to authenticate automatically on
-start. It will read the configuration file, read the command key from the
-keyfile and run the authhash and password commands.
+this option is ignored and is provided only for compatibility.
.TP
\fIcommand\fR
specify command. If no command is given, chronyc will read commands
diff --git a/chronyd.8.in b/chronyd.8.in
index bafe85e..22edec7 100644
--- a/chronyd.8.in
+++ b/chronyd.8.in
@@ -1,4 +1,4 @@
-.TH CHRONYD 8 "June 2015" "chrony 2.1.1" "System Administration"
+.TH CHRONYD 8 "October 2015" "chrony 2.2" "System Administration"
.SH NAME
chronyd \- chrony background daemon
@@ -40,9 +40,11 @@ A summary of the options supported by \fBchronyd\fR is included below.
.TP
\fB\-P\fR \fIpriority\fR
-This option will select the SCHED_FIFO real-time scheduler at the specified
-priority (which must be between 0 and 100). This mode is supported only on
-Linux.
+On Linux, this option will select the SCHED_FIFO real-time scheduler at the
+specified priority (which must be between 0 and 100). On Mac OS X, this
+option must have either a value of 0 (the default) to disable the thread
+time constraint policy or 1 for the policy to be enabled. Other systems do not
+support this option.
.TP
.B \-m
This option will lock chronyd into RAM so that it will never be paged out.
@@ -67,10 +69,9 @@ This option will reload sample histories for each of the servers being used.
These histories are created by using the \fIdump\fR command in \fIchronyc\fR,
or by setting the \fIdumponexit\fR directive in the configuration file. This
option is useful if you want to stop and restart \fBchronyd\fR briefly for any
-reason, e.g. to install a new version. However, it only makes sense on
+reason, e.g. to install a new version. However, it should be used only on
systems where the kernel can maintain clock compensation whilst not under
-\fBchronyd\fR's control. The only version where this happens so far is Linux.
-On other systems this option should not be used.
+\fBchronyd\fR's control (i.e. Linux, FreeBSD, NetBSD and Solaris).
.TP
.B \-R
When this option is used, the \fIinitstepslew\fR directive and the
@@ -79,13 +80,9 @@ option is useful when restarting \fBchronyd\fR and can be used in conjunction
with the \fB-r\fR option.
.TP
.B \-s
-This option will set the system clock from the computer's real-time
-clock. This is analogous to supplying the \fI-s\fR flag to the
-\fI/sbin/hwclock\fR program during the Linux boot sequence.
-
-Support for real-time clocks is limited at present - the criteria
-are described in the section on the \fIrtcfile\fR directive in the
-documentation supplied with the distribution.
+This option will set the system clock from the computer's real-time clock or
+to the last modification time of the file specified by the \fIdriftfile\fR
+directive. Real-time clocks are supported only on Linux.
If used in conjunction with the \fB-r\fR flag, \fBchronyd\fR will attempt
to preserve the old samples after setting the system clock from
@@ -96,16 +93,23 @@ not in use. For this to work well, it relies on \fBchronyd\fR having
been able to determine accurate statistics for the difference
between the RTC and system clock last time the computer was on.
-If \fBchronyd\fR doesn't support the RTC on your computer or there is no RTC
-installed, the system clock will be set with this option forward to the time of
-the last modification of the drift file (specified by the \fIdriftfile\fR
-directive) to restore the system time at which \fBchronyd\fR was previously
-stopped.
+If the last modification time of the drift file is later than the current time
+and the RTC time, the system time will be set to it to restore the time when
+\fBchronyd\fR was previously stopped. This is useful on computers that have no
+RTC or the RTC is broken (e.g. it has no battery).
.TP
\fB\-u\fR \fIuser\fR
-This option sets the name of the user to which will \fBchronyd\fR switch to
-drop root privileges if compiled with Linux capabilities support (default
-\fB@DEFAULT_USER@\fR).
+This option sets the name of the system user to which \fBchronyd\fR will switch
+after start in order to drop root privileges. It overrides the \fBuser\fR
+directive (default \fB@DEFAULT_USER@\fR). It may be set to a non-root user
+only when \fBchronyd\fR is compiled with support for Linux capabilities
+(libcap) or on NetBSD with the \fB/dev/clockctl\fR device.
+.TP
+\fB\-F\fR \fIlevel\fR
+This option configures a system call filter when \fBchronyd\fR is compiled with
+support for the Linux secure computing (seccomp) facility. In level 1 the
+process is killed when a forbidden system call is made, in level -1 the SYSSIG
+signal is thrown instead and in level 0 the filter is disabled (default 0).
.TP
.B \-q
When run in this mode, chronyd will set the system clock once
diff --git a/client.c b/client.c
index abe01aa..cd0977c 100644
--- a/client.c
+++ b/client.c
@@ -30,9 +30,11 @@
#include "sysincl.h"
+#include "array.h"
#include "candm.h"
+#include "logging.h"
+#include "memory.h"
#include "nameserv.h"
-#include "hash.h"
#include "getdate.h"
#include "cmdparse.h"
#include "pktlength.h"
@@ -49,23 +51,45 @@
/* ================================================== */
-union sockaddr_in46 {
+union sockaddr_all {
struct sockaddr_in in4;
#ifdef FEAT_IPV6
struct sockaddr_in6 in6;
#endif
- struct sockaddr u;
+ struct sockaddr_un un;
+ struct sockaddr sa;
};
-static int sock_fd;
-union sockaddr_in46 his_addr;
-static socklen_t his_addr_len;
+static ARR_Instance sockaddrs;
+
+static int sock_fd = -1;
+
+static int quit = 0;
static int on_terminal = 0;
static int no_dns = 0;
-static int recv_errqueue = 0;
+/* ================================================== */
+/* Log a message. This is a minimalistic replacement of the logging.c
+ implementation to avoid linking with it and other modules. */
+
+int log_debug_enabled = 0;
+
+void LOG_Message(LOG_Severity severity,
+#if DEBUG > 0
+ LOG_Facility facility, int line_number,
+ const char *filename, const char *function_name,
+#endif
+ const char *format, ...)
+{
+ va_list ap;
+
+ va_start(ap, format);
+ vfprintf(stderr, format, ap);
+ putc('\n', stderr);
+ va_end(ap);
+}
/* ================================================== */
/* Read a single line of commands from standard input. Eventually we
@@ -91,7 +115,7 @@ read_line(void)
line[sizeof(line) - 1] = '\0';
add_history(cmd);
/* free the buffer allocated by readline */
- free(cmd);
+ Free(cmd);
} else {
/* simulate the user has entered an empty line */
*line = '\0';
@@ -110,55 +134,118 @@ read_line(void)
}
/* ================================================== */
-/* Initialise the socket used to talk to the daemon */
-static void
-open_io(const char *hostname, int port)
+#define MAX_ADDRESSES 16
+
+static ARR_Instance
+get_sockaddrs(const char *hostnames, int port)
{
- IPAddr ip;
- int on_off = 1;
+ ARR_Instance addrs;
+ char *hostname, *s1, *s2;
+ IPAddr ip_addrs[MAX_ADDRESSES];
+ union sockaddr_all *addr;
+ int i;
- /* Note, this call could block for a while */
- if (DNS_Name2IPAddress(hostname, &ip, 1) != DNS_Success) {
- fprintf(stderr, "Could not get IP address for %s\n", hostname);
- exit(1);
+ addrs = ARR_CreateInstance(sizeof (union sockaddr_all));
+ s1 = Strdup(hostnames);
+
+ /* Parse the comma-separated list of hostnames */
+ for (hostname = s1; hostname && *hostname; hostname = s2) {
+ s2 = strchr(hostname, ',');
+ if (s2)
+ *s2++ = '\0';
+
+ /* hostname starting with / is considered a path of Unix domain socket */
+ if (hostname[0] == '/') {
+ addr = (union sockaddr_all *)ARR_GetNewElement(addrs);
+ if (snprintf(addr->un.sun_path, sizeof (addr->un.sun_path), "%s", hostname) >=
+ sizeof (addr->un.sun_path))
+ LOG_FATAL(LOGF_Client, "Unix socket path too long");
+ addr->un.sun_family = AF_UNIX;
+ } else {
+ if (DNS_Name2IPAddress(hostname, ip_addrs, MAX_ADDRESSES) != DNS_Success) {
+ DEBUG_LOG(LOGF_Client, "Could not get IP address for %s", hostname);
+ break;
+ }
+
+ for (i = 0; i < MAX_ADDRESSES && ip_addrs[i].family != IPADDR_UNSPEC; i++) {
+ addr = (union sockaddr_all *)ARR_GetNewElement(addrs);
+ UTI_IPAndPortToSockaddr(&ip_addrs[i], port, (struct sockaddr *)addr);
+ DEBUG_LOG(LOGF_Client, "Resolved %s to %s", hostname, UTI_IPToString(&ip_addrs[i]));
+ }
+ }
}
- switch (ip.family) {
- case IPADDR_INET4:
- sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
+ Free(s1);
+ return addrs;
+}
+
+/* ================================================== */
+/* Initialise the socket used to talk to the daemon */
+
+static int
+prepare_socket(union sockaddr_all *addr)
+{
+ socklen_t addr_len;
+ char *dir;
+
+ switch (addr->sa.sa_family) {
+ case AF_UNIX:
+ addr_len = sizeof (addr->un);
+ break;
+ case AF_INET:
+ addr_len = sizeof (addr->in4);
break;
#ifdef FEAT_IPV6
- case IPADDR_INET6:
- sock_fd = socket(AF_INET6, SOCK_DGRAM, 0);
+ case AF_INET6:
+ addr_len = sizeof (addr->in6);
break;
#endif
default:
assert(0);
}
- his_addr_len = UTI_IPAndPortToSockaddr(&ip, port, &his_addr.u);
+ sock_fd = socket(addr->sa.sa_family, SOCK_DGRAM, 0);
if (sock_fd < 0) {
- perror("Can't create socket");
- exit(1);
+ DEBUG_LOG(LOGF_Client, "Could not create socket : %s", strerror(errno));
+ return 0;
}
- /* Enable extended error reporting (e.g. ECONNREFUSED on ICMP unreachable) */
-#ifdef IP_RECVERR
- if (ip.family == IPADDR_INET4 &&
- !setsockopt(sock_fd, IPPROTO_IP, IP_RECVERR, &on_off, sizeof(on_off))) {
- recv_errqueue = 1;
+ if (addr->sa.sa_family == AF_UNIX) {
+ struct sockaddr_un sa_un;
+
+ /* Construct path of our socket. Use the same directory as the server
+ socket and include our process ID to allow multiple chronyc instances
+ running at the same time. */
+ dir = UTI_PathToDir(addr->un.sun_path);
+ if (snprintf(sa_un.sun_path, sizeof (sa_un.sun_path),
+ "%s/chronyc.%d.sock", dir, (int)getpid()) >= sizeof (sa_un.sun_path))
+ LOG_FATAL(LOGF_Client, "Unix socket path too long");
+ Free(dir);
+
+ sa_un.sun_family = AF_UNIX;
+ unlink(sa_un.sun_path);
+
+ /* Bind the socket to the path */
+ if (bind(sock_fd, (struct sockaddr *)&sa_un, sizeof (sa_un)) < 0) {
+ DEBUG_LOG(LOGF_Client, "Could not bind socket : %s", strerror(errno));
+ return 0;
+ }
+
+ /* Allow server without root privileges to send replies to our socket */
+ if (chmod(sa_un.sun_path, 0666) < 0) {
+ DEBUG_LOG(LOGF_Client, "Could not change socket permissions : %s", strerror(errno));
+ return 0;
+ }
}
-#endif
-#ifdef FEAT_IPV6
-#ifdef IPV6_RECVERR
- if (ip.family == IPADDR_INET6 &&
- !setsockopt(sock_fd, IPPROTO_IPV6, IPV6_RECVERR, &on_off, sizeof(on_off))) {
- recv_errqueue = 1;
+
+ if (connect(sock_fd, &addr->sa, addr_len) < 0) {
+ DEBUG_LOG(LOGF_Client, "Could not connect socket : %s", strerror(errno));
+ return 0;
}
-#endif
-#endif
+
+ return 1;
}
/* ================================================== */
@@ -166,9 +253,50 @@ open_io(const char *hostname, int port)
static void
close_io(void)
{
+ union sockaddr_all addr;
+ socklen_t addr_len = sizeof (addr);
+
+ if (sock_fd < 0)
+ return;
+
+ /* Remove our Unix domain socket */
+ if (getsockname(sock_fd, &addr.sa, &addr_len) < 0)
+ LOG_FATAL(LOGF_Client, "getsockname() failed : %s", strerror(errno));
+ if (addr_len <= sizeof (addr) && addr_len > sizeof (addr.sa.sa_family) &&
+ addr.sa.sa_family == AF_UNIX)
+ unlink(addr.un.sun_path);
close(sock_fd);
+ sock_fd = -1;
+}
+
+/* ================================================== */
+
+static int
+open_io(void)
+{
+ static unsigned int address_index = 0;
+ union sockaddr_all *addr;
+ /* If a socket is already opened, close it and try the next address */
+ if (sock_fd >= 0) {
+ close_io();
+ address_index++;
+ }
+
+ /* Find an address for which a socket can be opened and connected */
+ for (; address_index < ARR_GetSize(sockaddrs); address_index++) {
+ addr = (union sockaddr_all *)ARR_GetElement(sockaddrs, address_index);
+ DEBUG_LOG(LOGF_Client, "Opening connection to %s",
+ UTI_SockaddrToString(&addr->sa));
+
+ if (prepare_socket(addr))
+ return 1;
+
+ close_io();
+ }
+
+ return 0;
}
/* ================================================== */
@@ -237,13 +365,13 @@ read_mask_address(char *line, IPAddr *mask, IPAddr *address)
bits_to_mask(-1, address->family, mask);
return 1;
} else {
- fprintf(stderr, "Could not get address for hostname\n");
+ LOG(LOGS_ERR, LOGF_Client, "Could not get address for hostname");
return 0;
}
}
}
- fprintf(stderr, "Invalid syntax for mask/address\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for mask/address");
return 0;
}
@@ -302,11 +430,11 @@ read_address_integer(char *line, IPAddr *address, int *value)
line = CPS_SplitWord(line);
if (sscanf(line, "%d", value) != 1) {
- fprintf(stderr, "Invalid syntax for address value\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for address value");
ok = 0;
} else {
if (DNS_Name2IPAddress(hostname, address, 1) != DNS_Success) {
- fprintf(stderr, "Could not get address for hostname\n");
+ LOG(LOGS_ERR, LOGF_Client, "Could not get address for hostname");
ok = 0;
} else {
ok = 1;
@@ -330,11 +458,11 @@ read_address_double(char *line, IPAddr *address, double *value)
line = CPS_SplitWord(line);
if (sscanf(line, "%lf", value) != 1) {
- fprintf(stderr, "Invalid syntax for address value\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for address value");
ok = 0;
} else {
if (DNS_Name2IPAddress(hostname, address, 1) != DNS_Success) {
- fprintf(stderr, "Could not get address for hostname\n");
+ LOG(LOGS_ERR, LOGF_Client, "Could not get address for hostname");
ok = 0;
} else {
ok = 1;
@@ -567,7 +695,7 @@ process_cmd_burst(CMD_Request *msg, char *line)
CPS_SplitWord(s2);
if (sscanf(s1, "%d/%d", &n_good_samples, &n_total_samples) != 2) {
- fprintf(stderr, "Invalid syntax for burst command\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for burst command");
return 0;
}
@@ -603,7 +731,7 @@ process_cmd_local(CMD_Request *msg, const char *line)
msg->data.local.on_off = htonl(1);
msg->data.local.stratum = htonl(stratum);
} else {
- fprintf(stderr, "Invalid syntax for local command\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for local command");
return 0;
}
@@ -627,7 +755,7 @@ process_cmd_manual(CMD_Request *msg, const char *line)
} else if (!strcmp(p, "reset")) {
msg->data.manual.option = htonl(2);
} else {
- fprintf(stderr, "Invalid syntax for manual command\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for manual command");
return 0;
}
msg->command = htons(REQ_MANUAL);
@@ -662,7 +790,7 @@ parse_allow_deny(CMD_Request *msg, char *line)
/* Try to parse as the name of a machine */
if (DNS_Name2IPAddress(p, &ip, 1) != DNS_Success) {
- fprintf(stderr, "Could not read address\n");
+ LOG(LOGS_ERR, LOGF_Client, "Could not read address");
return 0;
} else {
UTI_IPHostToNetwork(&ip, &msg->data.allow_deny.ip);
@@ -715,7 +843,8 @@ parse_allow_deny(CMD_Request *msg, char *line)
if (n == 1) {
msg->data.allow_deny.subnet_bits = htonl(specified_subnet_bits);
} else {
- fprintf(stderr, "Warning: badly formatted subnet size, using %ld\n", (long) ntohl(msg->data.allow_deny.subnet_bits));
+ LOG(LOGS_WARN, LOGF_Client, "Warning: badly formatted subnet size, using %d",
+ (int)ntohl(msg->data.allow_deny.subnet_bits));
}
}
}
@@ -849,7 +978,7 @@ process_cmd_accheck(CMD_Request *msg, char *line)
UTI_IPHostToNetwork(&ip, &msg->data.ac_check.ip);
return 1;
} else {
- fprintf(stderr, "Could not read address\n");
+ LOG(LOGS_ERR, LOGF_Client, "Could not read address");
return 0;
}
}
@@ -865,7 +994,7 @@ process_cmd_cmdaccheck(CMD_Request *msg, char *line)
UTI_IPHostToNetwork(&ip, &msg->data.ac_check.ip);
return 1;
} else {
- fprintf(stderr, "Could not read address\n");
+ LOG(LOGS_ERR, LOGF_Client, "Could not read address");
return 0;
}
}
@@ -937,42 +1066,42 @@ process_cmd_add_server_or_peer(CMD_Request *msg, char *line)
switch (status) {
case CPS_Success:
if (DNS_Name2IPAddress(data.name, &ip_addr, 1) != DNS_Success) {
- fprintf(stderr, "Invalid host/IP address\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid host/IP address");
break;
}
if (data.params.min_stratum != SRC_DEFAULT_MINSTRATUM) {
- fprintf(stderr, "Option minstratum not supported\n");
+ LOG(LOGS_WARN, LOGF_Client, "Option minstratum not supported");
break;
}
if (data.params.poll_target != SRC_DEFAULT_POLLTARGET) {
- fprintf(stderr, "Option polltarget not supported\n");
+ LOG(LOGS_WARN, LOGF_Client, "Option polltarget not supported");
break;
}
if (data.params.max_delay_dev_ratio != SRC_DEFAULT_MAXDELAYDEVRATIO) {
- fprintf(stderr, "Option maxdelaydevratio not supported\n");
+ LOG(LOGS_WARN, LOGF_Client, "Option maxdelaydevratio not supported");
break;
}
if (data.params.version != NTP_VERSION) {
- fprintf(stderr, "Option version not supported\n");
+ LOG(LOGS_WARN, LOGF_Client, "Option version not supported");
break;
}
if (data.params.max_sources != SRC_DEFAULT_MAXSOURCES) {
- fprintf(stderr, "Option maxsources not supported\n");
+ LOG(LOGS_WARN, LOGF_Client, "Option maxsources not supported");
break;
}
if (data.params.min_samples != SRC_DEFAULT_MINSAMPLES) {
- fprintf(stderr, "Option minsamples not supported\n");
+ LOG(LOGS_WARN, LOGF_Client, "Option minsamples not supported");
break;
}
if (data.params.max_samples != SRC_DEFAULT_MAXSAMPLES) {
- fprintf(stderr, "Option maxsamples not supported\n");
+ LOG(LOGS_WARN, LOGF_Client, "Option maxsamples not supported");
break;
}
@@ -995,7 +1124,7 @@ process_cmd_add_server_or_peer(CMD_Request *msg, char *line)
break;
default:
CPS_StatusToString(status, str, sizeof (str));
- fprintf(stderr, "%s\n", str);
+ LOG(LOGS_ERR, LOGF_Client, "%s", str);
break;
}
@@ -1034,11 +1163,11 @@ process_cmd_delete(CMD_Request *msg, char *line)
CPS_SplitWord(line);
if (!*hostname) {
- fprintf(stderr, "Invalid syntax for address\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for address");
ok = 0;
} else {
if (DNS_Name2IPAddress(hostname, &address, 1) != DNS_Success) {
- fprintf(stderr, "Could not get address for hostname\n");
+ LOG(LOGS_ERR, LOGF_Client, "Could not get address for hostname");
ok = 0;
} else {
UTI_IPHostToNetwork(&address, &msg->data.del_source.ip_addr);
@@ -1052,163 +1181,95 @@ process_cmd_delete(CMD_Request *msg, char *line)
/* ================================================== */
-static char *password = NULL;
-static int password_length;
-static int auth_hash_id;
-
-/* ================================================== */
-
-static int
-process_cmd_password(CMD_Request *msg, char *line)
-{
- char *p;
- struct timeval now;
- int i, len;
-
- /* Blank and free the old password */
- if (password) {
- for (i = 0; i < password_length; i++)
- password[i] = 0;
- free(password);
- password = NULL;
- }
-
- p = line;
-
- if (!*p) {
- /* blank line, prompt for password */
- p = getpass("Password: ");
- }
-
- if (!*p)
- return 0;
-
- len = strlen(p);
- password_length = UTI_DecodePasswordFromText(p);
-
- if (password_length > 0) {
- password = malloc(password_length);
- memcpy(password, p, password_length);
- }
-
- /* Erase the password from the input or getpass buffer */
- for (i = 0; i < len; i++)
- p[i] = 0;
-
- if (password_length <= 0) {
- fprintf(stderr, "Could not decode password\n");
- return 0;
- }
-
- if (gettimeofday(&now, NULL) < 0) {
- printf("500 - Could not read time of day\n");
- return 0;
- } else {
- msg->command = htons(REQ_LOGON); /* Just force a round trip so that we get tokens etc */
- UTI_TimevalHostToNetwork(&now, &msg->data.logon.ts);
- return 1;
- }
-}
-
-/* ================================================== */
-
-static int
-generate_auth(CMD_Request *msg)
-{
- int data_len;
-
- data_len = PKL_CommandLength(msg);
-
- assert(auth_hash_id >= 0);
-
- return UTI_GenerateNTPAuth(auth_hash_id, (unsigned char *)password, password_length,
- (unsigned char *)msg, data_len, ((unsigned char *)msg) + data_len, sizeof (msg->auth));
-}
-
-/* ================================================== */
-
-static int
-check_reply_auth(CMD_Reply *msg, int len)
-{
- int data_len;
-
- data_len = PKL_ReplyLength(msg);
-
- assert(auth_hash_id >= 0);
-
- return UTI_CheckNTPAuth(auth_hash_id, (unsigned char *)password, password_length,
- (unsigned char *)msg, data_len,
- ((unsigned char *)msg) + data_len, len - data_len);
-}
-
-/* ================================================== */
-
static void
give_help(void)
{
- printf("Commands:\n");
- printf("accheck <address> : Check whether NTP access is allowed to <address>\n");
- printf("activity : Check how many NTP sources are online/offline\n");
- printf("add peer <address> ... : Add a new NTP peer\n");
- printf("add server <address> ... : Add a new NTP server\n");
- printf("allow [<subnet-addr>] : Allow NTP access to that subnet as a default\n");
- printf("allow all [<subnet-addr>] : Allow NTP access to that subnet and all children\n");
- printf("burst <n-good>/<n-max> [<mask>/<masked-address>] : Start a rapid set of measurements\n");
- printf("clients : Report on clients that have accessed the server\n");
- printf("cmdaccheck <address> : Check whether command access is allowed to <address>\n");
- printf("cmdallow [<subnet-addr>] : Allow command access to that subnet as a default\n");
- printf("cmdallow all [<subnet-addr>] : Allow command access to that subnet and all children\n");
- printf("cmddeny [<subnet-addr>] : Deny command access to that subnet as a default\n");
- printf("cmddeny all [<subnet-addr>] : Deny command access to that subnet and all children\n");
- printf("cyclelogs : Close and re-open logs files\n");
- printf("delete <address> : Remove an NTP server or peer\n");
- printf("deny [<subnet-addr>] : Deny NTP access to that subnet as a default\n");
- printf("deny all [<subnet-addr>] : Deny NTP access to that subnet and all children\n");
- printf("dump : Dump all measurements to save files\n");
- printf("local off : Disable server capability for unsynchronised clock\n");
- printf("local stratum <stratum> : Enable server capability for unsynchronised clock\n");
- printf("makestep [<threshold> <updates>] : Correct clock by stepping\n");
- printf("manual off|on|reset : Disable/enable/reset settime command and statistics\n");
- printf("manual list : Show previous settime entries\n");
- printf("maxdelay <address> <new-max-delay> : Modify maximum round-trip valid sample delay for source\n");
- printf("maxdelayratio <address> <new-max-ratio> : Modify max round-trip delay ratio for source\n");
- printf("maxdelaydevratio <address> <new-max-ratio> : Modify max round-trip delay dev ratio for source\n");
- printf("maxpoll <address> <new-maxpoll> : Modify maximum polling interval of source\n");
- printf("maxupdateskew <new-max-skew> : Modify maximum skew for a clock frequency update to be made\n");
- printf("minpoll <address> <new-minpoll> : Modify minimum polling interval of source\n");
- printf("minstratum <address> <new-min-stratum> : Modify minimum stratum of source\n");
- printf("offline [<mask>/<masked-address>] : Set sources in subnet to offline status\n");
- printf("online [<mask>/<masked-address>] : Set sources in subnet to online status\n");
- printf("password [<new-password>] : Set command authentication password\n");
- printf("polltarget <address> <new-poll-target> : Modify poll target of source\n");
- printf("reselect : Reselect synchronisation source\n");
- printf("rtcdata : Print current RTC performance parameters\n");
- printf("settime <date/time (e.g. Nov 21, 1997 16:30:05 or 16:30:05)> : Manually set the daemon time\n");
- printf("smoothing : Display current time smoothing state\n");
- printf("smoothtime reset|activate : Reset/activate time smoothing\n");
- printf("sources [-v] : Display information about current sources\n");
- printf("sourcestats [-v] : Display estimation information about current sources\n");
- printf("tracking : Display system time information\n");
- printf("trimrtc : Correct RTC relative to system clock\n");
- printf("waitsync [max-tries [max-correction [max-skew]]] : Wait until synchronised\n");
- printf("writertc : Save RTC parameters to file\n");
- printf("\n");
- printf("authhash <name>: Set command authentication hash function\n");
- printf("dns -n|+n : Disable/enable resolving IP addresses to hostnames\n");
- printf("dns -4|-6|-46 : Resolve hostnames only to IPv4/IPv6/both addresses\n");
- printf("timeout <milliseconds> : Set initial response timeout\n");
- printf("retries <n> : Set maximum number of retries\n");
- printf("exit|quit : Leave the program\n");
- printf("help : Generate this help\n");
- printf("\n");
+ int line, len;
+ const char *s, cols[] =
+ "System clock:\0\0"
+ "tracking\0Display system time information\0"
+ "makestep\0Correct clock by stepping immediately\0"
+ "makestep <threshold> <updates>\0Configure automatic clock stepping\0"
+ "maxupdateskew <skew>\0Modify maximum valid skew to update frequency\0"
+ "waitsync [max-tries [max-correction [max-skew [interval]]]]\0"
+ "Wait until synchronised in specified limits\0"
+ "\0\0"
+ "Time sources:\0\0"
+ "sources [-v]\0Display information about current sources\0"
+ "sourcestats [-v]\0Display statistics about collected measurements\0"
+ "reselect\0Force reselecting synchronisation source\0"
+ "\0\0"
+ "NTP sources:\0\0"
+ "activity\0Check how many NTP sources are online/offline\0"
+ "add server <address> [options]\0Add new NTP server\0"
+ "add peer <address> [options]\0Add new NTP peer\0"
+ "delete <address>\0Remove server or peer\0"
+ "burst <n-good>/<n-max> [<mask>/<address>]\0Start rapid set of measurements\0"
+ "maxdelay <address> <delay>\0Modify maximum valid sample delay\0"
+ "maxdelayratio <address> <ratio>\0Modify maximum valid delay/minimum ratio\0"
+ "maxdelaydevratio <address> <ratio>\0Modify maximum valid delay/deviation ratio\0"
+ "minpoll <address> <poll>\0Modify minimum polling interval\0"
+ "maxpoll <address> <poll>\0Modify maximum polling interval\0"
+ "minstratum <address> <stratum>\0Modify minimum stratum\0"
+ "offline [<mask>/<address>]\0Set sources in subnet to offline status\0"
+ "online [<mask>/<address>]\0Set sources in subnet to online status\0"
+ "polltarget <address> <target>\0Modify poll target\0"
+ "refresh\0Refresh IP addresses\0"
+ "\0\0"
+ "Manual time input:\0\0"
+ "manual off|on|reset\0Disable/enable/reset settime command\0"
+ "manual list\0Show previous settime entries\0"
+ "manual delete <index>\0Delete previous settime entry\0"
+ "settime <time>\0Set daemon time\0"
+ "\0(e.g. Sep 25, 2015 16:30:05 or 16:30:05)\0"
+ "\0\0NTP access:\0\0"
+ "accheck <address>\0Check whether address is allowed\0"
+ "clients\0Report on clients that have accessed the server\0"
+ "allow [<subnet>]\0Allow access to subnet as a default\0"
+ "allow all [<subnet>]\0Allow access to subnet and all children\0"
+ "deny [<subnet>]\0Deny access to subnet as a default\0"
+ "deny all [<subnet>]\0Deny access to subnet and all children\0"
+ "local stratum <stratum>\0Serve time at stratum when not synchronised\0"
+ "local off\0Don't serve time when not synchronised\0"
+ "smoothtime reset|activate\0Reset/activate time smoothing\0"
+ "smoothing\0Display current time smoothing state\0"
+ "\0\0"
+ "Monitoring access:\0\0"
+ "cmdaccheck <address>\0Check whether address is allowed\0"
+ "cmdallow [<subnet>]\0Allow access to subnet as a default\0"
+ "cmdallow all [<subnet>]\0Allow access to subnet and all children\0"
+ "cmddeny [<subnet>]\0Deny access to subnet as a default\0"
+ "cmddeny all [<subnet>]\0Deny access to subnet and all children\0"
+ "\0\0"
+ "Real-time clock:\0\0"
+ "rtcdata\0Print current RTC performance parameters\0"
+ "trimrtc\0Correct RTC relative to system clock\0"
+ "writertc\0Save RTC performance parameters to file\0"
+ "\0\0"
+ "Other daemon commands:\0\0"
+ "cyclelogs\0Close and re-open log files\0"
+ "dump\0Dump all measurements to save files\0"
+ "\0\0"
+ "Client commands:\0\0"
+ "dns -n|+n\0Disable/enable resolving IP addresses to hostnames\0"
+ "dns -4|-6|-46\0Resolve hostnames only to IPv4/IPv6/both addresses\0"
+ "timeout <milliseconds>\0Set initial response timeout\0"
+ "retries <retries>\0Set maximum number of retries\0"
+ "exit|quit\0Leave the program\0"
+ "help\0Generate this help\0"
+ "\0";
+
+ /* Indent the second column */
+ for (s = cols, line = 0; s < cols + sizeof (cols); s += len + 1, line++) {
+ len = strlen(s);
+ printf(line % 2 == 0 ? (len >= 28 ? "%s\n%28s" : "%-28s%s") : "%s%s\n",
+ s, "");
+ }
}
/* ================================================== */
static unsigned long sequence = 0;
-static unsigned long utoken = 0;
-static unsigned long token = 0;
-
static int max_retries = 2;
static int initial_timeout = 1000;
static int proto_version = PROTO_VERSION_NUMBER;
@@ -1219,19 +1280,16 @@ static int proto_version = PROTO_VERSION_NUMBER;
successful or not.*/
static int
-submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
+submit_request(CMD_Request *request, CMD_Reply *reply)
{
unsigned long tx_sequence;
- socklen_t where_from_len;
- union sockaddr_in46 where_from;
- int bad_length, bad_sender, bad_sequence, bad_header;
+ int bad_length, bad_sequence, bad_header;
int select_status;
- int recvfrom_status;
+ int recv_status;
int read_length;
int expected_length;
int command_length;
int padding_length;
- int auth_length;
struct timeval tv;
int timeout;
int n_attempts;
@@ -1243,8 +1301,8 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
tx_sequence = sequence++;
request->sequence = htonl(tx_sequence);
request->attempt = 0;
- request->utoken = htonl(utoken);
- request->token = htonl(token);
+ request->pad1 = 0;
+ request->pad2 = 0;
timeout = initial_timeout;
@@ -1256,43 +1314,22 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
padding_length = PKL_CommandPaddingLength(request);
assert(command_length > 0 && command_length > padding_length);
- /* Zero the padding to avoid sending uninitialized data. This needs to be
- done before generating auth data as it includes the padding. */
+ /* Zero the padding to avoid sending uninitialized data */
memset(((char *)request) + command_length - padding_length, 0, padding_length);
- /* Decide whether to authenticate */
- if (password) {
- if (!utoken || (request->command == htons(REQ_LOGON))) {
- /* Otherwise, the daemon won't bother authenticating our
- packet and we won't get a token back */
- request->utoken = htonl(SPECIAL_UTOKEN);
- }
- auth_length = generate_auth(request);
- } else {
- auth_length = 0;
- }
-
- /* add empty MD5 auth so older servers will not drop the request
- due to bad length */
- if (!auth_length) {
- memset(((char *)request) + command_length, 0, 16);
- auth_length = 16;
+ if (sock_fd < 0) {
+ DEBUG_LOG(LOGF_Client, "No socket to send request");
+ return 0;
}
-#if 0
- printf("Sent command length=%d bytes auth length=%d bytes\n", command_length, auth_length);
-#endif
-
- if (sendto(sock_fd, (void *) request, command_length + auth_length, 0,
- &his_addr.u, his_addr_len) < 0) {
-
-
-#if 0
- perror("Could not send packet");
-#endif
+ if (send(sock_fd, (void *)request, command_length, 0) < 0) {
+ DEBUG_LOG(LOGF_Client, "Could not send %d bytes : %s",
+ command_length, strerror(errno));
return 0;
}
+ DEBUG_LOG(LOGF_Client, "Sent %d bytes", command_length);
+
/* Increment this for next time */
++ request->attempt;
@@ -1306,12 +1343,13 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
FD_SET(sock_fd, &rdfd);
+ if (quit)
+ return 0;
+
select_status = select(sock_fd + 1, &rdfd, &wrfd, &exfd, &tv);
if (select_status < 0) {
-#if 0
- perror("Select returned negative status");
-#endif
+ DEBUG_LOG(LOGF_Client, "select failed : %s", strerror(errno));
} else if (select_status == 0) {
/* Timeout must have elapsed, try a resend? */
n_attempts ++;
@@ -1323,36 +1361,21 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
continue;
} else {
+ recv_status = recv(sock_fd, (void *)reply, sizeof(CMD_Reply), 0);
- where_from_len = sizeof(where_from);
- recvfrom_status = recvfrom(sock_fd, (void *) reply, sizeof(CMD_Reply), 0,
- &where_from.u, &where_from_len);
-
-
-#if 0
- printf("Received packet, status=%d\n", recvfrom_status);
-#endif
-
- if (recvfrom_status < 0) {
+ if (recv_status < 0) {
/* If we get connrefused here, it suggests the sendto is
- going to a dead port - but only if the daemon machine is
- running Linux (Solaris doesn't return anything) */
-
-#ifdef IP_RECVERR
- /* Fetch the message from the error queue */
- if (recv_errqueue &&
- recvfrom(sock_fd, (void *)reply, sizeof(CMD_Reply), MSG_ERRQUEUE,
- &where_from.u, &where_from_len) < 0)
- ;
-#endif
+ going to a dead port */
+ DEBUG_LOG(LOGF_Client, "Could not receive : %s", strerror(errno));
n_attempts++;
if (n_attempts > max_retries) {
return 0;
}
} else {
+ DEBUG_LOG(LOGF_Client, "Received %d bytes", recv_status);
- read_length = recvfrom_status;
+ read_length = recv_status;
if (read_length >= offsetof(CMD_Reply, data)) {
expected_length = PKL_ReplyLength(reply);
} else {
@@ -1361,17 +1384,6 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
bad_length = (read_length < expected_length ||
expected_length < offsetof(CMD_Reply, data));
- bad_sender = (where_from.u.sa_family != his_addr.u.sa_family ||
- (where_from.u.sa_family == AF_INET &&
- (where_from.in4.sin_addr.s_addr != his_addr.in4.sin_addr.s_addr ||
- where_from.in4.sin_port != his_addr.in4.sin_port)) ||
-#ifdef FEAT_IPV6
- (where_from.u.sa_family == AF_INET6 &&
- (memcmp(where_from.in6.sin6_addr.s6_addr, his_addr.in6.sin6_addr.s6_addr,
- sizeof (where_from.in6.sin6_addr.s6_addr)) != 0 ||
- where_from.in6.sin6_port != his_addr.in6.sin6_port)) ||
-#endif
- 0);
if (!bad_length) {
bad_sequence = (ntohl(reply->sequence) != tx_sequence);
@@ -1379,7 +1391,7 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
bad_sequence = 0;
}
- if (bad_length || bad_sender || bad_sequence) {
+ if (bad_length || bad_sequence) {
n_attempts++;
if (n_attempts > max_retries) {
return 0;
@@ -1417,38 +1429,10 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
#endif
/* Good packet received, print out results */
-#if 0
- printf("Reply cmd=%d reply=%d stat=%d seq=%d utok=%08lx tok=%d\n",
- ntohs(reply->command), ntohs(reply->reply),
- ntohs(reply->status),
- ntohl(reply->sequence),
- ntohl(reply->utoken),
- ntohl(reply->token));
-#endif
-
- if (password) {
- *reply_auth_ok = check_reply_auth(reply, read_length);
- } else {
- /* Assume in this case that the reply is always considered
- to be authentic */
- *reply_auth_ok = 1;
- }
-
- utoken = ntohl(reply->utoken);
-
- if (*reply_auth_ok) {
- /* If we're in authenticated mode, only acquire the utoken
- and new token values if the reply authenticated properly.
- This protects against forged packets with bogus tokens
- in. We won't accept a repeat of an old message with a
- stale token in it, due to bad_sequence processing
- earlier. */
- utoken = ntohl(reply->utoken);
- token = ntohl(reply->token);
- }
-
+ DEBUG_LOG(LOGF_Client, "Reply cmd=%d reply=%d stat=%d seq=%d",
+ ntohs(reply->command), ntohs(reply->reply), ntohs(reply->status),
+ ntohl(reply->sequence));
break;
-
}
}
} while (1);
@@ -1461,10 +1445,12 @@ submit_request(CMD_Request *request, CMD_Reply *reply, int *reply_auth_ok)
static int
request_reply(CMD_Request *request, CMD_Reply *reply, int requested_reply, int verbose)
{
- int reply_auth_ok;
int status;
- if (!submit_request(request, reply, &reply_auth_ok)) {
+ while (!submit_request(request, reply)) {
+ /* Try connecting to other addresses before giving up */
+ if (open_io())
+ continue;
printf("506 Cannot talk to daemon\n");
return 0;
}
@@ -1536,11 +1522,7 @@ request_reply(CMD_Request *request, CMD_Reply *reply, int requested_reply, int v
default:
printf("520 Got unexpected error from daemon");
}
- if (reply_auth_ok) {
- printf("\n");
- } else {
- printf(" --- Reply not authenticated\n");
- }
+ printf("\n");
}
if (status != STT_SUCCESS &&
@@ -2012,7 +1994,7 @@ process_cmd_smoothtime(CMD_Request *msg, const char *line)
} else if (!strcmp(line, "activate")) {
msg->data.smoothtime.option = htonl(REQ_SMOOTHTIME_ACTIVATE);
} else {
- fprintf(stderr, "Invalid syntax for smoothtime command\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid syntax for smoothtime command");
return 0;
}
@@ -2190,9 +2172,8 @@ process_cmd_manual_delete(CMD_Request *msg, const char *line)
int index;
if (sscanf(line, "%d", &index) != 1) {
- fprintf(stderr, "Bad syntax for manual delete command\n");
+ LOG(LOGS_ERR, LOGF_Client, "Bad syntax for manual delete command");
return 0;
-
}
msg->command = htons(REQ_MANUAL_DELETE);
@@ -2254,7 +2235,7 @@ process_cmd_makestep(CMD_Request *msg, char *line)
if (*line) {
if (sscanf(line, "%lf %d", &threshold, &limit) != 2) {
- fprintf(stderr, "Bad syntax for makestep command\n");
+ LOG(LOGS_ERR, LOGF_Client, "Bad syntax for makestep command");
return 0;
}
msg->command = htons(REQ_MODIFY_MAKESTEP);
@@ -2319,20 +2300,34 @@ process_cmd_reselect(CMD_Request *msg, char *line)
/* ================================================== */
+static void
+process_cmd_refresh(CMD_Request *msg, char *line)
+{
+ msg->command = htons(REQ_REFRESH);
+}
+
+/* ================================================== */
+
static int
process_cmd_waitsync(char *line)
{
CMD_Request request;
CMD_Reply reply;
uint32_t ref_id, a, b, c, d;
- double correction, skew_ppm, max_correction, max_skew_ppm;
+ double correction, skew_ppm, max_correction, max_skew_ppm, interval;
int ret = 0, max_tries, i;
+ struct timeval timeout;
max_tries = 0;
max_correction = 0.0;
max_skew_ppm = 0.0;
+ interval = 10.0;
- sscanf(line, "%d %lf %lf", &max_tries, &max_correction, &max_skew_ppm);
+ sscanf(line, "%d %lf %lf %lf", &max_tries, &max_correction, &max_skew_ppm, &interval);
+
+ /* Don't allow shorter interval than 0.1 seconds */
+ if (interval < 0.1)
+ interval = 0.1;
request.command = htons(REQ_TRACKING);
@@ -2358,8 +2353,10 @@ process_cmd_waitsync(char *line)
}
}
- if (!ret && (!max_tries || i < max_tries)) {
- sleep(10);
+ if (!ret && (!max_tries || i < max_tries) && !quit) {
+ UTI_DoubleToTimeval(interval, &timeout);
+ if (select(0, NULL, NULL, NULL, &timeout))
+ break;
} else {
break;
}
@@ -2383,36 +2380,9 @@ process_cmd_dns(const char *line)
} else if (!strcmp(line, "+n")) {
no_dns = 0;
} else {
- fprintf(stderr, "Unrecognized dns command\n");
- return 0;
- }
- return 1;
-}
-
-/* ================================================== */
-
-static int
-process_cmd_authhash(const char *line)
-{
- const char *hash_name;
- int new_hash_id;
-
- assert(auth_hash_id >= 0);
- hash_name = line;
-
- if (!*hash_name) {
- fprintf(stderr, "Could not parse hash name\n");
+ LOG(LOGS_ERR, LOGF_Client, "Unrecognized dns command");
return 0;
}
-
- new_hash_id = HSH_GetHashId(hash_name);
- if (new_hash_id < 0) {
- fprintf(stderr, "Unknown hash name: %s\n", hash_name);
- return 0;
- }
-
- auth_hash_id = new_hash_id;
-
return 1;
}
@@ -2425,7 +2395,7 @@ process_cmd_timeout(const char *line)
timeout = atoi(line);
if (timeout < 100) {
- fprintf(stderr, "Timeout %d is too short\n", timeout);
+ LOG(LOGS_ERR, LOGF_Client, "Timeout %d is too short", timeout);
return 0;
}
initial_timeout = timeout;
@@ -2441,7 +2411,7 @@ process_cmd_retries(const char *line)
retries = atoi(line);
if (retries < 0) {
- fprintf(stderr, "Invalid maximum number of retries\n");
+ LOG(LOGS_ERR, LOGF_Client, "Invalid maximum number of retries");
return 0;
}
max_retries = retries;
@@ -2451,7 +2421,7 @@ process_cmd_retries(const char *line)
/* ================================================== */
static int
-process_line(char *line, int *quit)
+process_line(char *line)
{
char *command;
int do_normal_submit;
@@ -2459,7 +2429,6 @@ process_line(char *line, int *quit)
CMD_Request tx_message;
CMD_Reply rx_message;
- *quit = 0;
ret = 0;
do_normal_submit = 1;
@@ -2490,9 +2459,6 @@ process_line(char *line, int *quit)
} else {
do_normal_submit = process_cmd_allow(&tx_message, line);
}
- } else if (!strcmp(command, "authhash")) {
- ret = process_cmd_authhash(line);
- do_normal_submit = 0;
} else if (!strcmp(command, "burst")) {
do_normal_submit = process_cmd_burst(&tx_message, line);
} else if (!strcmp(command, "clients")) {
@@ -2534,7 +2500,7 @@ process_line(char *line, int *quit)
process_cmd_dump(&tx_message, line);
} else if (!strcmp(command, "exit")) {
do_normal_submit = 0;
- *quit = 1;
+ quit = 1;
ret = 1;
} else if (!strcmp(command, "help")) {
do_normal_submit = 0;
@@ -2571,14 +2537,14 @@ process_line(char *line, int *quit)
do_normal_submit = process_cmd_offline(&tx_message, line);
} else if (!strcmp(command, "online")) {
do_normal_submit = process_cmd_online(&tx_message, line);
- } else if (!strcmp(command, "password")) {
- do_normal_submit = process_cmd_password(&tx_message, line);
} else if (!strcmp(command, "polltarget")) {
do_normal_submit = process_cmd_polltarget(&tx_message, line);
} else if (!strcmp(command, "quit")) {
do_normal_submit = 0;
- *quit = 1;
+ quit = 1;
ret = 1;
+ } else if (!strcmp(command, "refresh")) {
+ process_cmd_refresh(&tx_message, line);
} else if (!strcmp(command, "rekey")) {
process_cmd_rekey(&tx_message, line);
} else if (!strcmp(command, "reselect")) {
@@ -2618,8 +2584,14 @@ process_line(char *line, int *quit)
do_normal_submit = 0;
} else if (!strcmp(command, "writertc")) {
process_cmd_writertc(&tx_message, line);
+ } else if (!strcmp(command, "authhash") ||
+ !strcmp(command, "password")) {
+ /* Warn, but don't return error to not break scripts */
+ LOG(LOGS_WARN, LOGF_Client, "Authentication is no longer supported");
+ do_normal_submit = 0;
+ ret = 1;
} else {
- fprintf(stderr, "Unrecognized command\n");
+ LOG(LOGS_ERR, LOGF_Client, "Unrecognized command");
do_normal_submit = 0;
}
@@ -2634,80 +2606,9 @@ process_line(char *line, int *quit)
/* ================================================== */
static int
-authenticate_from_config(const char *filename)
-{
- CMD_Request tx_message;
- CMD_Reply rx_message;
- char line[2048], keyfile[2048], *command, *arg, *password;
- const char *hashname;
- uint32_t key_id = 0, key_id2;
- int key_id_valid = 1, ret;
- FILE *in;
-
- in = fopen(filename, "r");
- if (!in) {
- fprintf(stderr, "Could not open file %s : %s\n", filename, strerror(errno));
- return 0;
- }
-
- *keyfile = '\0';
- while (fgets(line, sizeof (line), in)) {
- CPS_NormalizeLine(line);
- command = line;
- arg = CPS_SplitWord(line);
- if (!strcasecmp(command, "keyfile")) {
- snprintf(keyfile, sizeof (keyfile), "%s", arg);
- } else if (!strcasecmp(command, "commandkey")) {
- key_id_valid = sscanf(arg, "%"SCNu32, &key_id) == 1;
- }
- }
- fclose(in);
-
- if (!*keyfile || !key_id_valid) {
- fprintf(stderr, "Could not read keyfile or commandkey in file %s\n", filename);
- return 0;
- }
-
- in = fopen(keyfile, "r");
- if (!in) {
- fprintf(stderr, "Could not open keyfile %s : %s\n", keyfile, strerror(errno));
- return 0;
- }
-
- key_id2 = key_id + 1;
- while (fgets(line, sizeof (line), in)) {
- CPS_NormalizeLine(line);
- if (!*line || !CPS_ParseKey(line, &key_id2, &hashname, &password))
- continue;
- if (key_id == key_id2)
- break;
- }
- fclose(in);
-
- if (key_id == key_id2) {
- if (process_cmd_authhash(hashname) &&
- process_cmd_password(&tx_message, password)) {
- ret = request_reply(&tx_message, &rx_message, RPY_NULL, 1);
- } else {
- ret = 0;
- }
- } else {
- fprintf(stderr, "Could not find key %"PRIu32" in keyfile %s\n", key_id, keyfile);
- ret = 0;
- }
-
- /* Erase password from stack */
- memset(line, 0, sizeof (line));
-
- return ret;
-}
-
-/* ================================================== */
-
-static int
process_args(int argc, char **argv, int multi)
{
- int total_length, i, ret, quit;
+ int total_length, i, ret;
char *line;
total_length = 0;
@@ -2715,7 +2616,7 @@ process_args(int argc, char **argv, int multi)
total_length += strlen(argv[i]) + 1;
}
- line = (char *) malloc((2 + total_length) * sizeof(char));
+ line = (char *) Malloc((2 + total_length) * sizeof(char));
for (i = 0; i < argc; i++) {
line[0] = '\0';
@@ -2729,12 +2630,12 @@ process_args(int argc, char **argv, int multi)
}
}
- ret = process_line(line, &quit);
+ ret = process_line(line);
if (!ret || quit)
break;
}
- free(line);
+ Free(line);
return ret;
}
@@ -2742,6 +2643,14 @@ process_args(int argc, char **argv, int multi)
/* ================================================== */
static void
+signal_handler(int signum)
+{
+ quit = 1;
+}
+
+/* ================================================== */
+
+static void
display_gpl(void)
{
printf("chrony version %s\n"
@@ -2759,9 +2668,8 @@ main(int argc, char **argv)
{
char *line;
const char *progname = argv[0];
- const char *hostname = NULL;
- const char *conf_file = DEFAULT_CONF_FILE;
- int quit = 0, ret = 1, multi = 0, auto_auth = 0, family = IPADDR_UNSPEC;
+ const char *hostnames = NULL;
+ int ret = 1, multi = 0, family = IPADDR_UNSPEC;
int port = DEFAULT_CANDM_PORT;
/* Parse command line options */
@@ -2769,7 +2677,7 @@ main(int argc, char **argv)
if (!strcmp(*argv, "-h")) {
++argv, --argc;
if (*argv) {
- hostname = *argv;
+ hostnames = *argv;
}
} else if (!strcmp(*argv, "-p")) {
++argv, --argc;
@@ -2778,11 +2686,11 @@ main(int argc, char **argv)
}
} else if (!strcmp(*argv, "-f")) {
++argv, --argc;
- if (*argv) {
- conf_file = *argv;
- }
+ /* For compatibility */
} else if (!strcmp(*argv, "-a")) {
- auto_auth = 1;
+ /* For compatibility */
+ } else if (!strcmp(*argv, "-d")) {
+ log_debug_enabled = 1;
} else if (!strcmp(*argv, "-m")) {
multi = 1;
} else if (!strcmp(*argv, "-n")) {
@@ -2795,8 +2703,9 @@ main(int argc, char **argv)
printf("chronyc (chrony) version %s (%s)\n", CHRONY_VERSION, CHRONYC_FEATURES);
return 0;
} else if (!strncmp(*argv, "-", 1)) {
- fprintf(stderr, "Usage: %s [-h HOST] [-p PORT] [-n] [-4|-6] [-a] [-f FILE] [-m] [COMMAND]\n",
- progname);
+ LOG(LOGS_ERR, LOGF_Client,
+ "Usage: %s [-h HOST] [-p PORT] [-n] [-d] [-4|-6] [-m] [COMMAND]",
+ progname);
return 1;
} else {
break; /* And process remainder of line as a command */
@@ -2810,38 +2719,27 @@ main(int argc, char **argv)
if (on_terminal && (argc == 0)) {
display_gpl();
}
-
- /* MD5 is the default authentication hash */
- auth_hash_id = HSH_GetHashId("MD5");
- if (auth_hash_id < 0) {
- fprintf(stderr, "Could not initialize MD5\n");
- return 1;
- }
DNS_SetAddressFamily(family);
- if (!hostname) {
- hostname = family == IPADDR_INET6 ? "::1" : "127.0.0.1";
-#ifdef FEAT_ASYNCDNS
- initial_timeout /= 10;
-#endif
+ if (!hostnames) {
+ hostnames = DEFAULT_COMMAND_SOCKET",127.0.0.1,::1";
}
- open_io(hostname, port);
+ UTI_SetQuitSignalsHandler(signal_handler);
- if (auto_auth) {
- ret = authenticate_from_config(conf_file);
- }
+ sockaddrs = get_sockaddrs(hostnames, port);
+
+ if (!open_io())
+ LOG_FATAL(LOGF_Client, "Could not open connection to daemon");
- if (!ret) {
- ;
- } else if (argc > 0) {
+ if (argc > 0) {
ret = process_args(argc, argv, multi);
} else {
do {
line = read_line();
- if (line) {
- ret = process_line(line, &quit);
+ if (line && !quit) {
+ ret = process_line(line);
}else {
/* supply the final '\n' when user exits via ^D */
if( on_terminal ) printf("\n");
@@ -2851,7 +2749,7 @@ main(int argc, char **argv)
close_io();
- free(password);
+ ARR_DestroyInstance(sockaddrs);
return !ret;
}
diff --git a/clientlog.c b/clientlog.c
index df38b38..79e65e2 100644
--- a/clientlog.c
+++ b/clientlog.c
@@ -263,25 +263,31 @@ find_subnet(Subnet *subnet, uint32_t *addr, int addr_len, int bits_consumed)
/* ================================================== */
+static Node *
+get_node(IPAddr *ip)
+{
+ uint32_t ip6[4];
+
+ switch (ip->family) {
+ case IPADDR_INET4:
+ return (Node *)find_subnet(&top_subnet4, &ip->addr.in4, 1, 0);
+ case IPADDR_INET6:
+ split_ip6(ip, ip6);
+ return (Node *)find_subnet(&top_subnet6, ip6, 4, 0);
+ default:
+ return NULL;
+ }
+}
+
+/* ================================================== */
+
void
CLG_LogNTPClientAccess (IPAddr *client, time_t now)
{
- uint32_t ip6[4];
Node *node;
if (active) {
- switch (client->family) {
- case IPADDR_INET4:
- node = (Node *) find_subnet(&top_subnet4, &client->addr.in4, 1, 0);
- break;
- case IPADDR_INET6:
- split_ip6(client, ip6);
- node = (Node *) find_subnet(&top_subnet6, ip6, 4, 0);
- break;
- default:
- assert(0);
- }
-
+ node = get_node(client);
if (node == NULL)
return;
@@ -296,22 +302,10 @@ CLG_LogNTPClientAccess (IPAddr *client, time_t now)
void
CLG_LogNTPPeerAccess(IPAddr *client, time_t now)
{
- uint32_t ip6[4];
Node *node;
if (active) {
- switch (client->family) {
- case IPADDR_INET4:
- node = (Node *) find_subnet(&top_subnet4, &client->addr.in4, 1, 0);
- break;
- case IPADDR_INET6:
- split_ip6(client, ip6);
- node = (Node *) find_subnet(&top_subnet6, ip6, 4, 0);
- break;
- default:
- assert(0);
- }
-
+ node = get_node(client);
if (node == NULL)
return;
@@ -326,22 +320,10 @@ CLG_LogNTPPeerAccess(IPAddr *client, time_t now)
void
CLG_LogCommandAccess(IPAddr *client, CLG_Command_Type type, time_t now)
{
- uint32_t ip6[4];
Node *node;
if (active) {
- switch (client->family) {
- case IPADDR_INET4:
- node = (Node *) find_subnet(&top_subnet4, &client->addr.in4, 1, 0);
- break;
- case IPADDR_INET6:
- split_ip6(client, ip6);
- node = (Node *) find_subnet(&top_subnet6, ip6, 4, 0);
- break;
- default:
- assert(0);
- }
-
+ node = get_node(client);
if (node == NULL)
return;
diff --git a/cmdmon.c b/cmdmon.c
index 5d5c559..a5b223d 100644
--- a/cmdmon.c
+++ b/cmdmon.c
@@ -53,15 +53,17 @@
/* ================================================== */
-union sockaddr_in46 {
+union sockaddr_all {
struct sockaddr_in in4;
#ifdef FEAT_IPV6
struct sockaddr_in6 in6;
#endif
- struct sockaddr u;
+ struct sockaddr_un un;
+ struct sockaddr sa;
};
/* File descriptors for command and monitoring sockets */
+static int sock_fdu;
static int sock_fd4;
#ifdef FEAT_IPV6
static int sock_fd6;
@@ -70,44 +72,6 @@ static int sock_fd6;
/* Flag indicating whether this module has been initialised or not */
static int initialised = 0;
-/* Token which is unique every time the daemon is run */
-static unsigned long utoken;
-
-/* The register of issued tokens */
-static unsigned long issued_tokens;
-
-/* The register of received tokens */
-static unsigned long returned_tokens;
-
-/* The token number corresponding to the base of the registers */
-static unsigned long token_base;
-
-/* The position of the next free token to issue in the issue register */
-static unsigned long issue_pointer;
-
-/* Type and linked list for buffering responses */
-typedef struct _ResponseCell {
- struct _ResponseCell *next;
- unsigned long tok; /* The token that the client sent in the message
- to which this was the reply */
- unsigned long next_tok; /* The next token issued to the same client.
- If we receive a request with this token,
- it implies the reply stored in this cell
- was successfully received */
- unsigned long msg_seq; /* Client's sequence number used in request
- to which this is the response. */
- unsigned long attempt; /* Attempt number that we saw in the last request
- with this sequence number (prevents attacker
- firing the same request at us to make us
- keep generating the same reply). */
- struct timeval ts; /* Time we saved the reply - allows purging based
- on staleness. */
- CMD_Reply rpy;
-} ResponseCell;
-
-static ResponseCell kept_replies;
-static ResponseCell *free_replies;
-
/* ================================================== */
/* Array of permission levels for command types */
@@ -165,6 +129,7 @@ static const char permissions[] = {
PERMIT_AUTH, /* MODIFY_MAKESTEP */
PERMIT_OPEN, /* SMOOTHING */
PERMIT_AUTH, /* SMOOTHTIME */
+ PERMIT_AUTH, /* REFRESH */
};
/* ================================================== */
@@ -184,43 +149,45 @@ prepare_socket(int family, int port_number)
{
int sock_fd;
socklen_t my_addr_len;
- union sockaddr_in46 my_addr;
+ union sockaddr_all my_addr;
IPAddr bind_address;
int on_off = 1;
sock_fd = socket(family, SOCK_DGRAM, 0);
if (sock_fd < 0) {
LOG(LOGS_ERR, LOGF_CmdMon, "Could not open %s command socket : %s",
- family == AF_INET ? "IPv4" : "IPv6", strerror(errno));
+ UTI_SockaddrFamilyToString(family), strerror(errno));
return -1;
}
/* Close on exec */
UTI_FdSetCloexec(sock_fd);
- /* Allow reuse of port number */
- if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on_off, sizeof(on_off)) < 0) {
- LOG(LOGS_ERR, LOGF_CmdMon, "Could not set reuseaddr socket options");
- /* Don't quit - we might survive anyway */
- }
+ if (family != AF_UNIX) {
+ /* Allow reuse of port number */
+ if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on_off, sizeof(on_off)) < 0) {
+ LOG(LOGS_ERR, LOGF_CmdMon, "Could not set reuseaddr socket options");
+ /* Don't quit - we might survive anyway */
+ }
#ifdef IP_FREEBIND
- /* Allow binding to address that doesn't exist yet */
- if (setsockopt(sock_fd, IPPROTO_IP, IP_FREEBIND, (char *)&on_off, sizeof(on_off)) < 0) {
- LOG(LOGS_ERR, LOGF_CmdMon, "Could not set free bind socket option");
- }
+ /* Allow binding to address that doesn't exist yet */
+ if (setsockopt(sock_fd, IPPROTO_IP, IP_FREEBIND, (char *)&on_off, sizeof(on_off)) < 0) {
+ LOG(LOGS_ERR, LOGF_CmdMon, "Could not set free bind socket option");
+ }
#endif
#ifdef FEAT_IPV6
- if (family == AF_INET6) {
+ if (family == AF_INET6) {
#ifdef IPV6_V6ONLY
- /* Receive IPv6 packets only */
- if (setsockopt(sock_fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&on_off, sizeof(on_off)) < 0) {
- LOG(LOGS_ERR, LOGF_CmdMon, "Could not request IPV6_V6ONLY socket option");
+ /* Receive IPv6 packets only */
+ if (setsockopt(sock_fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&on_off, sizeof(on_off)) < 0) {
+ LOG(LOGS_ERR, LOGF_CmdMon, "Could not request IPV6_V6ONLY socket option");
+ }
+#endif
}
#endif
}
-#endif
memset(&my_addr, 0, sizeof (my_addr));
@@ -252,13 +219,21 @@ prepare_socket(int family, int port_number)
my_addr.in6.sin6_addr = in6addr_loopback;
break;
#endif
+ case AF_UNIX:
+ my_addr_len = sizeof (my_addr.un);
+ my_addr.un.sun_family = family;
+ if (snprintf(my_addr.un.sun_path, sizeof (my_addr.un.sun_path), "%s",
+ CNF_GetBindCommandPath()) >= sizeof (my_addr.un.sun_path))
+ LOG_FATAL(LOGF_CmdMon, "Unix socket path too long");
+ unlink(my_addr.un.sun_path);
+ break;
default:
assert(0);
}
- if (bind(sock_fd, &my_addr.u, my_addr_len) < 0) {
+ if (bind(sock_fd, &my_addr.sa, my_addr_len) < 0) {
LOG(LOGS_ERR, LOGF_CmdMon, "Could not bind %s command socket : %s",
- family == AF_INET ? "IPv4" : "IPv6", strerror(errno));
+ UTI_SockaddrFamilyToString(family), strerror(errno));
close(sock_fd);
return -1;
}
@@ -293,14 +268,7 @@ CAM_Initialise(int family)
assert(command_length == 0 || command_length >= offsetof(CMD_Reply, data));
}
- utoken = (unsigned long) time(NULL);
-
- issued_tokens = returned_tokens = issue_pointer = 0;
- token_base = 1; /* zero is the value used when the previous command was
- unauthenticated */
-
- free_replies = NULL;
- kept_replies.next = NULL;
+ sock_fdu = -1;
port_number = CNF_GetCommandPort();
@@ -332,6 +300,12 @@ CAM_Initialise(int family)
void
CAM_Finalise(void)
{
+ if (sock_fdu >= 0) {
+ SCH_RemoveInputFileHandler(sock_fdu);
+ close(sock_fdu);
+ unlink(CNF_GetBindCommandPath());
+ }
+ sock_fdu = -1;
if (sock_fd4 >= 0) {
SCH_RemoveInputFileHandler(sock_fd4);
close(sock_fd4);
@@ -351,343 +325,27 @@ CAM_Finalise(void)
}
/* ================================================== */
-/* This function checks whether the authenticator field of the packet
- checks correctly against what we would compute locally given the
- rest of the packet */
-
-static int
-check_rx_packet_auth(CMD_Request *packet, int packet_len)
-{
- int pkt_len, auth_len;
-
- pkt_len = PKL_CommandLength(packet);
- auth_len = packet_len - pkt_len;
-
- return KEY_CheckAuth(KEY_GetCommandKey(), (unsigned char *)packet,
- pkt_len, ((unsigned char *)packet) + pkt_len, auth_len);
-}
-
-/* ================================================== */
-
-static int
-generate_tx_packet_auth(CMD_Reply *packet)
-{
- int pkt_len;
-
- pkt_len = PKL_ReplyLength(packet);
-
- return KEY_GenerateAuth(KEY_GetCommandKey(), (unsigned char *)packet,
- pkt_len, ((unsigned char *)packet) + pkt_len, sizeof (packet->auth));
-}
-
-/* ================================================== */
-static void
-shift_tokens(void)
-{
- do {
- issued_tokens >>= 1;
- returned_tokens >>= 1;
- token_base++;
- issue_pointer--;
- } while ((issued_tokens & 1) && (returned_tokens & 1));
-}
-
-/* ================================================== */
-
-static unsigned long
-get_token(void)
-{
- unsigned long result;
-
- if (issue_pointer == 32) {
- /* The lowest number open token has not been returned - bad luck
- to that command client */
- shift_tokens();
- }
-
- result = token_base + issue_pointer;
- issued_tokens |= (1UL << issue_pointer);
- issue_pointer++;
-
- return result;
-}
-
-/* ================================================== */
-
-static int
-check_token(unsigned long token)
-{
- int result;
- unsigned long pos;
-
- if (token < token_base) {
- /* Token too old */
- result = 0;
- } else {
- pos = token - token_base;
- if (pos >= issue_pointer) {
- /* Token hasn't been issued yet */
- result = 0;
- } else {
- if (returned_tokens & (1UL << pos)) {
- /* Token has already been returned */
- result = 0;
- } else {
- /* Token is OK */
- result = 1;
- returned_tokens |= (1UL << pos);
- if (pos == 0) {
- shift_tokens();
- }
- }
- }
- }
-
- return result;
-
-}
-
-/* ================================================== */
-
-#define TS_MARGIN 20
-
-/* ================================================== */
-
-typedef struct _TimestampCell {
- struct _TimestampCell *next;
- struct timeval ts;
-} TimestampCell;
-
-static struct _TimestampCell seen_ts_list={NULL};
-static struct _TimestampCell *free_ts_list=NULL;
-
-#define EXTEND_QUANTUM 32
-
-/* ================================================== */
-
-static TimestampCell *
-allocate_ts_cell(void)
-{
- TimestampCell *result;
- int i;
- if (free_ts_list == NULL) {
- free_ts_list = MallocArray(TimestampCell, EXTEND_QUANTUM);
- for (i=0; i<EXTEND_QUANTUM-1; i++) {
- free_ts_list[i].next = free_ts_list + i + 1;
- }
- free_ts_list[EXTEND_QUANTUM - 1].next = NULL;
- }
-
- result = free_ts_list;
- free_ts_list = free_ts_list->next;
- return result;
-}
-
-/* ================================================== */
-
-static void
-release_ts_cell(TimestampCell *node)
-{
- node->next = free_ts_list;
- free_ts_list = node;
-}
-
-/* ================================================== */
-/* Return 1 if not found, 0 if found (i.e. not unique). Prune out any
- stale entries. */
-
-static int
-check_unique_ts(struct timeval *ts, struct timeval *now)
-{
- TimestampCell *last_valid, *cell, *next;
- int ok;
-
- ok = 1;
- last_valid = &(seen_ts_list);
- cell = last_valid->next;
-
- while (cell) {
- next = cell->next;
- /* Check if stale */
- if ((now->tv_sec - cell->ts.tv_sec) > TS_MARGIN) {
- release_ts_cell(cell);
- last_valid->next = next;
- } else {
- /* Timestamp in cell is still within window */
- last_valid->next = cell;
- last_valid = cell;
- if ((cell->ts.tv_sec == ts->tv_sec) && (cell->ts.tv_usec == ts->tv_usec)) {
- ok = 0;
- }
- }
- cell = next;
- }
-
- if (ok) {
- /* Need to add this timestamp to the list */
- cell = allocate_ts_cell();
- last_valid->next = cell;
- cell->next = NULL;
- cell->ts = *ts;
- }
-
- return ok;
-}
-
-/* ================================================== */
-
-static int
-ts_is_unique_and_not_stale(struct timeval *ts, struct timeval *now)
-{
- int within_margin=0;
- int is_unique=0;
- long diff;
-
- diff = now->tv_sec - ts->tv_sec;
- if ((diff < TS_MARGIN) && (diff > -TS_MARGIN)) {
- within_margin = 1;
- } else {
- within_margin = 0;
- }
- is_unique = check_unique_ts(ts, now);
-
- return within_margin && is_unique;
-}
-
-/* ================================================== */
-
-#define REPLY_EXTEND_QUANTUM 8
-
-static void
-get_more_replies(void)
-{
- ResponseCell *new_replies;
- int i;
-
- if (!free_replies) {
- new_replies = MallocArray(ResponseCell, REPLY_EXTEND_QUANTUM);
- for (i=1; i<REPLY_EXTEND_QUANTUM; i++) {
- new_replies[i-1].next = new_replies + i;
- }
- new_replies[REPLY_EXTEND_QUANTUM - 1].next = NULL;
- free_replies = new_replies;
- }
-}
-
-/* ================================================== */
-
-static ResponseCell *
-get_reply_slot(void)
-{
- ResponseCell *result;
- if (!free_replies) {
- get_more_replies();
- }
- result = free_replies;
- free_replies = result->next;
- return result;
-}
-
-/* ================================================== */
-
-static void
-free_reply_slot(ResponseCell *cell)
-{
- cell->next = free_replies;
- free_replies = cell;
-}
-
-/* ================================================== */
-
-static void
-save_reply(CMD_Reply *msg,
- unsigned long tok_reply_to,
- unsigned long new_tok_issued,
- unsigned long client_msg_seq,
- unsigned short attempt,
- struct timeval *now)
-{
- ResponseCell *cell;
-
- cell = get_reply_slot();
-
- cell->ts = *now;
- memcpy(&cell->rpy, msg, sizeof(CMD_Reply));
- cell->tok = tok_reply_to;
- cell->next_tok = new_tok_issued;
- cell->msg_seq = client_msg_seq;
- cell->attempt = (unsigned long) attempt;
-
- cell->next = kept_replies.next;
- kept_replies.next = cell;
-
-}
-
-/* ================================================== */
-
-static CMD_Reply *
-lookup_reply(unsigned long prev_msg_token, unsigned long client_msg_seq, unsigned short attempt)
-{
- ResponseCell *ptr;
-
- ptr = kept_replies.next;
- while (ptr) {
- if ((ptr->tok == prev_msg_token) &&
- (ptr->msg_seq == client_msg_seq) &&
- ((unsigned long) attempt > ptr->attempt)) {
-
- /* Set the attempt field to remember the highest number we have
- had so far */
- ptr->attempt = (unsigned long) attempt;
- return &ptr->rpy;
- }
- ptr = ptr->next;
- }
-
- return NULL;
-}
-
-
-/* ================================================== */
-
-#define REPLY_MAXAGE 300
-
-static void
-token_acknowledged(unsigned long token, struct timeval *now)
+void
+CAM_OpenUnixSocket(void)
{
- ResponseCell *last_valid, *cell, *next;
-
- last_valid = &kept_replies;
- cell = kept_replies.next;
-
- while(cell) {
- next = cell->next;
-
- /* Discard if it's the one or if the reply is stale */
- if ((cell->next_tok == token) ||
- ((now->tv_sec - cell->ts.tv_sec) > REPLY_MAXAGE)) {
- free_reply_slot(cell);
- last_valid->next = next;
- } else {
- last_valid->next = cell;
- last_valid = cell;
- }
- cell = next;
- }
+ /* This is separated from CAM_Initialise() as it needs to be called when
+ the process has already dropped the root privileges */
+ if (CNF_GetBindCommandPath()[0])
+ sock_fdu = prepare_socket(AF_UNIX, 0);
}
/* ================================================== */
static void
-transmit_reply(CMD_Reply *msg, union sockaddr_in46 *where_to, int auth_len)
+transmit_reply(CMD_Reply *msg, union sockaddr_all *where_to)
{
int status;
int tx_message_length;
int sock_fd;
socklen_t addrlen;
-
- switch (where_to->u.sa_family) {
+
+ switch (where_to->sa.sa_family) {
case AF_INET:
sock_fd = sock_fd4;
addrlen = sizeof (where_to->in4);
@@ -698,21 +356,26 @@ transmit_reply(CMD_Reply *msg, union sockaddr_in46 *where_to, int auth_len)
addrlen = sizeof (where_to->in6);
break;
#endif
+ case AF_UNIX:
+ sock_fd = sock_fdu;
+ addrlen = sizeof (where_to->un);
+ break;
default:
assert(0);
}
- tx_message_length = PKL_ReplyLength(msg) + auth_len;
+ tx_message_length = PKL_ReplyLength(msg);
status = sendto(sock_fd, (void *) msg, tx_message_length, 0,
- &where_to->u, addrlen);
+ &where_to->sa, addrlen);
if (status < 0) {
- unsigned short port;
- IPAddr ip;
-
- UTI_SockaddrToIPAndPort(&where_to->u, &ip, &port);
- DEBUG_LOG(LOGF_CmdMon, "Could not send response to %s:%hu", UTI_IPToString(&ip), port);
+ DEBUG_LOG(LOGF_CmdMon, "Could not send to %s fd %d : %s",
+ UTI_SockaddrToString(&where_to->sa), sock_fd, strerror(errno));
+ return;
}
+
+ DEBUG_LOG(LOGF_CmdMon, "Sent %d bytes to %s fd %d", status,
+ UTI_SockaddrToString(&where_to->sa), sock_fd);
}
/* ================================================== */
@@ -1479,6 +1142,14 @@ handle_reselect(CMD_Request *rx_message, CMD_Reply *tx_message)
}
/* ================================================== */
+
+static void
+handle_refresh(CMD_Request *rx_message, CMD_Reply *tx_message)
+{
+ NSR_RefreshAddresses();
+}
+
+/* ================================================== */
/* Read a packet and process it */
static void
@@ -1489,26 +1160,16 @@ read_from_cmd_socket(void *anything)
int expected_length; /* Expected length of packet without auth data */
unsigned long flags;
CMD_Request rx_message;
- CMD_Reply tx_message, *prev_tx_message;
- int rx_message_length, tx_message_length;
+ CMD_Reply tx_message;
+ int rx_message_length;
int sock_fd;
- union sockaddr_in46 where_from;
+ union sockaddr_all where_from;
socklen_t from_length;
IPAddr remote_ip;
unsigned short remote_port;
- int auth_length;
- int auth_ok;
- int utoken_ok, token_ok;
- int issue_token;
- int valid_ts;
- int authenticated;
int localhost;
int allowed;
unsigned short rx_command;
- unsigned long rx_message_token;
- unsigned long tx_message_token;
- unsigned long rx_message_seq;
- unsigned long rx_attempt;
struct timeval now;
struct timeval cooked_now;
@@ -1518,7 +1179,7 @@ read_from_cmd_socket(void *anything)
sock_fd = (long)anything;
status = recvfrom(sock_fd, (char *)&rx_message, rx_message_length, flags,
- &where_from.u, &from_length);
+ &where_from.sa, &from_length);
if (status < 0) {
LOG(LOGS_WARN, LOGF_CmdMon, "Error [%s] reading from control socket %d",
@@ -1526,31 +1187,46 @@ read_from_cmd_socket(void *anything)
return;
}
- if (from_length > sizeof (where_from))
- LOG_FATAL(LOGF_CmdMon, "Truncated source address");
+ if (from_length > sizeof (where_from) ||
+ from_length <= sizeof (where_from.sa.sa_family)) {
+ DEBUG_LOG(LOGF_CmdMon, "Read command packet without source address");
+ return;
+ }
read_length = status;
/* Get current time cheaply */
SCH_GetLastEventTime(&cooked_now, NULL, &now);
- UTI_SockaddrToIPAndPort(&where_from.u, &remote_ip, &remote_port);
+ UTI_SockaddrToIPAndPort(&where_from.sa, &remote_ip, &remote_port);
- /* Check if it's a loopback address (127.0.0.1 or ::1) */
+ /* Check if it's from localhost (127.0.0.1, ::1, or Unix domain) */
switch (remote_ip.family) {
case IPADDR_INET4:
+ assert(sock_fd == sock_fd4);
localhost = remote_ip.addr.in4 == INADDR_LOOPBACK;
break;
#ifdef FEAT_IPV6
case IPADDR_INET6:
+ assert(sock_fd == sock_fd6);
localhost = !memcmp(remote_ip.addr.in6, &in6addr_loopback,
sizeof (in6addr_loopback));
break;
#endif
+ case IPADDR_UNSPEC:
+ /* This should be the Unix domain socket */
+ if (where_from.sa.sa_family != AF_UNIX)
+ return;
+ assert(sock_fd == sock_fdu);
+ localhost = 1;
+ break;
default:
assert(0);
}
+ DEBUG_LOG(LOGF_CmdMon, "Received %d bytes from %s fd %d",
+ status, UTI_SockaddrToString(&where_from.sa), sock_fd);
+
if (!(localhost || ADF_IsAllowed(access_auth_table, &remote_ip))) {
/* The client is not allowed access, so don't waste any more time
on him. Note that localhost is always allowed access
@@ -1585,204 +1261,79 @@ read_from_cmd_socket(void *anything)
tx_message.res1 = 0;
tx_message.res2 = 0;
tx_message.command = rx_message.command;
- tx_message.sequence = rx_message.sequence;
tx_message.reply = htons(RPY_NULL);
tx_message.status = htons(STT_SUCCESS);
tx_message.pad1 = 0;
tx_message.pad2 = 0;
tx_message.pad3 = 0;
- tx_message.utoken = htonl(utoken);
- /* Set this to a default (invalid) value. This protects against the
- token field being set to an arbitrary value if we reject the
- message, e.g. due to the host failing the access check. */
- tx_message.token = htonl(0xffffffffUL);
- memset(&tx_message.auth, 0, sizeof(tx_message.auth));
+ tx_message.sequence = rx_message.sequence;
+ tx_message.pad4 = 0;
+ tx_message.pad5 = 0;
if (rx_message.version != PROTO_VERSION_NUMBER) {
- DEBUG_LOG(LOGF_CmdMon, "Read command packet with protocol version %d (expected %d) from %s:%hu", rx_message.version, PROTO_VERSION_NUMBER, UTI_IPToString(&remote_ip), remote_port);
+ DEBUG_LOG(LOGF_CmdMon, "Read command packet with protocol version %d (expected %d) from %s",
+ rx_message.version, PROTO_VERSION_NUMBER, UTI_SockaddrToString(&where_from.sa));
CLG_LogCommandAccess(&remote_ip, CLG_CMD_BAD_PKT, cooked_now.tv_sec);
if (rx_message.version >= PROTO_VERSION_MISMATCH_COMPAT_SERVER) {
tx_message.status = htons(STT_BADPKTVERSION);
- transmit_reply(&tx_message, &where_from, 0);
+ transmit_reply(&tx_message, &where_from);
}
return;
}
if (rx_command >= N_REQUEST_TYPES) {
- DEBUG_LOG(LOGF_CmdMon, "Read command packet with invalid command %d from %s:%hu", rx_command, UTI_IPToString(&remote_ip), remote_port);
+ DEBUG_LOG(LOGF_CmdMon, "Read command packet with invalid command %d from %s",
+ rx_command, UTI_SockaddrToString(&where_from.sa));
CLG_LogCommandAccess(&remote_ip, CLG_CMD_BAD_PKT, cooked_now.tv_sec);
tx_message.status = htons(STT_INVALID);
- transmit_reply(&tx_message, &where_from, 0);
+ transmit_reply(&tx_message, &where_from);
return;
}
if (read_length < expected_length) {
- DEBUG_LOG(LOGF_CmdMon, "Read incorrectly sized command packet from %s:%hu", UTI_IPToString(&remote_ip), remote_port);
+ DEBUG_LOG(LOGF_CmdMon, "Read incorrectly sized command packet from %s",
+ UTI_SockaddrToString(&where_from.sa));
CLG_LogCommandAccess(&remote_ip, CLG_CMD_BAD_PKT, cooked_now.tv_sec);
tx_message.status = htons(STT_BADPKTLENGTH);
- transmit_reply(&tx_message, &where_from, 0);
+ transmit_reply(&tx_message, &where_from);
return;
}
/* OK, we have a valid message. Now dispatch on message type and process it. */
- /* Do authentication stuff and command tokens here. Well-behaved
- clients will set their utokens to 0 to save us wasting our time
- if the packet is unauthenticatable. */
- if (rx_message.utoken != 0) {
- auth_ok = check_rx_packet_auth(&rx_message, read_length);
- } else {
- auth_ok = 0;
- }
-
- /* All this malarky is to protect the system against various forms
- of attack.
-
- Simple packet forgeries are blocked by requiring the packet to
- authenticate properly with MD5 or other crypto hash. (The
- assumption is that the command key is in a read-only keys file
- read by the daemon, and is known only to administrators.)
-
- Replay attacks are prevented by 2 fields in the packet. The
- 'token' field is where the client plays back to us a token that
- he was issued in an earlier reply. Each time we reply to a
- suitable packet, we issue a new token. The 'utoken' field is set
- to a new (hopefully increasing) value each time the daemon is
- run. This prevents packets from a previous incarnation being
- played back at us when the same point in the 'token' sequence
- comes up. (The token mechanism also prevents a non-idempotent
- command from being executed twice from the same client, if the
- client fails to receive our reply the first time and tries a
- resend.)
-
- The problem is how a client should get its first token. Our
- token handling only remembers a finite number of issued tokens
- (actually 32) - if a client replies with a (legitimate) token
- older than that, it will be treated as though a duplicate token
- has been supplied. If a simple token-request protocol were used,
- the whole thing would be vulnerable to a denial of service
- attack, where an attacker just replays valid token-request
- packets at us, causing us to keep issuing new tokens,
- invalidating all the ones we have given out to true clients
- already.
-
- To protect against this, the token-request (REQ_LOGON) packet
- includes a timestamp field. To issue a token, we require that
- this field is different from any we have processed before. To
- bound our storage, we require that the timestamp is within a
- certain period of our current time. For clients running on the
- same host this will be easily satisfied.
-
- */
-
- utoken_ok = (ntohl(rx_message.utoken) == utoken);
-
- /* Avoid binning a valid user's token if we merely get a forged
- packet */
- rx_message_token = ntohl(rx_message.token);
- rx_message_seq = ntohl(rx_message.sequence);
- rx_attempt = ntohs(rx_message.attempt);
-
- if (auth_ok && utoken_ok) {
- token_ok = check_token(rx_message_token);
- } else {
- token_ok = 0;
- }
-
- if (auth_ok && utoken_ok && !token_ok) {
- /* This might be a resent message, due to the client not getting
- our reply to the first attempt. See if we can find the message. */
- prev_tx_message = lookup_reply(rx_message_token, rx_message_seq, rx_attempt);
- if (prev_tx_message) {
- /* Just send this message again */
- tx_message_length = PKL_ReplyLength(prev_tx_message);
- status = sendto(sock_fd, (void *) prev_tx_message, tx_message_length, 0,
- &where_from.u, from_length);
- if (status < 0) {
- DEBUG_LOG(LOGF_CmdMon, "Could not send response to %s:%hu", UTI_IPToString(&remote_ip), remote_port);
- }
- return;
- }
- /* Otherwise, just fall through into normal processing */
-
- }
-
- if (auth_ok && utoken_ok && token_ok) {
- /* See whether we can discard the previous reply from storage */
- token_acknowledged(rx_message_token, &now);
- }
-
- valid_ts = 0;
- issue_token = 0;
-
- if (auth_ok) {
- if (utoken_ok && token_ok) {
- issue_token = 1;
- } else if (rx_command == REQ_LOGON &&
- ntohl(rx_message.utoken) == SPECIAL_UTOKEN) {
- struct timeval ts;
-
- UTI_TimevalNetworkToHost(&rx_message.data.logon.ts, &ts);
- valid_ts = ts_is_unique_and_not_stale(&ts, &now);
-
- if (valid_ts) {
- issue_token = 1;
- }
- }
- }
-
- authenticated = auth_ok & utoken_ok & token_ok;
-
- if (authenticated) {
- CLG_LogCommandAccess(&remote_ip, CLG_CMD_AUTH, cooked_now.tv_sec);
- } else {
- CLG_LogCommandAccess(&remote_ip, CLG_CMD_NORMAL, cooked_now.tv_sec);
- }
-
- if (issue_token) {
- /* Only command clients where the user has apparently 'logged on'
- get a token to allow them to emit an authenticated command next
- time */
- tx_message_token = get_token();
- } else {
- tx_message_token = 0xffffffffUL;
- }
-
- tx_message.token = htonl(tx_message_token);
-
+ CLG_LogCommandAccess(&remote_ip, CLG_CMD_NORMAL, cooked_now.tv_sec);
if (rx_command >= N_REQUEST_TYPES) {
/* This should be already handled */
assert(0);
} else {
- /* Check level of authority required to issue the command */
- switch(permissions[rx_command]) {
- case PERMIT_AUTH:
- if (authenticated) {
- allowed = 1;
- } else {
+ /* Check level of authority required to issue the command. All commands
+ from the Unix domain socket (which is accessible only by the root and
+ chrony user/group) are allowed. */
+ if (where_from.sa.sa_family == AF_UNIX) {
+ assert(sock_fd == sock_fdu);
+ allowed = 1;
+ } else {
+ switch (permissions[rx_command]) {
+ case PERMIT_AUTH:
allowed = 0;
- }
- break;
- case PERMIT_LOCAL:
- if (authenticated || localhost) {
+ break;
+ case PERMIT_LOCAL:
+ allowed = localhost;
+ break;
+ case PERMIT_OPEN:
allowed = 1;
- } else {
+ break;
+ default:
+ assert(0);
allowed = 0;
- }
- break;
- case PERMIT_OPEN:
- allowed = 1;
- break;
- default:
- assert(0);
- allowed = 0;
+ }
}
if (allowed) {
@@ -1836,25 +1387,8 @@ read_from_cmd_socket(void *anything)
break;
case REQ_LOGON:
- /* If the log-on fails, record the reason why */
- if (!issue_token) {
- DEBUG_LOG(LOGF_CmdMon,
- "Bad command logon from %s port %d (auth_ok=%d valid_ts=%d)",
- UTI_IPToString(&remote_ip),
- remote_port,
- auth_ok, valid_ts);
- }
-
- if (issue_token == 1) {
- tx_message.status = htons(STT_SUCCESS);
- } else if (!auth_ok) {
- tx_message.status = htons(STT_UNAUTH);
- } else if (!valid_ts) {
- tx_message.status = htons(STT_INVALIDTS);
- } else {
- tx_message.status = htons(STT_FAILED);
- }
-
+ /* Authentication is no longer supported, log-on always fails */
+ tx_message.status = htons(STT_FAILED);
break;
case REQ_SETTIME:
@@ -2009,6 +1543,10 @@ read_from_cmd_socket(void *anything)
handle_modify_polltarget(&rx_message, &tx_message);
break;
+ case REQ_REFRESH:
+ handle_refresh(&rx_message, &tx_message);
+ break;
+
default:
assert(0);
break;
@@ -2018,21 +1556,6 @@ read_from_cmd_socket(void *anything)
}
}
- if (auth_ok) {
- auth_length = generate_tx_packet_auth(&tx_message);
- } else {
- auth_length = 0;
- }
-
- if (token_ok) {
- save_reply(&tx_message,
- rx_message_token,
- tx_message_token,
- rx_message_seq,
- rx_attempt,
- &now);
- }
-
/* Transmit the response */
{
/* Include a simple way to lose one message in three to test resend */
@@ -2040,7 +1563,7 @@ read_from_cmd_socket(void *anything)
static int do_it=1;
if (do_it) {
- transmit_reply(&tx_message, &where_from, auth_length);
+ transmit_reply(&tx_message, &where_from);
}
#if 0
diff --git a/cmdmon.h b/cmdmon.h
index ac337e7..5b717d2 100644
--- a/cmdmon.h
+++ b/cmdmon.h
@@ -33,6 +33,7 @@ extern void CAM_Initialise(int family);
extern void CAM_Finalise(void);
+extern void CAM_OpenUnixSocket(void);
extern int CAM_AddAccessRestriction(IPAddr *ip_addr, int subnet_bits, int allow, int all);
extern int CAM_CheckAccessRestriction(IPAddr *ip_addr);
diff --git a/conf.c b/conf.c
index a83d937..5cec397 100644
--- a/conf.c
+++ b/conf.c
@@ -47,7 +47,6 @@
static int parse_string(char *line, char **result);
static int parse_int(char *line, int *result);
-static int parse_uint32(char *, uint32_t *result);
static int parse_double(char *line, double *result);
static int parse_null(char *line);
@@ -80,19 +79,18 @@ static void parse_tempcomp(char *);
/* Configuration variables */
static int restarted = 0;
-static int generate_command_key = 0;
static char *rtc_device;
static int acquisition_port = -1;
static int ntp_port = 123;
static char *keys_file = NULL;
static char *drift_file = NULL;
static char *rtc_file = NULL;
-static uint32_t command_key_id;
static double max_update_skew = 1000.0;
static double correction_time_ratio = 3.0;
static double max_clock_error = 1.0; /* in ppm */
static double max_slew_rate = 1e6 / 12.0; /* in ppm */
+static double max_distance = 3.0;
static double reselect_distance = 1e-4;
static double stratum_weight = 1e-3;
static double combine_limit = 3.0;
@@ -126,7 +124,7 @@ static int enable_manual=0;
static int rtc_on_utc = 0;
/* Filename used to read the hwclock(8) LOCAL/UTC setting */
-static char *hwclock_file = NULL;
+static char *hwclock_file;
/* Flag set if the RTC should be automatically synchronised by kernel */
static int rtc_sync = 0;
@@ -182,6 +180,9 @@ static IPAddr bind_acq_address4, bind_acq_address6;
the loopback address will be used */
static IPAddr bind_cmd_address4, bind_cmd_address6;
+/* Path to the Unix domain command socket. */
+static char *bind_cmd_path;
+
/* Filename to use for storing pid of running chronyd, to prevent multiple
* chronyds being started. */
static char *pidfile;
@@ -320,8 +321,10 @@ CNF_Initialise(int r)
dumpdir = Strdup(".");
logdir = Strdup(".");
+ bind_cmd_path = Strdup(DEFAULT_COMMAND_SOCKET);
pidfile = Strdup("/var/run/chronyd.pid");
rtc_device = Strdup("/dev/rtc");
+ hwclock_file = Strdup(DEFAULT_HWCLOCK_FILE);
user = Strdup(DEFAULT_USER);
}
@@ -349,6 +352,7 @@ CNF_Finalise(void)
Free(keys_file);
Free(leapsec_tz);
Free(logdir);
+ Free(bind_cmd_path);
Free(pidfile);
Free(rtc_device);
Free(rtc_file);
@@ -370,10 +374,13 @@ CNF_ReadFile(const char *filename)
in = fopen(filename, "r");
if (!in) {
- LOG_FATAL(LOGF_Configure, "Could not open configuration file %s", filename);
+ LOG_FATAL(LOGF_Configure, "Could not open configuration file %s : %s",
+ filename, strerror(errno));
return;
}
+ DEBUG_LOG(LOGF_Configure, "Reading %s", filename);
+
for (i = 1; fgets(line, sizeof(line), in); i++) {
CNF_ParseLine(filename, i, line);
}
@@ -426,8 +433,6 @@ CNF_ParseLine(const char *filename, int number, char *line)
parse_int(p, &cmd_port);
} else if (!strcasecmp(command, "combinelimit")) {
parse_double(p, &combine_limit);
- } else if (!strcasecmp(command, "commandkey")) {
- parse_uint32(p, &command_key_id);
} else if (!strcasecmp(command, "corrtimeratio")) {
parse_double(p, &correction_time_ratio);
} else if (!strcasecmp(command, "deny")) {
@@ -440,8 +445,6 @@ CNF_ParseLine(const char *filename, int number, char *line)
do_dump_on_exit = parse_null(p);
} else if (!strcasecmp(command, "fallbackdrift")) {
parse_fallbackdrift(p);
- } else if (!strcasecmp(command, "generatecommandkey")) {
- generate_command_key = parse_null(p);
} else if (!strcasecmp(command, "hwclockfile")) {
parse_string(p, &hwclock_file);
} else if (!strcasecmp(command, "include")) {
@@ -454,10 +457,6 @@ CNF_ParseLine(const char *filename, int number, char *line)
parse_leapsecmode(p);
} else if (!strcasecmp(command, "leapsectz")) {
parse_string(p, &leapsec_tz);
- } else if (!strcasecmp(command, "linux_freq_scale")) {
- LOG(LOGS_WARN, LOGF_Configure, "%s directive is no longer supported", command);
- } else if (!strcasecmp(command, "linux_hz")) {
- LOG(LOGS_WARN, LOGF_Configure, "%s directive is no longer supported", command);
} else if (!strcasecmp(command, "local")) {
parse_local(p);
} else if (!strcasecmp(command, "lock_all")) {
@@ -480,6 +479,8 @@ CNF_ParseLine(const char *filename, int number, char *line)
parse_maxchange(p);
} else if (!strcasecmp(command, "maxclockerror")) {
parse_double(p, &max_clock_error);
+ } else if (!strcasecmp(command, "maxdistance")) {
+ parse_double(p, &max_distance);
} else if (!strcasecmp(command, "maxsamples")) {
parse_int(p, &max_samples);
} else if (!strcasecmp(command, "maxslewrate")) {
@@ -526,6 +527,11 @@ CNF_ParseLine(const char *filename, int number, char *line)
parse_tempcomp(p);
} else if (!strcasecmp(command, "user")) {
parse_string(p, &user);
+ } else if (!strcasecmp(command, "commandkey") ||
+ !strcasecmp(command, "generatecommandkey") ||
+ !strcasecmp(command, "linux_freq_scale") ||
+ !strcasecmp(command, "linux_hz")) {
+ LOG(LOGS_WARN, LOGF_Configure, "%s directive is no longer supported", command);
} else {
other_parse_error("Invalid command");
}
@@ -558,19 +564,6 @@ parse_int(char *line, int *result)
/* ================================================== */
static int
-parse_uint32(char *line, uint32_t *result)
-{
- check_number_of_args(line, 1);
- if (sscanf(line, "%"SCNu32, result) != 1) {
- command_parse_error();
- return 0;
- }
- return 1;
-}
-
-/* ================================================== */
-
-static int
parse_double(char *line, double *result)
{
check_number_of_args(line, 1);
@@ -1113,7 +1106,14 @@ parse_bindcmdaddress(char *line)
IPAddr ip;
check_number_of_args(line, 1);
- if (UTI_StringToIP(line, &ip)) {
+
+ /* Address starting with / is for the Unix domain socket */
+ if (line[0] == '/') {
+ parse_string(line, &bind_cmd_path);
+ /* / disables the socket */
+ if (!strcmp(bind_cmd_path, "/"))
+ bind_cmd_path[0] = '\0';
+ } else if (UTI_StringToIP(line, &ip)) {
if (ip.family == IPADDR_INET4)
bind_cmd_address4 = ip;
else if (ip.family == IPADDR_INET6)
@@ -1240,8 +1240,47 @@ parse_tempcomp(char *line)
static void
parse_include(char *line)
{
+ glob_t gl;
+ size_t i;
+
check_number_of_args(line, 1);
- CNF_ReadFile(line);
+
+ if (glob(line, 0, NULL, &gl)) {
+ DEBUG_LOG(LOGF_Configure, "glob of %s failed", line);
+ return;
+ }
+
+ for (i = 0; i < gl.gl_pathc; i++)
+ CNF_ReadFile(gl.gl_pathv[i]);
+
+ globfree(&gl);
+}
+
+/* ================================================== */
+
+void
+CNF_CreateDirs(uid_t uid, gid_t gid)
+{
+ char *dir;
+
+ UTI_CreateDirAndParents(logdir, 0755, uid, gid);
+ UTI_CreateDirAndParents(dumpdir, 0755, uid, gid);
+
+ /* Create a directory for the Unix domain command socket */
+ if (bind_cmd_path[0]) {
+ dir = UTI_PathToDir(bind_cmd_path);
+ UTI_CreateDirAndParents(dir, 0770, uid, gid);
+
+ /* Check the permissions and owner/group in case the directory already
+ existed. It MUST NOT be accessible by others as permissions on Unix
+ domain sockets are ignored on some systems (e.g. Solaris). */
+ if (!UTI_CheckDirPermissions(dir, 0770, uid, gid)) {
+ LOG(LOGS_WARN, LOGF_Configure, "Disabled command socket %s", bind_cmd_path);
+ bind_cmd_path[0] = '\0';
+ }
+
+ Free(dir);
+ }
}
/* ================================================== */
@@ -1449,22 +1488,6 @@ CNF_GetRtcDevice(void)
/* ================================================== */
-uint32_t
-CNF_GetCommandKey(void)
-{
- return command_key_id;
-}
-
-/* ================================================== */
-
-int
-CNF_GetGenerateCommandKey(void)
-{
- return generate_command_key;
-}
-
-/* ================================================== */
-
int
CNF_GetDumpOnExit(void)
{
@@ -1506,6 +1529,14 @@ CNF_GetMaxSlewRate(void)
/* ================================================== */
double
+CNF_GetMaxDistance(void)
+{
+ return max_distance;
+}
+
+/* ================================================== */
+
+double
CNF_GetReselectDistance(void)
{
return reselect_distance;
@@ -1697,6 +1728,14 @@ CNF_GetBindAcquisitionAddress(int family, IPAddr *addr)
/* ================================================== */
+char *
+CNF_GetBindCommandPath(void)
+{
+ return bind_cmd_path;
+}
+
+/* ================================================== */
+
void
CNF_GetBindCommandAddress(int family, IPAddr *addr)
{
diff --git a/conf.h b/conf.h
index ec08ded..75f2764 100644
--- a/conf.h
+++ b/conf.h
@@ -39,6 +39,8 @@ extern char *CNF_GetRtcDevice(void);
extern void CNF_ReadFile(const char *filename);
extern void CNF_ParseLine(const char *filename, int number, char *line);
+extern void CNF_CreateDirs(uid_t uid, gid_t gid);
+
extern void CNF_AddInitSources(void);
extern void CNF_AddSources(void);
extern void CNF_AddBroadcasts(void);
@@ -58,8 +60,6 @@ extern int CNF_GetLogRefclocks(void);
extern int CNF_GetLogTempComp(void);
extern char *CNF_GetKeysFile(void);
extern char *CNF_GetRtcFile(void);
-extern uint32_t CNF_GetCommandKey(void);
-extern int CNF_GetGenerateCommandKey(void);
extern int CNF_GetDumpOnExit(void);
extern int CNF_GetManualEnabled(void);
extern int CNF_GetCommandPort(void);
@@ -75,6 +75,7 @@ extern void CNF_GetFallbackDrifts(int *min, int *max);
extern void CNF_GetBindAddress(int family, IPAddr *addr);
extern void CNF_GetBindAcquisitionAddress(int family, IPAddr *addr);
extern void CNF_GetBindCommandAddress(int family, IPAddr *addr);
+extern char *CNF_GetBindCommandPath(void);
extern char *CNF_GetPidFile(void);
extern REF_LeapMode CNF_GetLeapSecMode(void);
extern char *CNF_GetLeapSecTimezone(void);
@@ -85,6 +86,7 @@ extern double CNF_GetMaxClockError(void);
extern double CNF_GetCorrectionTimeRatio(void);
extern double CNF_GetMaxSlewRate(void);
+extern double CNF_GetMaxDistance(void);
extern double CNF_GetReselectDistance(void);
extern double CNF_GetStratumWeight(void);
extern double CNF_GetCombineLimit(void);
diff --git a/configure b/configure
index d069c65..e9e596d 100755
--- a/configure
+++ b/configure
@@ -4,32 +4,12 @@
# chronyd/chronyc - Programs for keeping computer clocks accurate.
#
# Copyright (C) Richard P. Curnow 1997-2003
-# Copyright (C) Miroslav Lichvar 2009, 2012-2014
+# Copyright (C) Miroslav Lichvar 2009, 2012-2015
#
# =======================================================================
# This configure script determines the operating system type and version
-if [ "x${CC}" = "x" ]; then
- MYCC="gcc"
-else
- MYCC="${CC}"
-fi
-
-if [ "x${CFLAGS}" = "x" ]; then
- MYCFLAGS="-O2 -g"
-else
- MYCFLAGS="${CFLAGS}"
-fi
-
-MYCPPFLAGS="${CPPFLAGS}"
-
-if [ "x${MYCC}" = "xgcc" ]; then
- MYCFLAGS="${MYCFLAGS} -Wmissing-prototypes -Wall"
-fi
-
-MYLDFLAGS="${LDFLAGS}"
-
# ======================================================================
# FUNCTIONS
@@ -41,7 +21,7 @@ test_code () {
ldflags=$4
code=$5
- echo -n "Checking for $name : "
+ printf "%s" "Checking for $name : "
(
for h in $headers; do
@@ -113,12 +93,16 @@ For better control, use the options below.
--disable-pps Disable PPS refclock driver
--disable-ipv6 Disable IPv6 support
--disable-rtc Don't include RTC even on Linux
- --disable-linuxcaps Disable libcap (Linux capabilities) support
+ --disable-privdrop Disable support for dropping root privileges
+ --without-libcap Don't use libcap even if it is available
+ --enable-scfilter Enable support for system call filtering
+ --without-seccomp Don't use seccomp even if it is available
--disable-asyncdns Disable asynchronous name resolving
--disable-forcednsretry Don't retry on permanent DNS error
--with-ntp-era=SECONDS Specify earliest assumed NTP time in seconds
since 1970-01-01 [50*365 days ago]
--with-user=USER Specify default chronyd user [root]
+ --with-hwclockfile=PATH Specify default path to hwclock(8) adjtime file
--with-sendmail=PATH Path to sendmail binary [/usr/lib/sendmail]
--enable-debug Enable debugging support
@@ -131,6 +115,7 @@ Fine tuning of the installation directories:
--mandir=DIR man documentation [DATAROOTDIR/man]
--docdir=DIR documentation root [DATAROOTDIR/doc/chrony]
--localstatedir=DIR modifiable single-machine data [/var]
+ --chronysockdir=DIR location for chrony sockets [LOCALSTATEDIR/run/chrony]
--chronyvardir=DIR location for chrony data [LOCALSTATEDIR/lib/chrony]
Overriding system detection when cross-compiling:
@@ -174,12 +159,12 @@ get_features () {
ff=1
for f; do
if [ "$ff" = "0" ]; then
- echo -n " "
+ printf " "
fi
if grep "define FEAT_$f" config.h > /dev/null; then
- echo -n "+$f"
+ printf "%s" "+$f"
else
- echo -n "-$f"
+ printf "%s" "-$f"
fi
ff=0
done
@@ -213,7 +198,10 @@ try_tomcrypt=1
feat_rtc=1
try_rtc=0
feat_droproot=1
-try_libcap=0
+try_libcap=-1
+try_clockctl=0
+feat_scfilter=0
+try_seccomp=-1
readline_lib=""
readline_inc=""
ncurses_lib=""
@@ -227,6 +215,7 @@ feat_asyncdns=1
feat_forcednsretry=1
ntp_era_split=""
default_user="root"
+default_hwclockfile=""
mail_program="/usr/lib/sendmail"
for option
@@ -283,6 +272,9 @@ do
--localstatedir=* )
SETLOCALSTATEDIR=`echo $option | sed -e 's/^.*=//;'`
;;
+ --chronysockdir=* )
+ SETCHRONYSOCKDIR=`echo $option | sed -e 's/^.*=//;'`
+ ;;
--chronyvardir=* )
SETCHRONYVARDIR=`echo $option | sed -e 's/^.*=//;'`
;;
@@ -307,9 +299,21 @@ do
--disable-pps)
feat_pps=0
;;
- --disable-linuxcaps)
+ --disable-privdrop)
feat_droproot=0
;;
+ --without-libcap|--disable-linuxcaps)
+ try_libcap=0
+ ;;
+ --enable-scfilter)
+ feat_scfilter=1
+ ;;
+ --disable-scfilter)
+ feat_scfilter=0
+ ;;
+ --without-seccomp)
+ try_seccomp=0
+ ;;
--disable-asyncdns)
feat_asyncdns=0
;;
@@ -322,6 +326,9 @@ do
--with-user=* )
default_user=`echo $option | sed -e 's/^.*=//;'`
;;
+ --with-hwclockfile=* )
+ default_hwclockfile=`echo $option | sed -e 's/^.*=//;'`
+ ;;
--with-sendmail=* )
mail_program=`echo $option | sed -e 's/^.*=//;'`
;;
@@ -356,78 +363,50 @@ rm -f config.h config.log
SYSTEM=${OPERATINGSYSTEM}-${MACHINE}
-case $SYSTEM in
- SunOS-sun4* )
- case $VERSION in
- 4.* )
- EXTRA_OBJECTS="sys_sunos.o strerror.o"
- EXTRA_LIBS="-lkvm"
- add_def SUNOS
- echo "Configuring for SunOS (" $SYSTEM "version" $VERSION ")"
- ;;
- 5.* )
- EXTRA_OBJECTS="sys_solaris.o"
- EXTRA_LIBS="-lsocket -lnsl -lkvm -lelf"
- EXTRA_CLI_LIBS="-lsocket -lnsl"
- add_def SOLARIS
- echo "Configuring for Solaris (" $SYSTEM "SunOS version" $VERSION ")"
- ;;
- esac
- ;;
- Linux* )
- EXTRA_OBJECTS="sys_generic.o sys_linux.o wrap_adjtimex.o"
- try_libcap=1
+case $OPERATINGSYSTEM in
+ Linux)
+ EXTRA_OBJECTS="sys_generic.o sys_linux.o sys_timex.o"
+ [ $try_libcap != "0" ] && try_libcap=1
try_rtc=1
+ [ $try_seccomp != "0" ] && try_seccomp=1
try_setsched=1
try_lockmem=1
try_phc=1
add_def LINUX
echo "Configuring for " $SYSTEM
- if [ "${MACHINE}" = "alpha" ]; then
- echo "Enabling -mieee"
- # FIXME: Should really test for GCC
- MYCFLAGS="$MYCFLAGS -mieee"
- fi
- ;;
-
- BSD/386-i[3456]86|FreeBSD-i386|FreeBSD-amd64 )
- # Antti Jrvinen <costello@iki.fi> reported that this system can
- # be supported with the SunOS 4.x driver files.
- EXTRA_OBJECTS="sys_sunos.o strerror.o"
- EXTRA_LIBS="-lkvm"
- add_def SUNOS
- echo "Configuring for $SYSTEM (using SunOS driver)"
- ;;
- NetBSD-* )
- EXTRA_OBJECTS="sys_netbsd.o"
- EXTRA_LIBS="-lkvm"
- SYSDEFS=""
+ ;;
+
+ FreeBSD)
+ EXTRA_OBJECTS="sys_generic.o sys_netbsd.o sys_timex.o"
+ add_def FREEBSD
+ echo "Configuring for $SYSTEM"
+ ;;
+ NetBSD)
+ EXTRA_OBJECTS="sys_generic.o sys_netbsd.o sys_timex.o"
+ try_clockctl=1
+ add_def NETBSD
echo "Configuring for $SYSTEM"
;;
- Darwin-* )
+ Darwin)
EXTRA_OBJECTS="sys_macosx.o"
EXTRA_LIBS="-lresolv"
EXTRA_CLI_LIBS="-lresolv"
add_def MACOSX
echo "Configuring for MacOS X (" $SYSTEM "MacOS X version" $VERSION ")"
;;
- SunOS-i86pc* )
- # Doug Woodward <dougw@whistler.com> reported that this configuration
- # works for Solaris 2.8 / SunOS 5.8 on x86 platforms
- EXTRA_OBJECTS="sys_solaris.o"
- EXTRA_LIBS="-lsocket -lnsl -lkvm -lelf"
- EXTRA_CLI_LIBS="-lsocket -lnsl"
+ SunOS)
+ EXTRA_OBJECTS="sys_generic.o sys_solaris.o sys_timex.o"
+ EXTRA_LIBS="-lsocket -lnsl -lresolv"
+ EXTRA_CLI_LIBS="-lsocket -lnsl -lresolv"
add_def SOLARIS
+ # These are needed to have msg_control in struct msghdr
+ add_def __EXTENSIONS__
+ add_def _XOPEN_SOURCE 1
+ add_def _XOPEN_SOURCE_EXTENDED 1
echo "Configuring for Solaris (" $SYSTEM "SunOS version" $VERSION ")"
;;
- CYGWIN32_NT-i[3456]86 )
- EXTRA_OBJECTS="sys_winnt.o"
- EXTRA_LIBS=""
- add_def WINNT
- echo "Configuring for Windows NT (Cygwin32)"
- ;;
* )
- echo "Sorry, I don't know how to build this software on your system."
+ echo "error: $SYSTEM is not supported (yet?)"
exit 1
;;
esac
@@ -460,6 +439,35 @@ if [ $feat_refclock = "1" ]; then
EXTRA_OBJECTS="$EXTRA_OBJECTS refclock.o refclock_phc.o refclock_pps.o refclock_shm.o refclock_sock.o"
fi
+MYCC="$CC"
+MYCFLAGS="$CFLAGS"
+MYCPPFLAGS="$CPPFLAGS"
+MYLDFLAGS="$LDFLAGS"
+
+if [ "x$MYCC" = "x" ]; then
+ MYCC=gcc
+ if ! test_code "$MYCC" '' '' '' ''; then
+ MYCC=cc
+ if ! test_code "$MYCC" '' '' '' ''; then
+ echo "error: no C compiler found"
+ exit 1
+ fi
+ fi
+else
+ if ! test_code "$MYCC" '' '' '' ''; then
+ echo "error: C compiler $MYCC cannot create executables"
+ exit 1
+ fi
+fi
+
+if [ "x$MYCFLAGS" = "x" ]; then
+ MYCFLAGS="-O2 -g"
+fi
+
+if [ "x$MYCC" = "xgcc" ]; then
+ MYCFLAGS="$MYCFLAGS -Wmissing-prototypes -Wall"
+fi
+
if test_code '64-bit time_t' 'time.h' '' '' '
char x[sizeof(time_t) > 4 ? 1 : -1] = {0};
return x[0];'
@@ -472,7 +480,7 @@ then
else
split_seconds=`date '+%s'`
if [ "x$split_seconds" = "" ]; then
- echo "Could not get current time, --with-ntp-era option is needed"
+ echo "error: could not get current time, --with-ntp-era option is needed"
exit 1
fi
split_days=$((50 * 365))
@@ -501,7 +509,7 @@ else
if test_code 'math in -lm' 'math.h' '' '-lm' "$MATHCODE"; then
LIBS="-lm"
else
- echo "Can't compile/link a program which uses sqrt(), log(), pow(), bailing out"
+ echo "error: could not compile/link a program which uses sqrt(), log(), pow()"
exit 1
fi
fi
@@ -514,21 +522,28 @@ if test_code '<inttypes.h>' 'inttypes.h' '' '' ''; then
add_def HAVE_INTTYPES_H
fi
+if test_code 'struct in_pktinfo' 'sys/socket.h netinet/in.h' '' '' '
+ struct in_pktinfo ipi;
+ return sizeof (ipi.ipi_spec_dst.s_addr) + IP_PKTINFO;'
+then
+ add_def HAVE_IN_PKTINFO
+fi
+
if [ $feat_ipv6 = "1" ] && \
- test_code 'IPv6 support' 'arpa/inet.h sys/socket.h netinet/in.h' '' '' '
+ test_code 'IPv6 support' 'arpa/inet.h sys/socket.h netinet/in.h' '' "$EXTRA_LIBS" '
struct sockaddr_in6 n;
char p[100];
n.sin6_addr = in6addr_any;
return !inet_ntop(AF_INET6, &n.sin6_addr.s6_addr, p, sizeof(p));'
then
add_def FEAT_IPV6
- if test_code 'in6_pktinfo' 'sys/socket.h netinet/in.h' '' '' '
- return sizeof(struct in6_pktinfo);'
+ if test_code 'struct in6_pktinfo' 'sys/socket.h netinet/in.h' '' '' '
+ return sizeof (struct in6_pktinfo) + IPV6_PKTINFO;'
then
add_def HAVE_IN6_PKTINFO
else
- if test_code 'in6_pktinfo with _GNU_SOURCE' 'sys/socket.h netinet/in.h' \
- '-D_GNU_SOURCE' '' 'return sizeof(struct in6_pktinfo);'
+ if test_code 'struct in6_pktinfo with _GNU_SOURCE' 'sys/socket.h netinet/in.h' \
+ '-D_GNU_SOURCE' '' 'return sizeof (struct in6_pktinfo) + IPV6_PKTINFO;'
then
add_def _GNU_SOURCE
add_def HAVE_IN6_PKTINFO
@@ -536,7 +551,7 @@ then
fi
fi
-if test_code 'getaddrinfo()' 'sys/types.h sys/socket.h netdb.h' '' '' \
+if test_code 'getaddrinfo()' 'sys/types.h sys/socket.h netdb.h' '' "$EXTRA_LIBS" \
'return getaddrinfo(0, 0, 0, 0);'
then
add_def HAVE_GETADDRINFO
@@ -586,6 +601,20 @@ then
EXTRA_LIBS="$EXTRA_LIBS -lcap"
fi
+if [ $feat_droproot = "1" ] && [ $try_clockctl = "1" ] && \
+ test_code '<sys/clockctl.h>' 'sys/clockctl.h' '' '' ''
+then
+ add_def FEAT_PRIVDROP
+fi
+
+if [ $feat_scfilter = "1" ] && [ $try_seccomp = "1" ] && \
+ test_code seccomp 'seccomp.h' '' '-lseccomp' \
+ 'seccomp_init(SCMP_ACT_KILL);'
+then
+ add_def FEAT_SCFILTER
+ EXTRA_LIBS="$EXTRA_LIBS -lseccomp"
+fi
+
if [ $feat_rtc = "1" ] && [ $try_rtc = "1" ] && \
test_code '<linux/rtc.h>' 'sys/ioctl.h linux/rtc.h' '' '' \
'ioctl(1, RTC_UIE_ON&RTC_UIE_OFF&RTC_RD_TIME&RTC_SET_TIME, 0&RTC_UF);'
@@ -759,28 +788,37 @@ if [ "x$SETLOCALSTATEDIR" != "x" ]; then
LOCALSTATEDIR=$SETLOCALSTATEDIR
fi
+CHRONYSOCKDIR=${LOCALSTATEDIR}/run/chrony
+if [ "x$SETCHRONYSOCKDIR" != "x" ]; then
+ CHRONYSOCKDIR=$SETCHRONYSOCKDIR
+fi
+
CHRONYVARDIR=${LOCALSTATEDIR}/lib/chrony
if [ "x$SETCHRONYVARDIR" != "x" ]; then
CHRONYVARDIR=$SETCHRONYVARDIR
fi
add_def DEFAULT_CONF_FILE "\"$SYSCONFDIR/chrony.conf\""
+add_def DEFAULT_HWCLOCK_FILE "\"$default_hwclockfile\""
add_def DEFAULT_USER "\"$default_user\""
+add_def DEFAULT_COMMAND_SOCKET "\"$CHRONYSOCKDIR/chronyd.sock\""
add_def MAIL_PROGRAM "\"$mail_program\""
-common_features="`get_features ASYNCDNS IPV6 SECHASH`"
+common_features="`get_features IPV6 DEBUG`"
chronyc_features="`get_features READLINE`"
-chronyd_features="`get_features CMDMON NTP REFCLOCK RTC PRIVDROP DEBUG`"
+chronyd_features="`get_features CMDMON NTP REFCLOCK RTC PRIVDROP SCFILTER SECHASH ASYNCDNS`"
add_def CHRONYC_FEATURES "\"$chronyc_features $common_features\""
add_def CHRONYD_FEATURES "\"$chronyd_features $common_features\""
echo "Features : $chronyd_features $chronyc_features $common_features"
if [ -f version.txt ]; then
- add_def CHRONY_VERSION "\"`cat version.txt`\""
+ CHRONY_VERSION="`cat version.txt`"
else
- add_def CHRONY_VERSION "\"DEVELOPMENT\""
+ CHRONY_VERSION="DEVELOPMENT"
fi
+add_def CHRONY_VERSION "\"${CHRONY_VERSION}\""
+
for f in Makefile chrony.conf.5 chrony.texi chronyc.1 chronyd.8
do
echo Creating $f
@@ -802,8 +840,11 @@ do
s%@MANDIR@%${MANDIR}%;\
s%@INFODIR@%${INFODIR}%;\
s%@LOCALSTATEDIR@%${LOCALSTATEDIR}%;\
+ s%@CHRONYSOCKDIR@%${CHRONYSOCKDIR}%;\
s%@CHRONYVARDIR@%${CHRONYVARDIR}%;\
- s%@DEFAULT_USER@%${default_user}%;"\
+ s%@DEFAULT_HWCLOCK_FILE@%${default_hwclockfile}%;\
+ s%@DEFAULT_USER@%${default_user}%;\
+ s%@CHRONY_VERSION@%${CHRONY_VERSION}%;" \
< ${f}.in > $f
done
diff --git a/contrib/bryan_christianson_1/README.txt b/contrib/bryan_christianson_1/README.txt
new file mode 100644
index 0000000..0a221aa
--- /dev/null
+++ b/contrib/bryan_christianson_1/README.txt
@@ -0,0 +1,103 @@
+Notes for installing chrony on MacOS X
+Author: Bryan Christianson (bryan@whatroute.net)
+------------------------------------------------
+
+These files are for those admins/users who would prefer to install chrony
+from the source distribution and are intended as guidelines rather than
+being definitive. They can be edited with a plain text editor, such as
+vi, emacs or your favourite IDE (xcode)
+
+It is assumed you are comfortable with installing software from the
+terminal command line and know how to use sudo to acquire root access.
+
+If you are not familiar with the MacOS X command line then
+please consider using ChronyControl from http://whatroute.net/chronycontrol.html
+
+ChronyControl provides a gui wrapper for installing these files and sets the
+necessary permissions on each file.
+
+
+Install the chrony software
+---------------------------
+
+You will need xcode and the commandline additions to build and install chrony.
+These can be obtained from Apple's website via the App Store.
+
+cd to the chrony directory
+./configure
+make
+sudo make install
+
+chrony is now installed in default locations (/usr/local/sbin/chronyd,
+/usr/local/bin/chronyc)
+
+Create a chrony.conf file - see the chrony website for details
+
+The support files here assume the following directives are specified in the
+chrony.conf file
+
+keyfile /etc/chrony.d/chrony.keys
+driftfile /var/db/chrony/chrony.drift
+bindcmdaddress /var/db/chrony/chronyd.sock
+logdir /var/log/chrony
+dumpdir /var/db/chrony
+
+Install this file as /etc/chrony.d/chrony.conf and create
+the directories specified in the above directives if they don't exist.
+You will need root permissions to create the directories.
+
+
+Running chronyd
+---------------
+At this point chronyd *could* be run as a daemon. Apple discourage running
+daemons and their preferred method uses the launchd facility. The
+support files here provide a launchd configuration file for chronyd and also
+a shell script and launchd configuration file to rotate the chronyd logs on a daily basis.
+
+
+Support files
+-------------
+Dates and sizes may differ
+-rw-r--r-- 1 yourname staff 2084 4 Aug 22:54 README.txt
+-rwxr-xr-x 1 yourname staff 676 4 Aug 21:18 chronylogrotate.sh
+-rw-r--r-- 1 yourname staff 543 18 Jul 20:10 org.tuxfamily.chronyc.plist
+-rw-r--r-- 1 yourname staff 511 19 Jun 18:30 org.tuxfamily.chronyd.plist
+
+If you have used chrony support directories other than those suggested, you
+will need to edit each file and make the appropriate changes.
+
+
+Installing the support files
+----------------------------
+
+1. chronylogrotate.sh
+This is a simple shell script that deletes old log files. Unfortunately because
+of the need to run chronyc, the standard MacOS X logrotation does not work with
+chrony logs.
+
+This script runs on a daily basis under control of launchd and should be
+installed in the /usr/local/bin directory
+
+sudo cp chronylogrotate.sh /usr/local/bin
+sudo chmod +x /usr/local/bin/chronylogrotate.sh
+sudo chown root:wheel /usr/local/bin/chronylogrotate.sh
+
+
+2. org.tuxfamily.chronyc.plist
+This file is the launchd plist that runs logrotation each day. You may
+wish to edit this file to change the time of day at which the rotation
+will run, currently 04:05 am
+
+sudo cp org.tuxfamily.chronyc.plist /Library/LaunchDaemons
+sudo chown root:wheel /Library/LaunchDaemons/org.tuxfamily.chronyc.plist
+sudo chmod 0644 /Library/LaunchDaemons/org.tuxfamily.chronyc.plist
+sudo launchctl load -w /Library/LaunchDaemons/org.tuxfamily.chronyc.plist
+
+
+3. org.tuxfamily.chronyd.plist
+This file is the launchd plist that runs chronyd when the Macintosh starts.
+
+sudo cp org.tuxfamily.chronyd.plist /Library/LaunchDaemons
+sudo chown root:wheel /Library/LaunchDaemons/org.tuxfamily.chronyd.plist
+sudo chmod 0644 /Library/LaunchDaemons/org.tuxfamily.chronyd.plist
+sudo launchctl load -w /Library/LaunchDaemons/org.tuxfamily.chronyd.plist
diff --git a/contrib/bryan_christianson_1/chronylogrotate.sh b/contrib/bryan_christianson_1/chronylogrotate.sh
new file mode 100755
index 0000000..632aba3
--- /dev/null
+++ b/contrib/bryan_christianson_1/chronylogrotate.sh
@@ -0,0 +1,45 @@
+#!/bin/sh
+
+# chronylogrotate.sh
+# ChronyControl
+#
+# Created by Bryan Christianson on 12/07/15.
+#
+
+LOGDIR=/var/log/chrony
+
+if [ ! -e "$LOGDIR" ]; then
+ echo "missing directory: $LOGDIR"
+ exit 1
+fi
+
+cd $LOGDIR
+
+rotate () {
+ prefix=$1
+
+ rm -f $prefix.log.10
+
+ for (( count=9; count>= 0; count-- ))
+ do
+ next=$(( $count+1 ))
+ if [ -f $prefix.log.$count ]; then
+ mv $prefix.log.$count $prefix.log.$next
+ fi
+ done
+
+ if [ -f $prefix.log ]; then
+ mv $prefix.log $prefix.log.0
+ fi
+}
+
+rotate measurements
+rotate statistics
+rotate tracking
+
+#
+# signal chronyd via chronyc
+
+/usr/local/bin/chronyc -a -f /etc/chrony.d/chrony.conf cyclelogs > /dev/null
+
+exit $? \ No newline at end of file
diff --git a/contrib/bryan_christianson_1/org.tuxfamily.chronyc.plist b/contrib/bryan_christianson_1/org.tuxfamily.chronyc.plist
new file mode 100644
index 0000000..a3c42c6
--- /dev/null
+++ b/contrib/bryan_christianson_1/org.tuxfamily.chronyc.plist
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>org.tuxfamily.logrotate</string>
+ <key>KeepAlive</key>
+ <false/>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/bin/sh</string>
+ <string>/usr/local/bin/chronylogrotate.sh</string>
+ </array>
+ <key>StartCalendarInterval</key>
+ <dict>
+ <key>Minute</key>
+ <integer>5</integer>
+ <key>Hour</key>
+ <integer>4</integer>
+ </dict>
+</dict>
+</plist>
diff --git a/contrib/bryan_christianson_1/org.tuxfamily.chronyd.plist b/contrib/bryan_christianson_1/org.tuxfamily.chronyd.plist
new file mode 100644
index 0000000..2bf42aa
--- /dev/null
+++ b/contrib/bryan_christianson_1/org.tuxfamily.chronyd.plist
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>org.tuxfamily.chronyd</string>
+ <key>Program</key>
+ <string>/usr/local/sbin/chronyd</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>chronyd</string>
+ <string>-n</string>
+ <string>-f</string>
+ <string>/private/etc/chrony.d/chrony.conf</string>
+ </array>
+ <key>KeepAlive</key>
+ <true/>
+</dict>
+</plist>
diff --git a/examples/chrony-wait.service b/examples/chrony-wait.service
index 6513b4f..3f02f71 100644
--- a/examples/chrony-wait.service
+++ b/examples/chrony-wait.service
@@ -9,7 +9,7 @@ Wants=time-sync.target
Type=oneshot
# Wait up to ~10 minutes for chronyd to synchronize and the remaining
# clock correction to be less than 0.1 seconds
-ExecStart=/usr/bin/chronyc waitsync 60 0.1
+ExecStart=/usr/bin/chronyc waitsync 600 0.1 0.0 1
RemainAfterExit=yes
StandardOutput=null
diff --git a/examples/chrony.conf.example1 b/examples/chrony.conf.example1
index f749534..ab16335 100644
--- a/examples/chrony.conf.example1
+++ b/examples/chrony.conf.example1
@@ -5,8 +5,8 @@ pool pool.ntp.org iburst
driftfile /var/lib/chrony/drift
# In first three updates step the system clock instead of slew
-# if the adjustment is larger than 10 seconds.
-makestep 10 3
+# if the adjustment is larger than 1 second.
+makestep 1.0 3
# Enable kernel synchronization of the real-time clock (RTC).
rtcsync
diff --git a/examples/chrony.conf.example2 b/examples/chrony.conf.example2
index 7c61b0a..45c67c1 100644
--- a/examples/chrony.conf.example2
+++ b/examples/chrony.conf.example2
@@ -6,8 +6,8 @@ pool pool.ntp.org iburst
driftfile /var/lib/chrony/drift
# In first three updates step the system clock instead of slew
-# if the adjustment is larger than 10 seconds.
-makestep 10 3
+# if the adjustment is larger than 1 second.
+makestep 1.0 3
# Enable kernel synchronization of the real-time clock (RTC).
rtcsync
@@ -18,14 +18,8 @@ rtcsync
# Serve time even if not synchronized to any NTP server.
#local stratum 10
-# Specify file containing keys for NTP and command authentication.
-keyfile /etc/chrony.keys
-
-# Specify key number for command authentication.
-commandkey 1
-
-# Generate new command key on start if missing.
-generatecommandkey
+# Specify file containing keys for NTP authentication.
+#keyfile /etc/chrony.keys
# Disable logging of client accesses.
noclientlog
diff --git a/examples/chrony.conf.example3 b/examples/chrony.conf.example3
index 9f2bbe5..f1c2d48 100644
--- a/examples/chrony.conf.example3
+++ b/examples/chrony.conf.example3
@@ -95,24 +95,10 @@
driftfile /var/lib/chrony/drift
-# If you want to use the program called chronyc to configure aspects of
-# chronyd's operation once it is running (e.g. tell it the Internet link
-# has gone up or down), you need a password. This is stored in the
-# following keys file. (You also need keys to support authenticated NTP
-# exchanges between cooperating machines.) Again, this option is
-# assumed by default.
+# If you want to enable NTP authentication with symmetric keys, you will need
+# to uncomment the following line and edit the file to set up the keys.
-keyfile /etc/chrony.keys
-
-# Tell chronyd which numbered key in the file is used as the password
-# for chronyc. (You can pick any integer up to 2**32-1. '1' is just a
-# default. Using another value will _NOT_ increase security.)
-
-commandkey 1
-
-# With this directive a random password will be generated automatically.
-
-generatecommandkey
+! keyfile /etc/chrony.keys
# chronyd can save the measurement history for the servers to files when
# it it exits. This is useful in 2 situations:
@@ -142,15 +128,15 @@ generatecommandkey
#######################################################################
### INITIAL CLOCK CORRECTION
# This option is useful to quickly correct the clock on start if it's
-# off by a large amount. The value '10' means that if the error is less
-# than 10 seconds, it will be gradually removed by speeding up or
-# slowing down your computer's clock until it is correct. If the error
-# is above 10 seconds, an immediate time jump will be applied to correct
-# it. The value '1' means the step is allowed only on the first update
-# of the clock. Some software can get upset if the system clock jumps
+# off by a large amount. The value '1.0' means that if the error is less
+# than 1 second, it will be gradually removed by speeding up or slowing
+# down your computer's clock until it is correct. If the error is above
+# 1 second, an immediate time jump will be applied to correct it. The
+# value '3' means the step is allowed only in the first three updates of
+# the clock. Some software can get upset if the system clock jumps
# (especially backwards), so be careful!
-! makestep 10 1
+! makestep 1.0 3
#######################################################################
### LOGGING
@@ -262,11 +248,6 @@ generatecommandkey
# syntax and meaning is the same as for 'allow' and 'deny', except that
# 'cmdallow' and 'cmddeny' control access to the chronyd's command port.
-# NOTE, even if the host where you run chronyc is granted access, you
-# still need a command key set up and you have to know the password to
-# put into chronyc to allow you to modify chronyd's parameters. By
-# default all you can do is view information about chronyd's operation.
-
#######################################################################
### REAL TIME CLOCK
# chronyd can characterise the system's real-time clock. This is the
diff --git a/examples/chrony.keys.example b/examples/chrony.keys.example
index 1583174..e6660ae 100644
--- a/examples/chrony.keys.example
+++ b/examples/chrony.keys.example
@@ -1,29 +1,15 @@
-#######################################################################
+# This is an example chrony keys file. It is used for NTP authentication with
+# symmetric keys. It should be readable only by root or the user to which
+# chronyd is configured to switch to.
#
-# This is an example chrony keys file. You should copy it to /etc/chrony.keys
-# after editing it to set up the key(s) you want to use. It should be readable
-# only by root or the user chronyd drops the root privileges to. In most
-# situations, you will require a single key (the 'commandkey') so that you can
-# supply a password to chronyc to enable you to modify chronyd's operation
-# whilst it is running.
-#
-# Copyright 2002 Richard P. Curnow
-#
-######################################################################
+# Don't use the example keys! The keys need to be random for maximum security.
+# These shell commands can be used to generate random MD5 and SHA1 keys on
+# systems which have the /dev/urandom device:
+# echo "1 MD5 HEX:$(tr -d -c '[:xdigit:]' < /dev/urandom | head -c 32)"
+# echo "1 SHA1 HEX:$(tr -d -c '[:xdigit:]' < /dev/urandom | head -c 40)"
# Examples of valid keys:
#1 ALongAndRandomPassword
#2 MD5 HEX:B028F91EA5C38D06C2E140B26C7F41EC
#3 SHA1 HEX:1DC764E0791B11FA67EFC7ECBC4B0D73F68A070C
-
-# The keys should be random for maximum security. If you wanted to use a key
-# with ID 1 as your commandkey (i.e. chronyc password) you would put
-# "commandkey 1" into chrony.conf. If no commandkey is present in the keys
-# file and the generatecommandkey directive is specified in chrony.conf,
-# a random commandkey will be generated and added to the keys file
-# automatically on chronyd start.
-
-# You might want to define more keys if you use the authentication facility
-# in the network time protocol to authenticate request/response packets between
-# trusted clients and servers.
diff --git a/examples/chrony.logrotate b/examples/chrony.logrotate
index e0cd83c..2823a1a 100644
--- a/examples/chrony.logrotate
+++ b/examples/chrony.logrotate
@@ -3,6 +3,6 @@
nocreate
sharedscripts
postrotate
- /usr/bin/chronyc -a cyclelogs > /dev/null 2>&1 || true
+ /usr/bin/chronyc cyclelogs > /dev/null 2>&1 || true
endscript
}
diff --git a/examples/chrony.nm-dispatcher b/examples/chrony.nm-dispatcher
index d23700b..084aed6 100644
--- a/examples/chrony.nm-dispatcher
+++ b/examples/chrony.nm-dispatcher
@@ -6,12 +6,12 @@ export LC_ALL=C
if [ "$2" = "up" ]; then
/sbin/ip route list dev "$1" | grep -q '^default' &&
- /usr/bin/chronyc -a online > /dev/null 2>&1
+ /usr/bin/chronyc online > /dev/null 2>&1
fi
if [ "$2" = "down" ]; then
/sbin/ip route list | grep -q '^default' ||
- /usr/bin/chronyc -a offline > /dev/null 2>&1
+ /usr/bin/chronyc offline > /dev/null 2>&1
fi
exit 0
diff --git a/examples/chrony.spec b/examples/chrony.spec
index fa8ae33..d8f9e31 100644
--- a/examples/chrony.spec
+++ b/examples/chrony.spec
@@ -1,4 +1,4 @@
-%global chrony_version 2.1.1
+%global chrony_version 2.2
%if 0%(echo %{chrony_version} | grep -q pre && echo 1)
%global prerelease %(echo %{chrony_version} | sed 's/.*-//')
%endif
diff --git a/getdate.c b/getdate.c
index 48a3b12..c0a2a51 100644
--- a/getdate.c
+++ b/getdate.c
@@ -1,19 +1,19 @@
-/* A Bison parser, made by GNU Bison 2.7. */
+/* A Bison parser, made by GNU Bison 3.0.2. */
/* Bison implementation for Yacc-like parsers in C
-
- Copyright (C) 1984, 1989-1990, 2000-2012 Free Software Foundation, Inc.
-
+
+ Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc.
+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
-
+
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
-
+
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
@@ -26,7 +26,7 @@
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
-
+
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
@@ -44,7 +44,7 @@
#define YYBISON 1
/* Bison version. */
-#define YYBISON_VERSION "2.7"
+#define YYBISON_VERSION "3.0.2"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
@@ -62,8 +62,7 @@
/* Copy the first part of user declarations. */
-/* Line 371 of yacc.c */
-#line 1 "getdate.y"
+#line 1 "getdate.y" /* yacc.c:339 */
/*
** Originally written by Steven M. Bellovin <smb@research.att.com> while
@@ -74,12 +73,7 @@
** This code is in the public domain and has no copyright.
*/
-#ifdef HAVE_CONFIG_H
-# include <config.h>
-# ifdef HAVE_ALLOCA_H
-# include <alloca.h>
-# endif
-#endif
+#include "config.h"
/* Since the code of getdate.y is not included in the Emacs executable
itself, there is no need to #define static in this file. Even if
@@ -241,14 +235,13 @@ static int yyRelSeconds;
static int yyRelYear;
-/* Line 371 of yacc.c */
-#line 246 "getdate.c"
+#line 239 "getdate.c" /* yacc.c:339 */
-# ifndef YY_NULL
+# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
-# define YY_NULL nullptr
+# define YY_NULLPTR nullptr
# else
-# define YY_NULL 0
+# define YY_NULLPTR 0
# endif
# endif
@@ -261,7 +254,7 @@ static int yyRelYear;
#endif
-/* Enabling traces. */
+/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
@@ -269,72 +262,56 @@ static int yyRelYear;
extern int yydebug;
#endif
-/* Tokens. */
+/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
- /* Put the tokens into the symbol table, so that GDB and other debuggers
- know about them. */
- enum yytokentype {
- tAGO = 258,
- tDAY = 259,
- tDAY_UNIT = 260,
- tDAYZONE = 261,
- tDST = 262,
- tHOUR_UNIT = 263,
- tID = 264,
- tMERIDIAN = 265,
- tMINUTE_UNIT = 266,
- tMONTH = 267,
- tMONTH_UNIT = 268,
- tSEC_UNIT = 269,
- tSNUMBER = 270,
- tUNUMBER = 271,
- tYEAR_UNIT = 272,
- tZONE = 273
- };
+ enum yytokentype
+ {
+ tAGO = 258,
+ tDAY = 259,
+ tDAY_UNIT = 260,
+ tDAYZONE = 261,
+ tDST = 262,
+ tHOUR_UNIT = 263,
+ tID = 264,
+ tMERIDIAN = 265,
+ tMINUTE_UNIT = 266,
+ tMONTH = 267,
+ tMONTH_UNIT = 268,
+ tSEC_UNIT = 269,
+ tSNUMBER = 270,
+ tUNUMBER = 271,
+ tYEAR_UNIT = 272,
+ tZONE = 273
+ };
#endif
-
+/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
-typedef union YYSTYPE
+typedef union YYSTYPE YYSTYPE;
+union YYSTYPE
{
-/* Line 387 of yacc.c */
-#line 182 "getdate.y"
+#line 177 "getdate.y" /* yacc.c:355 */
int Number;
enum _MERIDIAN Meridian;
-
-/* Line 387 of yacc.c */
-#line 310 "getdate.c"
-} YYSTYPE;
+#line 300 "getdate.c" /* yacc.c:355 */
+};
# define YYSTYPE_IS_TRIVIAL 1
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
+
extern YYSTYPE yylval;
-#ifdef YYPARSE_PARAM
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void *YYPARSE_PARAM);
-#else
-int yyparse ();
-#endif
-#else /* ! YYPARSE_PARAM */
-#if defined __STDC__ || defined __cplusplus
int yyparse (void);
-#else
-int yyparse ();
-#endif
-#endif /* ! YYPARSE_PARAM */
/* Copy the second part of user declarations. */
-/* Line 390 of yacc.c */
-#line 338 "getdate.c"
+#line 315 "getdate.c" /* yacc.c:358 */
#ifdef short
# undef short
@@ -348,11 +325,8 @@ typedef unsigned char yytype_uint8;
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
-#elif (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-typedef signed char yytype_int8;
#else
-typedef short int yytype_int8;
+typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
@@ -372,8 +346,7 @@ typedef short int yytype_int16;
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
-# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
+# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
@@ -395,6 +368,33 @@ typedef short int yytype_int16;
# endif
#endif
+#ifndef YY_ATTRIBUTE
+# if (defined __GNUC__ \
+ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
+ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
+# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
+# else
+# define YY_ATTRIBUTE(Spec) /* empty */
+# endif
+#endif
+
+#ifndef YY_ATTRIBUTE_PURE
+# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
+#endif
+
+#ifndef YY_ATTRIBUTE_UNUSED
+# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
+#endif
+
+#if !defined _Noreturn \
+ && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
+# if defined _MSC_VER && 1200 <= _MSC_VER
+# define _Noreturn __declspec (noreturn)
+# else
+# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
+# endif
+#endif
+
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
@@ -402,23 +402,25 @@ typedef short int yytype_int16;
# define YYUSE(E) /* empty */
#endif
-/* Identity function, used to suppress warnings about constant conditions. */
-#ifndef lint
-# define YYID(N) (N)
-#else
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static int
-YYID (int yyi)
+#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
+/* Suppress an incorrect diagnostic about yylval being uninitialized. */
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
+ _Pragma ("GCC diagnostic push") \
+ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
+ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
+ _Pragma ("GCC diagnostic pop")
#else
-static int
-YYID (yyi)
- int yyi;
+# define YY_INITIAL_VALUE(Value) Value
#endif
-{
- return yyi;
-}
+#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
+#ifndef YY_INITIAL_VALUE
+# define YY_INITIAL_VALUE(Value) /* Nothing. */
+#endif
+
#if ! defined yyoverflow || YYERROR_VERBOSE
@@ -437,8 +439,7 @@ YYID (yyi)
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
-# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
+# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
@@ -450,8 +451,8 @@ YYID (yyi)
# endif
# ifdef YYSTACK_ALLOC
- /* Pacify GCC's `empty if-body' warning. */
-# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
+ /* Pacify GCC's 'empty if-body' warning. */
+# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
@@ -467,7 +468,7 @@ YYID (yyi)
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
- && (defined YYFREE || defined free)))
+ && (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
@@ -475,15 +476,13 @@ YYID (yyi)
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
-# if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
+# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
-# if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
+# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
@@ -493,7 +492,7 @@ void free (void *); /* INFRINGES ON USER NAME SPACE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
- || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
+ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
@@ -518,16 +517,16 @@ union yyalloc
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
-# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
- do \
- { \
- YYSIZE_T yynewbytes; \
- YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
- Stack = &yyptr->Stack_alloc; \
- yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
- yyptr += yynewbytes / sizeof (*yyptr); \
- } \
- while (YYID (0))
+# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
+ do \
+ { \
+ YYSIZE_T yynewbytes; \
+ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
+ Stack = &yyptr->Stack_alloc; \
+ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+ yyptr += yynewbytes / sizeof (*yyptr); \
+ } \
+ while (0)
#endif
@@ -546,7 +545,7 @@ union yyalloc
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
- while (YYID (0))
+ while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
@@ -562,17 +561,19 @@ union yyalloc
#define YYNNTS 11
/* YYNRULES -- Number of rules. */
#define YYNRULES 51
-/* YYNRULES -- Number of states. */
+/* YYNSTATES -- Number of states. */
#define YYNSTATES 61
-/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
+/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
+ by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 273
-#define YYTRANSLATE(YYX) \
+#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
-/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
+/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
+ as returned by yylex, without out-of-bounds checking. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
@@ -606,48 +607,15 @@ static const yytype_uint8 yytranslate[] =
};
#if YYDEBUG
-/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
- YYRHS. */
-static const yytype_uint8 yyprhs[] =
-{
- 0, 0, 3, 4, 7, 9, 11, 13, 15, 17,
- 19, 22, 27, 32, 39, 46, 48, 50, 53, 55,
- 58, 61, 65, 71, 75, 79, 82, 87, 90, 94,
- 97, 99, 102, 105, 107, 110, 113, 115, 118, 121,
- 123, 126, 129, 131, 134, 137, 139, 142, 145, 147,
- 149, 150
-};
-
-/* YYRHS -- A `-1'-separated list of the rules' RHS. */
-static const yytype_int8 yyrhs[] =
-{
- 23, 0, -1, -1, 23, 24, -1, 25, -1, 26,
- -1, 28, -1, 27, -1, 29, -1, 31, -1, 16,
- 10, -1, 16, 19, 16, 32, -1, 16, 19, 16,
- 15, -1, 16, 19, 16, 19, 16, 32, -1, 16,
- 19, 16, 19, 16, 15, -1, 18, -1, 6, -1,
- 18, 7, -1, 4, -1, 4, 20, -1, 16, 4,
- -1, 16, 21, 16, -1, 16, 21, 16, 21, 16,
- -1, 16, 15, 15, -1, 16, 12, 15, -1, 12,
- 16, -1, 12, 16, 20, 16, -1, 16, 12, -1,
- 16, 12, 16, -1, 30, 3, -1, 30, -1, 16,
- 17, -1, 15, 17, -1, 17, -1, 16, 13, -1,
- 15, 13, -1, 13, -1, 16, 5, -1, 15, 5,
- -1, 5, -1, 16, 8, -1, 15, 8, -1, 8,
- -1, 16, 11, -1, 15, 11, -1, 11, -1, 16,
- 14, -1, 15, 14, -1, 14, -1, 16, -1, -1,
- 10, -1
-};
-
-/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
+ /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
- 0, 198, 198, 199, 202, 205, 208, 211, 214, 217,
- 220, 226, 232, 241, 247, 259, 262, 266, 271, 275,
- 279, 285, 289, 307, 313, 319, 323, 328, 332, 339,
- 347, 350, 353, 356, 359, 362, 365, 368, 371, 374,
- 377, 380, 383, 386, 389, 392, 395, 398, 401, 406,
- 440, 443
+ 0, 193, 193, 194, 197, 200, 203, 206, 209, 212,
+ 215, 221, 227, 236, 242, 254, 257, 261, 266, 270,
+ 274, 280, 284, 302, 308, 314, 318, 323, 327, 334,
+ 342, 345, 348, 351, 354, 357, 360, 363, 366, 369,
+ 372, 375, 378, 381, 384, 387, 390, 393, 396, 401,
+ 435, 438
};
#endif
@@ -660,13 +628,13 @@ static const char *const yytname[] =
"tDST", "tHOUR_UNIT", "tID", "tMERIDIAN", "tMINUTE_UNIT", "tMONTH",
"tMONTH_UNIT", "tSEC_UNIT", "tSNUMBER", "tUNUMBER", "tYEAR_UNIT",
"tZONE", "':'", "','", "'/'", "$accept", "spec", "item", "time", "zone",
- "day", "date", "rel", "relunit", "number", "o_merid", YY_NULL
+ "day", "date", "rel", "relunit", "number", "o_merid", YY_NULLPTR
};
#endif
# ifdef YYPRINT
-/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
- token YYLEX-NUM. */
+/* YYTOKNUM[NUM] -- (External) token number corresponding to the
+ (internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
@@ -675,52 +643,18 @@ static const yytype_uint16 yytoknum[] =
};
# endif
-/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
-static const yytype_uint8 yyr1[] =
-{
- 0, 22, 23, 23, 24, 24, 24, 24, 24, 24,
- 25, 25, 25, 25, 25, 26, 26, 26, 27, 27,
- 27, 28, 28, 28, 28, 28, 28, 28, 28, 29,
- 29, 30, 30, 30, 30, 30, 30, 30, 30, 30,
- 30, 30, 30, 30, 30, 30, 30, 30, 30, 31,
- 32, 32
-};
+#define YYPACT_NINF -20
-/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
-static const yytype_uint8 yyr2[] =
-{
- 0, 2, 0, 2, 1, 1, 1, 1, 1, 1,
- 2, 4, 4, 6, 6, 1, 1, 2, 1, 2,
- 2, 3, 5, 3, 3, 2, 4, 2, 3, 2,
- 1, 2, 2, 1, 2, 2, 1, 2, 2, 1,
- 2, 2, 1, 2, 2, 1, 2, 2, 1, 1,
- 0, 1
-};
+#define yypact_value_is_default(Yystate) \
+ (!!((Yystate) == (-20)))
-/* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM.
- Performed when YYTABLE doesn't specify something else to do. Zero
- means the default is an error. */
-static const yytype_uint8 yydefact[] =
-{
- 2, 0, 1, 18, 39, 16, 42, 45, 0, 36,
- 48, 0, 49, 33, 15, 3, 4, 5, 7, 6,
- 8, 30, 9, 19, 25, 38, 41, 44, 35, 47,
- 32, 20, 37, 40, 10, 43, 27, 34, 46, 0,
- 31, 0, 0, 17, 29, 0, 24, 28, 23, 50,
- 21, 26, 51, 12, 0, 11, 0, 50, 22, 14,
- 13
-};
+#define YYTABLE_NINF -1
-/* YYDEFGOTO[NTERM-NUM]. */
-static const yytype_int8 yydefgoto[] =
-{
- -1, 1, 15, 16, 17, 18, 19, 20, 21, 22,
- 55
-};
+#define yytable_value_is_error(Yytable_value) \
+ 0
-/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
- STATE-NUM. */
-#define YYPACT_NINF -20
+ /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+ STATE-NUM. */
static const yytype_int8 yypact[] =
{
-20, 0, -20, -19, -20, -20, -20, -20, -13, -20,
@@ -732,17 +666,37 @@ static const yytype_int8 yypact[] =
-20
};
-/* YYPGOTO[NTERM-NUM]. */
+ /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
+ Performed when YYTABLE does not specify something else to do. Zero
+ means the default is an error. */
+static const yytype_uint8 yydefact[] =
+{
+ 2, 0, 1, 18, 39, 16, 42, 45, 0, 36,
+ 48, 0, 49, 33, 15, 3, 4, 5, 7, 6,
+ 8, 30, 9, 19, 25, 38, 41, 44, 35, 47,
+ 32, 20, 37, 40, 10, 43, 27, 34, 46, 0,
+ 31, 0, 0, 17, 29, 0, 24, 28, 23, 50,
+ 21, 26, 51, 12, 0, 11, 0, 50, 22, 14,
+ 13
+};
+
+ /* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-20, -20, -20, -20, -20, -20, -20, -20, -20, -20,
-7
};
-/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
- positive, shift that token. If negative, reduce the rule which
- number is the opposite. If YYTABLE_NINF, syntax error. */
-#define YYTABLE_NINF -1
+ /* YYDEFGOTO[NTERM-NUM]. */
+static const yytype_int8 yydefgoto[] =
+{
+ -1, 1, 15, 16, 17, 18, 19, 20, 21, 22,
+ 55
+};
+
+ /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
+ positive, shift that token. If negative, reduce the rule whose
+ number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_uint8 yytable[] =
{
2, 23, 52, 24, 3, 4, 5, 59, 6, 46,
@@ -753,12 +707,6 @@ static const yytype_uint8 yytable[] =
60
};
-#define yypact_value_is_default(Yystate) \
- (!!((Yystate) == (-20)))
-
-#define yytable_value_is_error(Yytable_value) \
- YYID (0)
-
static const yytype_uint8 yycheck[] =
{
0, 20, 10, 16, 4, 5, 6, 15, 8, 15,
@@ -769,8 +717,8 @@ static const yytype_uint8 yycheck[] =
57
};
-/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
- symbol of state STATE-NUM. */
+ /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+ symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 23, 0, 4, 5, 6, 8, 11, 12, 13,
@@ -782,30 +730,38 @@ static const yytype_uint8 yystos[] =
32
};
-#define yyerrok (yyerrstatus = 0)
-#define yyclearin (yychar = YYEMPTY)
-#define YYEMPTY (-2)
-#define YYEOF 0
-
-#define YYACCEPT goto yyacceptlab
-#define YYABORT goto yyabortlab
-#define YYERROR goto yyerrorlab
-
-
-/* Like YYERROR except do call yyerror. This remains here temporarily
- to ease the transition to the new meaning of YYERROR, for GCC.
- Once GCC version 2 has supplanted version 1, this can go. However,
- YYFAIL appears to be in use. Nevertheless, it is formally deprecated
- in Bison 2.4.2's NEWS entry, where a plan to phase it out is
- discussed. */
-
-#define YYFAIL goto yyerrlab
-#if defined YYFAIL
- /* This is here to suppress warnings from the GCC cpp's
- -Wunused-macros. Normally we don't worry about that warning, but
- some users do, and we want to make it easy for users to remove
- YYFAIL uses, which will produce warnings from Bison 2.5. */
-#endif
+ /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
+static const yytype_uint8 yyr1[] =
+{
+ 0, 22, 23, 23, 24, 24, 24, 24, 24, 24,
+ 25, 25, 25, 25, 25, 26, 26, 26, 27, 27,
+ 27, 28, 28, 28, 28, 28, 28, 28, 28, 29,
+ 29, 30, 30, 30, 30, 30, 30, 30, 30, 30,
+ 30, 30, 30, 30, 30, 30, 30, 30, 30, 31,
+ 32, 32
+};
+
+ /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
+static const yytype_uint8 yyr2[] =
+{
+ 0, 2, 0, 2, 1, 1, 1, 1, 1, 1,
+ 2, 4, 4, 6, 6, 1, 1, 2, 1, 2,
+ 2, 3, 5, 3, 3, 2, 4, 2, 3, 2,
+ 1, 2, 2, 1, 2, 2, 1, 2, 2, 1,
+ 2, 2, 1, 2, 2, 1, 2, 2, 1, 1,
+ 0, 1
+};
+
+
+#define yyerrok (yyerrstatus = 0)
+#define yyclearin (yychar = YYEMPTY)
+#define YYEMPTY (-2)
+#define YYEOF 0
+
+#define YYACCEPT goto yyacceptlab
+#define YYABORT goto yyabortlab
+#define YYERROR goto yyerrorlab
+
#define YYRECOVERING() (!!yyerrstatus)
@@ -822,28 +778,16 @@ do \
else \
{ \
yyerror (YY_("syntax error: cannot back up")); \
- YYERROR; \
- } \
-while (YYID (0))
+ YYERROR; \
+ } \
+while (0)
/* Error token number */
-#define YYTERROR 1
-#define YYERRCODE 256
-
+#define YYTERROR 1
+#define YYERRCODE 256
-/* This macro is provided for backward compatibility. */
-#ifndef YY_LOCATION_PRINT
-# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
-#endif
-/* YYLEX -- calling `yylex' with the right arguments. */
-#ifdef YYLEX_PARAM
-# define YYLEX yylex (YYLEX_PARAM)
-#else
-# define YYLEX yylex ()
-#endif
-
/* Enable debugging if requested. */
#if YYDEBUG
@@ -852,40 +796,36 @@ while (YYID (0))
# define YYFPRINTF fprintf
# endif
-# define YYDPRINTF(Args) \
-do { \
- if (yydebug) \
- YYFPRINTF Args; \
-} while (YYID (0))
+# define YYDPRINTF(Args) \
+do { \
+ if (yydebug) \
+ YYFPRINTF Args; \
+} while (0)
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
-do { \
- if (yydebug) \
- { \
- YYFPRINTF (stderr, "%s ", Title); \
- yy_symbol_print (stderr, \
- Type, Value); \
- YYFPRINTF (stderr, "\n"); \
- } \
-} while (YYID (0))
+/* This macro is provided for backward compatibility. */
+#ifndef YY_LOCATION_PRINT
+# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+#endif
-/*--------------------------------.
-| Print this symbol on YYOUTPUT. |
-`--------------------------------*/
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
+do { \
+ if (yydebug) \
+ { \
+ YYFPRINTF (stderr, "%s ", Title); \
+ yy_symbol_print (stderr, \
+ Type, Value); \
+ YYFPRINTF (stderr, "\n"); \
+ } \
+} while (0)
+
+
+/*----------------------------------------.
+| Print this symbol's value on YYOUTPUT. |
+`----------------------------------------*/
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
-#else
-static void
-yy_symbol_value_print (yyoutput, yytype, yyvaluep)
- FILE *yyoutput;
- int yytype;
- YYSTYPE const * const yyvaluep;
-#endif
{
FILE *yyo = yyoutput;
YYUSE (yyo);
@@ -894,14 +834,8 @@ yy_symbol_value_print (yyoutput, yytype, yyvaluep)
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
-# else
- YYUSE (yyoutput);
# endif
- switch (yytype)
- {
- default:
- break;
- }
+ YYUSE (yytype);
}
@@ -909,22 +843,11 @@ yy_symbol_value_print (yyoutput, yytype, yyvaluep)
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
-#else
-static void
-yy_symbol_print (yyoutput, yytype, yyvaluep)
- FILE *yyoutput;
- int yytype;
- YYSTYPE const * const yyvaluep;
-#endif
{
- if (yytype < YYNTOKENS)
- YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
- else
- YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
+ YYFPRINTF (yyoutput, "%s %s (",
+ yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep);
YYFPRINTF (yyoutput, ")");
@@ -935,16 +858,8 @@ yy_symbol_print (yyoutput, yytype, yyvaluep)
| TOP (included). |
`------------------------------------------------------------------*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
-#else
-static void
-yy_stack_print (yybottom, yytop)
- yytype_int16 *yybottom;
- yytype_int16 *yytop;
-#endif
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
@@ -955,49 +870,42 @@ yy_stack_print (yybottom, yytop)
YYFPRINTF (stderr, "\n");
}
-# define YY_STACK_PRINT(Bottom, Top) \
-do { \
- if (yydebug) \
- yy_stack_print ((Bottom), (Top)); \
-} while (YYID (0))
+# define YY_STACK_PRINT(Bottom, Top) \
+do { \
+ if (yydebug) \
+ yy_stack_print ((Bottom), (Top)); \
+} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-static void
-yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
-#else
static void
-yy_reduce_print (yyvsp, yyrule)
- YYSTYPE *yyvsp;
- int yyrule;
-#endif
+yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule)
{
+ unsigned long int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
- unsigned long int yylno = yyrline[yyrule];
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
- yyrule - 1, yylno);
+ yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
- yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
- &(yyvsp[(yyi + 1) - (yynrhs)])
- );
+ yy_symbol_print (stderr,
+ yystos[yyssp[yyi + 1 - yynrhs]],
+ &(yyvsp[(yyi + 1) - (yynrhs)])
+ );
YYFPRINTF (stderr, "\n");
}
}
-# define YY_REDUCE_PRINT(Rule) \
-do { \
- if (yydebug) \
- yy_reduce_print (yyvsp, Rule); \
-} while (YYID (0))
+# define YY_REDUCE_PRINT(Rule) \
+do { \
+ if (yydebug) \
+ yy_reduce_print (yyssp, yyvsp, Rule); \
+} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
@@ -1011,7 +919,7 @@ int yydebug;
/* YYINITDEPTH -- initial size of the parser's stacks. */
-#ifndef YYINITDEPTH
+#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
@@ -1034,15 +942,8 @@ int yydebug;
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
static YYSIZE_T
yystrlen (const char *yystr)
-#else
-static YYSIZE_T
-yystrlen (yystr)
- const char *yystr;
-#endif
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
@@ -1058,16 +959,8 @@ yystrlen (yystr)
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
static char *
yystpcpy (char *yydest, const char *yysrc)
-#else
-static char *
-yystpcpy (yydest, yysrc)
- char *yydest;
- const char *yysrc;
-#endif
{
char *yyd = yydest;
const char *yys = yysrc;
@@ -1097,27 +990,27 @@ yytnamerr (char *yyres, const char *yystr)
char const *yyp = yystr;
for (;;)
- switch (*++yyp)
- {
- case '\'':
- case ',':
- goto do_not_strip_quotes;
-
- case '\\':
- if (*++yyp != '\\')
- goto do_not_strip_quotes;
- /* Fall through. */
- default:
- if (yyres)
- yyres[yyn] = *yyp;
- yyn++;
- break;
-
- case '"':
- if (yyres)
- yyres[yyn] = '\0';
- return yyn;
- }
+ switch (*++yyp)
+ {
+ case '\'':
+ case ',':
+ goto do_not_strip_quotes;
+
+ case '\\':
+ if (*++yyp != '\\')
+ goto do_not_strip_quotes;
+ /* Fall through. */
+ default:
+ if (yyres)
+ yyres[yyn] = *yyp;
+ yyn++;
+ break;
+
+ case '"':
+ if (yyres)
+ yyres[yyn] = '\0';
+ return yyn;
+ }
do_not_strip_quotes: ;
}
@@ -1140,11 +1033,11 @@ static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
- YYSIZE_T yysize0 = yytnamerr (YY_NULL, yytname[yytoken]);
+ YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
- const char *yyformat = YY_NULL;
+ const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
@@ -1152,10 +1045,6 @@ yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
int yycount = 0;
/* There are many possibilities here to consider:
- - Assume YYFAIL is not used. It's too flawed to consider. See
- <http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html>
- for details. YYERROR is fine as it does not invoke this
- function.
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
@@ -1205,7 +1094,7 @@ yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
}
yyarg[yycount++] = yytname[yyx];
{
- YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULL, yytname[yyx]);
+ YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
@@ -1272,31 +1161,17 @@ yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
-#else
-static void
-yydestruct (yymsg, yytype, yyvaluep)
- const char *yymsg;
- int yytype;
- YYSTYPE *yyvaluep;
-#endif
{
YYUSE (yyvaluep);
-
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
- switch (yytype)
- {
-
- default:
- break;
- }
+ YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+ YYUSE (yytype);
+ YY_IGNORE_MAYBE_UNINITIALIZED_END
}
@@ -1305,18 +1180,8 @@ yydestruct (yymsg, yytype, yyvaluep)
/* The lookahead symbol. */
int yychar;
-
-#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
-# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
-# define YY_IGNORE_MAYBE_UNINITIALIZED_END
-#endif
-#ifndef YY_INITIAL_VALUE
-# define YY_INITIAL_VALUE(Value) /* Nothing. */
-#endif
-
/* The semantic value of the lookahead symbol. */
-YYSTYPE yylval YY_INITIAL_VALUE(yyval_default);
-
+YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
@@ -1325,35 +1190,16 @@ int yynerrs;
| yyparse. |
`----------*/
-#ifdef YYPARSE_PARAM
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
-int
-yyparse (void *YYPARSE_PARAM)
-#else
-int
-yyparse (YYPARSE_PARAM)
- void *YYPARSE_PARAM;
-#endif
-#else /* ! YYPARSE_PARAM */
-#if (defined __STDC__ || defined __C99__FUNC__ \
- || defined __cplusplus || defined _MSC_VER)
int
yyparse (void)
-#else
-int
-yyparse ()
-
-#endif
-#endif
{
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
- `yyss': related to states.
- `yyvs': related to semantic values.
+ 'yyss': related to states.
+ 'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
@@ -1421,23 +1267,23 @@ yyparse ()
#ifdef yyoverflow
{
- /* Give user a chance to reallocate the stack. Use copies of
- these so that the &'s don't force the real ones into
- memory. */
- YYSTYPE *yyvs1 = yyvs;
- yytype_int16 *yyss1 = yyss;
-
- /* Each stack pointer address is followed by the size of the
- data in use in that stack, in bytes. This used to be a
- conditional around just the two extra args, but that might
- be undefined if yyoverflow is a macro. */
- yyoverflow (YY_("memory exhausted"),
- &yyss1, yysize * sizeof (*yyssp),
- &yyvs1, yysize * sizeof (*yyvsp),
- &yystacksize);
-
- yyss = yyss1;
- yyvs = yyvs1;
+ /* Give user a chance to reallocate the stack. Use copies of
+ these so that the &'s don't force the real ones into
+ memory. */
+ YYSTYPE *yyvs1 = yyvs;
+ yytype_int16 *yyss1 = yyss;
+
+ /* Each stack pointer address is followed by the size of the
+ data in use in that stack, in bytes. This used to be a
+ conditional around just the two extra args, but that might
+ be undefined if yyoverflow is a macro. */
+ yyoverflow (YY_("memory exhausted"),
+ &yyss1, yysize * sizeof (*yyssp),
+ &yyvs1, yysize * sizeof (*yyvsp),
+ &yystacksize);
+
+ yyss = yyss1;
+ yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
@@ -1445,22 +1291,22 @@ yyparse ()
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
- goto yyexhaustedlab;
+ goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
- yystacksize = YYMAXDEPTH;
+ yystacksize = YYMAXDEPTH;
{
- yytype_int16 *yyss1 = yyss;
- union yyalloc *yyptr =
- (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
- if (! yyptr)
- goto yyexhaustedlab;
- YYSTACK_RELOCATE (yyss_alloc, yyss);
- YYSTACK_RELOCATE (yyvs_alloc, yyvs);
+ yytype_int16 *yyss1 = yyss;
+ union yyalloc *yyptr =
+ (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+ if (! yyptr)
+ goto yyexhaustedlab;
+ YYSTACK_RELOCATE (yyss_alloc, yyss);
+ YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
- if (yyss1 != yyssa)
- YYSTACK_FREE (yyss1);
+ if (yyss1 != yyssa)
+ YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
@@ -1469,10 +1315,10 @@ yyparse ()
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
- (unsigned long int) yystacksize));
+ (unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
- YYABORT;
+ YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
@@ -1501,7 +1347,7 @@ yybackup:
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
- yychar = YYLEX;
+ yychar = yylex ();
}
if (yychar <= YYEOF)
@@ -1566,7 +1412,7 @@ yyreduce:
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
- `$$ = $1'.
+ '$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
@@ -1580,253 +1426,252 @@ yyreduce:
switch (yyn)
{
case 4:
-/* Line 1792 of yacc.c */
-#line 202 "getdate.y"
+#line 197 "getdate.y" /* yacc.c:1646 */
{
yyHaveTime++;
}
+#line 1434 "getdate.c" /* yacc.c:1646 */
break;
case 5:
-/* Line 1792 of yacc.c */
-#line 205 "getdate.y"
+#line 200 "getdate.y" /* yacc.c:1646 */
{
yyHaveZone++;
}
+#line 1442 "getdate.c" /* yacc.c:1646 */
break;
case 6:
-/* Line 1792 of yacc.c */
-#line 208 "getdate.y"
+#line 203 "getdate.y" /* yacc.c:1646 */
{
yyHaveDate++;
}
+#line 1450 "getdate.c" /* yacc.c:1646 */
break;
case 7:
-/* Line 1792 of yacc.c */
-#line 211 "getdate.y"
+#line 206 "getdate.y" /* yacc.c:1646 */
{
yyHaveDay++;
}
+#line 1458 "getdate.c" /* yacc.c:1646 */
break;
case 8:
-/* Line 1792 of yacc.c */
-#line 214 "getdate.y"
+#line 209 "getdate.y" /* yacc.c:1646 */
{
yyHaveRel++;
}
+#line 1466 "getdate.c" /* yacc.c:1646 */
break;
case 10:
-/* Line 1792 of yacc.c */
-#line 220 "getdate.y"
+#line 215 "getdate.y" /* yacc.c:1646 */
{
- yyHour = (yyvsp[(1) - (2)].Number);
+ yyHour = (yyvsp[-1].Number);
yyMinutes = 0;
yySeconds = 0;
- yyMeridian = (yyvsp[(2) - (2)].Meridian);
+ yyMeridian = (yyvsp[0].Meridian);
}
+#line 1477 "getdate.c" /* yacc.c:1646 */
break;
case 11:
-/* Line 1792 of yacc.c */
-#line 226 "getdate.y"
+#line 221 "getdate.y" /* yacc.c:1646 */
{
- yyHour = (yyvsp[(1) - (4)].Number);
- yyMinutes = (yyvsp[(3) - (4)].Number);
+ yyHour = (yyvsp[-3].Number);
+ yyMinutes = (yyvsp[-1].Number);
yySeconds = 0;
- yyMeridian = (yyvsp[(4) - (4)].Meridian);
+ yyMeridian = (yyvsp[0].Meridian);
}
+#line 1488 "getdate.c" /* yacc.c:1646 */
break;
case 12:
-/* Line 1792 of yacc.c */
-#line 232 "getdate.y"
+#line 227 "getdate.y" /* yacc.c:1646 */
{
- yyHour = (yyvsp[(1) - (4)].Number);
- yyMinutes = (yyvsp[(3) - (4)].Number);
+ yyHour = (yyvsp[-3].Number);
+ yyMinutes = (yyvsp[-1].Number);
yyMeridian = MER24;
yyHaveZone++;
- yyTimezone = ((yyvsp[(4) - (4)].Number) < 0
- ? -(yyvsp[(4) - (4)].Number) % 100 + (-(yyvsp[(4) - (4)].Number) / 100) * 60
- : - ((yyvsp[(4) - (4)].Number) % 100 + ((yyvsp[(4) - (4)].Number) / 100) * 60));
+ yyTimezone = ((yyvsp[0].Number) < 0
+ ? -(yyvsp[0].Number) % 100 + (-(yyvsp[0].Number) / 100) * 60
+ : - ((yyvsp[0].Number) % 100 + ((yyvsp[0].Number) / 100) * 60));
}
+#line 1502 "getdate.c" /* yacc.c:1646 */
break;
case 13:
-/* Line 1792 of yacc.c */
-#line 241 "getdate.y"
+#line 236 "getdate.y" /* yacc.c:1646 */
{
- yyHour = (yyvsp[(1) - (6)].Number);
- yyMinutes = (yyvsp[(3) - (6)].Number);
- yySeconds = (yyvsp[(5) - (6)].Number);
- yyMeridian = (yyvsp[(6) - (6)].Meridian);
+ yyHour = (yyvsp[-5].Number);
+ yyMinutes = (yyvsp[-3].Number);
+ yySeconds = (yyvsp[-1].Number);
+ yyMeridian = (yyvsp[0].Meridian);
}
+#line 1513 "getdate.c" /* yacc.c:1646 */
break;
case 14:
-/* Line 1792 of yacc.c */
-#line 247 "getdate.y"
+#line 242 "getdate.y" /* yacc.c:1646 */
{
- yyHour = (yyvsp[(1) - (6)].Number);
- yyMinutes = (yyvsp[(3) - (6)].Number);
- yySeconds = (yyvsp[(5) - (6)].Number);
+ yyHour = (yyvsp[-5].Number);
+ yyMinutes = (yyvsp[-3].Number);
+ yySeconds = (yyvsp[-1].Number);
yyMeridian = MER24;
yyHaveZone++;
- yyTimezone = ((yyvsp[(6) - (6)].Number) < 0
- ? -(yyvsp[(6) - (6)].Number) % 100 + (-(yyvsp[(6) - (6)].Number) / 100) * 60
- : - ((yyvsp[(6) - (6)].Number) % 100 + ((yyvsp[(6) - (6)].Number) / 100) * 60));
+ yyTimezone = ((yyvsp[0].Number) < 0
+ ? -(yyvsp[0].Number) % 100 + (-(yyvsp[0].Number) / 100) * 60
+ : - ((yyvsp[0].Number) % 100 + ((yyvsp[0].Number) / 100) * 60));
}
+#line 1528 "getdate.c" /* yacc.c:1646 */
break;
case 15:
-/* Line 1792 of yacc.c */
-#line 259 "getdate.y"
+#line 254 "getdate.y" /* yacc.c:1646 */
{
- yyTimezone = (yyvsp[(1) - (1)].Number);
+ yyTimezone = (yyvsp[0].Number);
}
+#line 1536 "getdate.c" /* yacc.c:1646 */
break;
case 16:
-/* Line 1792 of yacc.c */
-#line 262 "getdate.y"
+#line 257 "getdate.y" /* yacc.c:1646 */
{
- yyTimezone = (yyvsp[(1) - (1)].Number) - 60;
+ yyTimezone = (yyvsp[0].Number) - 60;
}
+#line 1544 "getdate.c" /* yacc.c:1646 */
break;
case 17:
-/* Line 1792 of yacc.c */
-#line 266 "getdate.y"
+#line 261 "getdate.y" /* yacc.c:1646 */
{
- yyTimezone = (yyvsp[(1) - (2)].Number) - 60;
+ yyTimezone = (yyvsp[-1].Number) - 60;
}
+#line 1552 "getdate.c" /* yacc.c:1646 */
break;
case 18:
-/* Line 1792 of yacc.c */
-#line 271 "getdate.y"
+#line 266 "getdate.y" /* yacc.c:1646 */
{
yyDayOrdinal = 1;
- yyDayNumber = (yyvsp[(1) - (1)].Number);
+ yyDayNumber = (yyvsp[0].Number);
}
+#line 1561 "getdate.c" /* yacc.c:1646 */
break;
case 19:
-/* Line 1792 of yacc.c */
-#line 275 "getdate.y"
+#line 270 "getdate.y" /* yacc.c:1646 */
{
yyDayOrdinal = 1;
- yyDayNumber = (yyvsp[(1) - (2)].Number);
+ yyDayNumber = (yyvsp[-1].Number);
}
+#line 1570 "getdate.c" /* yacc.c:1646 */
break;
case 20:
-/* Line 1792 of yacc.c */
-#line 279 "getdate.y"
+#line 274 "getdate.y" /* yacc.c:1646 */
{
- yyDayOrdinal = (yyvsp[(1) - (2)].Number);
- yyDayNumber = (yyvsp[(2) - (2)].Number);
+ yyDayOrdinal = (yyvsp[-1].Number);
+ yyDayNumber = (yyvsp[0].Number);
}
+#line 1579 "getdate.c" /* yacc.c:1646 */
break;
case 21:
-/* Line 1792 of yacc.c */
-#line 285 "getdate.y"
+#line 280 "getdate.y" /* yacc.c:1646 */
{
- yyMonth = (yyvsp[(1) - (3)].Number);
- yyDay = (yyvsp[(3) - (3)].Number);
+ yyMonth = (yyvsp[-2].Number);
+ yyDay = (yyvsp[0].Number);
}
+#line 1588 "getdate.c" /* yacc.c:1646 */
break;
case 22:
-/* Line 1792 of yacc.c */
-#line 289 "getdate.y"
+#line 284 "getdate.y" /* yacc.c:1646 */
{
/* Interpret as YYYY/MM/DD if $1 >= 1000, otherwise as MM/DD/YY.
The goal in recognizing YYYY/MM/DD is solely to support legacy
machine-generated dates like those in an RCS log listing. If
you want portability, use the ISO 8601 format. */
- if ((yyvsp[(1) - (5)].Number) >= 1000)
+ if ((yyvsp[-4].Number) >= 1000)
{
- yyYear = (yyvsp[(1) - (5)].Number);
- yyMonth = (yyvsp[(3) - (5)].Number);
- yyDay = (yyvsp[(5) - (5)].Number);
+ yyYear = (yyvsp[-4].Number);
+ yyMonth = (yyvsp[-2].Number);
+ yyDay = (yyvsp[0].Number);
}
else
{
- yyMonth = (yyvsp[(1) - (5)].Number);
- yyDay = (yyvsp[(3) - (5)].Number);
- yyYear = (yyvsp[(5) - (5)].Number);
+ yyMonth = (yyvsp[-4].Number);
+ yyDay = (yyvsp[-2].Number);
+ yyYear = (yyvsp[0].Number);
}
}
+#line 1611 "getdate.c" /* yacc.c:1646 */
break;
case 23:
-/* Line 1792 of yacc.c */
-#line 307 "getdate.y"
+#line 302 "getdate.y" /* yacc.c:1646 */
{
/* ISO 8601 format. yyyy-mm-dd. */
- yyYear = (yyvsp[(1) - (3)].Number);
- yyMonth = -(yyvsp[(2) - (3)].Number);
- yyDay = -(yyvsp[(3) - (3)].Number);
+ yyYear = (yyvsp[-2].Number);
+ yyMonth = -(yyvsp[-1].Number);
+ yyDay = -(yyvsp[0].Number);
}
+#line 1622 "getdate.c" /* yacc.c:1646 */
break;
case 24:
-/* Line 1792 of yacc.c */
-#line 313 "getdate.y"
+#line 308 "getdate.y" /* yacc.c:1646 */
{
/* e.g. 17-JUN-1992. */
- yyDay = (yyvsp[(1) - (3)].Number);
- yyMonth = (yyvsp[(2) - (3)].Number);
- yyYear = -(yyvsp[(3) - (3)].Number);
+ yyDay = (yyvsp[-2].Number);
+ yyMonth = (yyvsp[-1].Number);
+ yyYear = -(yyvsp[0].Number);
}
+#line 1633 "getdate.c" /* yacc.c:1646 */
break;
case 25:
-/* Line 1792 of yacc.c */
-#line 319 "getdate.y"
+#line 314 "getdate.y" /* yacc.c:1646 */
{
- yyMonth = (yyvsp[(1) - (2)].Number);
- yyDay = (yyvsp[(2) - (2)].Number);
+ yyMonth = (yyvsp[-1].Number);
+ yyDay = (yyvsp[0].Number);
}
+#line 1642 "getdate.c" /* yacc.c:1646 */
break;
case 26:
-/* Line 1792 of yacc.c */
-#line 323 "getdate.y"
+#line 318 "getdate.y" /* yacc.c:1646 */
{
- yyMonth = (yyvsp[(1) - (4)].Number);
- yyDay = (yyvsp[(2) - (4)].Number);
- yyYear = (yyvsp[(4) - (4)].Number);
+ yyMonth = (yyvsp[-3].Number);
+ yyDay = (yyvsp[-2].Number);
+ yyYear = (yyvsp[0].Number);
}
+#line 1652 "getdate.c" /* yacc.c:1646 */
break;
case 27:
-/* Line 1792 of yacc.c */
-#line 328 "getdate.y"
+#line 323 "getdate.y" /* yacc.c:1646 */
{
- yyMonth = (yyvsp[(2) - (2)].Number);
- yyDay = (yyvsp[(1) - (2)].Number);
+ yyMonth = (yyvsp[0].Number);
+ yyDay = (yyvsp[-1].Number);
}
+#line 1661 "getdate.c" /* yacc.c:1646 */
break;
case 28:
-/* Line 1792 of yacc.c */
-#line 332 "getdate.y"
+#line 327 "getdate.y" /* yacc.c:1646 */
{
- yyMonth = (yyvsp[(2) - (3)].Number);
- yyDay = (yyvsp[(1) - (3)].Number);
- yyYear = (yyvsp[(3) - (3)].Number);
+ yyMonth = (yyvsp[-1].Number);
+ yyDay = (yyvsp[-2].Number);
+ yyYear = (yyvsp[0].Number);
}
+#line 1671 "getdate.c" /* yacc.c:1646 */
break;
case 29:
-/* Line 1792 of yacc.c */
-#line 339 "getdate.y"
+#line 334 "getdate.y" /* yacc.c:1646 */
{
yyRelSeconds = -yyRelSeconds;
yyRelMinutes = -yyRelMinutes;
@@ -1835,206 +1680,206 @@ yyreduce:
yyRelMonth = -yyRelMonth;
yyRelYear = -yyRelYear;
}
+#line 1684 "getdate.c" /* yacc.c:1646 */
break;
case 31:
-/* Line 1792 of yacc.c */
-#line 350 "getdate.y"
+#line 345 "getdate.y" /* yacc.c:1646 */
{
- yyRelYear += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelYear += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1692 "getdate.c" /* yacc.c:1646 */
break;
case 32:
-/* Line 1792 of yacc.c */
-#line 353 "getdate.y"
+#line 348 "getdate.y" /* yacc.c:1646 */
{
- yyRelYear += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelYear += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1700 "getdate.c" /* yacc.c:1646 */
break;
case 33:
-/* Line 1792 of yacc.c */
-#line 356 "getdate.y"
+#line 351 "getdate.y" /* yacc.c:1646 */
{
- yyRelYear += (yyvsp[(1) - (1)].Number);
+ yyRelYear += (yyvsp[0].Number);
}
+#line 1708 "getdate.c" /* yacc.c:1646 */
break;
case 34:
-/* Line 1792 of yacc.c */
-#line 359 "getdate.y"
+#line 354 "getdate.y" /* yacc.c:1646 */
{
- yyRelMonth += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelMonth += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1716 "getdate.c" /* yacc.c:1646 */
break;
case 35:
-/* Line 1792 of yacc.c */
-#line 362 "getdate.y"
+#line 357 "getdate.y" /* yacc.c:1646 */
{
- yyRelMonth += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelMonth += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1724 "getdate.c" /* yacc.c:1646 */
break;
case 36:
-/* Line 1792 of yacc.c */
-#line 365 "getdate.y"
+#line 360 "getdate.y" /* yacc.c:1646 */
{
- yyRelMonth += (yyvsp[(1) - (1)].Number);
+ yyRelMonth += (yyvsp[0].Number);
}
+#line 1732 "getdate.c" /* yacc.c:1646 */
break;
case 37:
-/* Line 1792 of yacc.c */
-#line 368 "getdate.y"
+#line 363 "getdate.y" /* yacc.c:1646 */
{
- yyRelDay += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelDay += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1740 "getdate.c" /* yacc.c:1646 */
break;
case 38:
-/* Line 1792 of yacc.c */
-#line 371 "getdate.y"
+#line 366 "getdate.y" /* yacc.c:1646 */
{
- yyRelDay += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelDay += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1748 "getdate.c" /* yacc.c:1646 */
break;
case 39:
-/* Line 1792 of yacc.c */
-#line 374 "getdate.y"
+#line 369 "getdate.y" /* yacc.c:1646 */
{
- yyRelDay += (yyvsp[(1) - (1)].Number);
+ yyRelDay += (yyvsp[0].Number);
}
+#line 1756 "getdate.c" /* yacc.c:1646 */
break;
case 40:
-/* Line 1792 of yacc.c */
-#line 377 "getdate.y"
+#line 372 "getdate.y" /* yacc.c:1646 */
{
- yyRelHour += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelHour += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1764 "getdate.c" /* yacc.c:1646 */
break;
case 41:
-/* Line 1792 of yacc.c */
-#line 380 "getdate.y"
+#line 375 "getdate.y" /* yacc.c:1646 */
{
- yyRelHour += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelHour += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1772 "getdate.c" /* yacc.c:1646 */
break;
case 42:
-/* Line 1792 of yacc.c */
-#line 383 "getdate.y"
+#line 378 "getdate.y" /* yacc.c:1646 */
{
- yyRelHour += (yyvsp[(1) - (1)].Number);
+ yyRelHour += (yyvsp[0].Number);
}
+#line 1780 "getdate.c" /* yacc.c:1646 */
break;
case 43:
-/* Line 1792 of yacc.c */
-#line 386 "getdate.y"
+#line 381 "getdate.y" /* yacc.c:1646 */
{
- yyRelMinutes += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelMinutes += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1788 "getdate.c" /* yacc.c:1646 */
break;
case 44:
-/* Line 1792 of yacc.c */
-#line 389 "getdate.y"
+#line 384 "getdate.y" /* yacc.c:1646 */
{
- yyRelMinutes += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelMinutes += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1796 "getdate.c" /* yacc.c:1646 */
break;
case 45:
-/* Line 1792 of yacc.c */
-#line 392 "getdate.y"
+#line 387 "getdate.y" /* yacc.c:1646 */
{
- yyRelMinutes += (yyvsp[(1) - (1)].Number);
+ yyRelMinutes += (yyvsp[0].Number);
}
+#line 1804 "getdate.c" /* yacc.c:1646 */
break;
case 46:
-/* Line 1792 of yacc.c */
-#line 395 "getdate.y"
+#line 390 "getdate.y" /* yacc.c:1646 */
{
- yyRelSeconds += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelSeconds += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1812 "getdate.c" /* yacc.c:1646 */
break;
case 47:
-/* Line 1792 of yacc.c */
-#line 398 "getdate.y"
+#line 393 "getdate.y" /* yacc.c:1646 */
{
- yyRelSeconds += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
+ yyRelSeconds += (yyvsp[-1].Number) * (yyvsp[0].Number);
}
+#line 1820 "getdate.c" /* yacc.c:1646 */
break;
case 48:
-/* Line 1792 of yacc.c */
-#line 401 "getdate.y"
+#line 396 "getdate.y" /* yacc.c:1646 */
{
- yyRelSeconds += (yyvsp[(1) - (1)].Number);
+ yyRelSeconds += (yyvsp[0].Number);
}
+#line 1828 "getdate.c" /* yacc.c:1646 */
break;
case 49:
-/* Line 1792 of yacc.c */
-#line 407 "getdate.y"
+#line 402 "getdate.y" /* yacc.c:1646 */
{
if (yyHaveTime && yyHaveDate && !yyHaveRel)
- yyYear = (yyvsp[(1) - (1)].Number);
+ yyYear = (yyvsp[0].Number);
else
{
- if ((yyvsp[(1) - (1)].Number)>10000)
+ if ((yyvsp[0].Number)>10000)
{
yyHaveDate++;
- yyDay= ((yyvsp[(1) - (1)].Number))%100;
- yyMonth= ((yyvsp[(1) - (1)].Number)/100)%100;
- yyYear = (yyvsp[(1) - (1)].Number)/10000;
+ yyDay= ((yyvsp[0].Number))%100;
+ yyMonth= ((yyvsp[0].Number)/100)%100;
+ yyYear = (yyvsp[0].Number)/10000;
}
else
{
yyHaveTime++;
- if ((yyvsp[(1) - (1)].Number) < 100)
+ if ((yyvsp[0].Number) < 100)
{
- yyHour = (yyvsp[(1) - (1)].Number);
+ yyHour = (yyvsp[0].Number);
yyMinutes = 0;
}
else
{
- yyHour = (yyvsp[(1) - (1)].Number) / 100;
- yyMinutes = (yyvsp[(1) - (1)].Number) % 100;
+ yyHour = (yyvsp[0].Number) / 100;
+ yyMinutes = (yyvsp[0].Number) % 100;
}
yySeconds = 0;
yyMeridian = MER24;
}
}
}
+#line 1863 "getdate.c" /* yacc.c:1646 */
break;
case 50:
-/* Line 1792 of yacc.c */
-#line 440 "getdate.y"
+#line 435 "getdate.y" /* yacc.c:1646 */
{
(yyval.Meridian) = MER24;
}
+#line 1871 "getdate.c" /* yacc.c:1646 */
break;
case 51:
-/* Line 1792 of yacc.c */
-#line 444 "getdate.y"
+#line 439 "getdate.y" /* yacc.c:1646 */
{
- (yyval.Meridian) = (yyvsp[(1) - (1)].Meridian);
+ (yyval.Meridian) = (yyvsp[0].Meridian);
}
+#line 1879 "getdate.c" /* yacc.c:1646 */
break;
-/* Line 1792 of yacc.c */
-#line 2038 "getdate.c"
+#line 1883 "getdate.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
@@ -2056,7 +1901,7 @@ yyreduce:
*++yyvsp = yyval;
- /* Now `shift' the result of the reduction. Determine what state
+ /* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
@@ -2071,9 +1916,9 @@ yyreduce:
goto yynewstate;
-/*------------------------------------.
-| yyerrlab -- here on detecting error |
-`------------------------------------*/
+/*--------------------------------------.
+| yyerrlab -- here on detecting error. |
+`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
@@ -2124,20 +1969,20 @@ yyerrlab:
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
- error, discard it. */
+ error, discard it. */
if (yychar <= YYEOF)
- {
- /* Return failure if at end of input. */
- if (yychar == YYEOF)
- YYABORT;
- }
+ {
+ /* Return failure if at end of input. */
+ if (yychar == YYEOF)
+ YYABORT;
+ }
else
- {
- yydestruct ("Error: discarding",
- yytoken, &yylval);
- yychar = YYEMPTY;
- }
+ {
+ yydestruct ("Error: discarding",
+ yytoken, &yylval);
+ yychar = YYEMPTY;
+ }
}
/* Else will try to reuse lookahead token after shifting the error
@@ -2156,7 +2001,7 @@ yyerrorlab:
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
- /* Do not reclaim the symbols of the rule which action triggered
+ /* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
@@ -2169,29 +2014,29 @@ yyerrorlab:
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
- yyerrstatus = 3; /* Each real token shifted decrements this. */
+ yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
- {
- yyn += YYTERROR;
- if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
- {
- yyn = yytable[yyn];
- if (0 < yyn)
- break;
- }
- }
+ {
+ yyn += YYTERROR;
+ if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+ {
+ yyn = yytable[yyn];
+ if (0 < yyn)
+ break;
+ }
+ }
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
- YYABORT;
+ YYABORT;
yydestruct ("Error: popping",
- yystos[yystate], yyvsp);
+ yystos[yystate], yyvsp);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
@@ -2242,14 +2087,14 @@ yyreturn:
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval);
}
- /* Do not reclaim the symbols of the rule which action triggered
+ /* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
- yystos[*yyssp], yyvsp);
+ yystos[*yyssp], yyvsp);
YYPOPSTACK (1);
}
#ifndef yyoverflow
@@ -2260,13 +2105,9 @@ yyreturn:
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
- /* Make sure YYID is used. */
- return YYID (yyresult);
+ return yyresult;
}
-
-
-/* Line 2055 of yacc.c */
-#line 449 "getdate.y"
+#line 444 "getdate.y" /* yacc.c:1906 */
/* Include this file down here because bison inserts code above which
diff --git a/getdate.y b/getdate.y
index 99de9b0..f87875c 100644
--- a/getdate.y
+++ b/getdate.y
@@ -8,12 +8,7 @@
** This code is in the public domain and has no copyright.
*/
-#ifdef HAVE_CONFIG_H
-# include <config.h>
-# ifdef HAVE_ALLOCA_H
-# include <alloca.h>
-# endif
-#endif
+#include "config.h"
/* Since the code of getdate.y is not included in the Emacs executable
itself, there is no need to #define static in this file. Even if
diff --git a/hash_nss.c b/hash_nss.c
index 6e62304..71c8930 100644
--- a/hash_nss.c
+++ b/hash_nss.c
@@ -25,11 +25,12 @@
*/
+#include "config.h"
+
#include <nss.h>
#include <hasht.h>
#include <nsslowhash.h>
-/* #include "config.h" */
#include "hash.h"
static NSSLOWInitContext *ictx;
diff --git a/keys.c b/keys.c
index fcd1974..4e1df6a 100644
--- a/keys.c
+++ b/keys.c
@@ -50,72 +50,12 @@ typedef struct {
static ARR_Instance keys;
-static int command_key_valid;
-static uint32_t command_key_id;
static int cache_valid;
static uint32_t cache_key_id;
static int cache_key_pos;
/* ================================================== */
-static int
-generate_key(uint32_t key_id)
-{
-#ifdef FEAT_SECHASH
- unsigned char key[20];
- const char *hashname = "SHA1";
-#else
- unsigned char key[16];
- const char *hashname = "MD5";
-#endif
- const char *key_file, *rand_dev = "/dev/urandom";
- FILE *f;
- struct stat st;
- int i;
-
- key_file = CNF_GetKeysFile();
-
- if (!key_file)
- return 0;
-
- f = fopen(rand_dev, "r");
- if (!f || fread(key, sizeof (key), 1, f) != 1) {
- if (f)
- fclose(f);
- LOG_FATAL(LOGF_Keys, "Could not read %s", rand_dev);
- return 0;
- }
- fclose(f);
-
- f = fopen(key_file, "a");
- if (!f) {
- LOG_FATAL(LOGF_Keys, "Could not open keyfile %s for writing", key_file);
- return 0;
- }
-
- /* Make sure the keyfile is not world-readable */
- if (stat(key_file, &st) || chmod(key_file, st.st_mode & 0770)) {
- fclose(f);
- LOG_FATAL(LOGF_Keys, "Could not change permissions of keyfile %s", key_file);
- return 0;
- }
-
- fprintf(f, "\n%"PRIu32" %s HEX:", key_id, hashname);
- for (i = 0; i < sizeof (key); i++)
- fprintf(f, "%02hhX", key[i]);
- fprintf(f, "\n");
- fclose(f);
-
- /* Erase the key from stack */
- memset(key, 0, sizeof (key));
-
- LOG(LOGS_INFO, LOGF_Keys, "Generated key %"PRIu32, key_id);
-
- return 1;
-}
-
-/* ================================================== */
-
static void
free_keys(void)
{
@@ -125,7 +65,6 @@ free_keys(void)
Free(((Key *)ARR_GetElement(keys, i))->val);
ARR_SetSize(keys, 0);
- command_key_valid = 0;
cache_valid = 0;
}
@@ -135,14 +74,8 @@ void
KEY_Initialise(void)
{
keys = ARR_CreateInstance(sizeof (Key));
- command_key_valid = 0;
cache_valid = 0;
KEY_Reload();
-
- if (CNF_GetGenerateCommandKey() && !KEY_KeyKnown(KEY_GetCommandKey())) {
- if (generate_key(KEY_GetCommandKey()))
- KEY_Reload();
- }
}
/* ================================================== */
@@ -334,18 +267,6 @@ get_key_by_id(uint32_t key_id)
/* ================================================== */
-uint32_t
-KEY_GetCommandKey(void)
-{
- if (!command_key_valid) {
- command_key_id = CNF_GetCommandKey();
- }
-
- return command_key_id;
-}
-
-/* ================================================== */
-
int
KEY_KeyKnown(uint32_t key_id)
{
diff --git a/keys.h b/keys.h
index 58f28cb..e6e51aa 100644
--- a/keys.h
+++ b/keys.h
@@ -34,8 +34,6 @@ extern void KEY_Finalise(void);
extern void KEY_Reload(void);
-extern uint32_t KEY_GetCommandKey(void);
-
extern int KEY_GetKey(uint32_t key_id, char **key, int *len);
extern int KEY_KeyKnown(uint32_t key_id);
extern int KEY_GetAuthDelay(uint32_t key_id);
diff --git a/logging.c b/logging.c
index 2aff130..7eb680d 100644
--- a/logging.c
+++ b/logging.c
@@ -31,7 +31,6 @@
#include "conf.h"
#include "logging.h"
-#include "mkdirpp.h"
#include "util.h"
/* This is used by DEBUG_LOG macro */
@@ -49,10 +48,6 @@ static int parent_fd = 0;
#define DEBUG_LEVEL_PRINT_DEBUG 2
static int debug_level = 0;
-#ifdef WINNT
-static FILE *logfile;
-#endif
-
struct LogFile {
const char *name;
const char *banner;
@@ -74,10 +69,6 @@ void
LOG_Initialise(void)
{
initialised = 1;
-
-#ifdef WINNT
- logfile = fopen("./chronyd.err", "a");
-#endif
}
/* ================================================== */
@@ -86,15 +77,9 @@ LOG_Initialise(void)
void
LOG_Finalise(void)
{
-#ifdef WINNT
- if (logfile) {
- fclose(logfile);
- }
-#else
if (system_log) {
closelog();
}
-#endif
LOG_CycleLogFiles();
@@ -105,11 +90,6 @@ LOG_Finalise(void)
static void log_message(int fatal, LOG_Severity severity, const char *message)
{
-#ifdef WINNT
- if (logfile) {
- fprintf(logfile, fatal ? "Fatal error : %s\n" : "%s\n", message);
- }
-#else
if (system_log) {
int priority;
switch (severity) {
@@ -135,32 +115,33 @@ static void log_message(int fatal, LOG_Severity severity, const char *message)
} else {
fprintf(stderr, fatal ? "Fatal error : %s\n" : "%s\n", message);
}
-#endif
}
/* ================================================== */
-void LOG_Message(LOG_Severity severity, LOG_Facility facility,
- int line_number, const char *filename,
- const char *function_name, const char *format, ...)
+void LOG_Message(LOG_Severity severity,
+#if DEBUG > 0
+ LOG_Facility facility, int line_number,
+ const char *filename, const char *function_name,
+#endif
+ const char *format, ...)
{
char buf[2048];
va_list other_args;
time_t t;
struct tm stm;
-#ifdef WINNT
-#else
if (!system_log) {
/* Don't clutter up syslog with timestamps and internal debugging info */
time(&t);
stm = *gmtime(&t);
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &stm);
fprintf(stderr, "%s ", buf);
+#if DEBUG > 0
if (debug_level >= DEBUG_LEVEL_PRINT_FUNCTION)
fprintf(stderr, "%s:%d:(%s) ", filename, line_number, function_name);
- }
#endif
+ }
va_start(other_args, format);
vsnprintf(buf, sizeof(buf), format, other_args);
@@ -198,11 +179,8 @@ void LOG_Message(LOG_Severity severity, LOG_Facility facility,
void
LOG_OpenSystemLog(void)
{
-#ifdef WINNT
-#else
system_log = 1;
openlog("chronyd", LOG_PID, LOG_DAEMON);
-#endif
}
/* ================================================== */
@@ -301,20 +279,6 @@ LOG_FileWrite(LOG_FileID id, const char *format, ...)
/* ================================================== */
void
-LOG_CreateLogFileDir(void)
-{
- const char *logdir;
-
- logdir = CNF_GetLogDir();
-
- if (!mkdir_and_parents(logdir)) {
- LOG(LOGS_ERR, LOGF_Logging, "Could not create directory %s", logdir);
- }
-}
-
-/* ================================================== */
-
-void
LOG_CycleLogFiles(void)
{
LOG_FileID i;
diff --git a/logging.h b/logging.h
index b4b4d18..b480c42 100644
--- a/logging.h
+++ b/logging.h
@@ -3,7 +3,7 @@
**********************************************************************
* Copyright (C) Richard P. Curnow 1997-2002
- * Copyright (C) Miroslav Lichvar 2013-2014
+ * Copyright (C) Miroslav Lichvar 2013-2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
@@ -45,18 +45,28 @@ extern int log_debug_enabled;
#define FORMAT_ATTRIBUTE_PRINTF(str, first)
#endif
+#if DEBUG > 0
+#define LOG_MESSAGE(severity, facility, ...) \
+ LOG_Message(severity, facility, __LINE__, __FILE__, FUNCTION_NAME, __VA_ARGS__);
+#else
+#define LOG_MESSAGE(severity, facility, ...) \
+ LOG_Message(severity, __VA_ARGS__);
+#endif
+
#define DEBUG_LOG(facility, ...) \
do { \
if (DEBUG && log_debug_enabled) \
- LOG_Message(LOGS_DEBUG, facility, __LINE__, __FILE__, FUNCTION_NAME, __VA_ARGS__); \
+ LOG_MESSAGE(LOGS_DEBUG, facility, __VA_ARGS__); \
} while (0)
-#define LOG(severity, facility, ...) LOG_Message(severity, facility, __LINE__, __FILE__, FUNCTION_NAME, __VA_ARGS__)
+
#define LOG_FATAL(facility, ...) \
do { \
- LOG_Message(LOGS_FATAL, facility, __LINE__, __FILE__, FUNCTION_NAME, __VA_ARGS__); \
+ LOG_MESSAGE(LOGS_FATAL, facility, __VA_ARGS__); \
exit(1); \
} while (0)
+#define LOG(severity, facility, ...) LOG_MESSAGE(severity, facility, __VA_ARGS__)
+
/* Definition of severity */
typedef enum {
LOGS_INFO,
@@ -81,6 +91,7 @@ typedef enum {
LOGF_Util,
LOGF_Main,
LOGF_Memory,
+ LOGF_Client,
LOGF_ClientLog,
LOGF_Configure,
LOGF_CmdMon,
@@ -98,6 +109,7 @@ typedef enum {
LOGF_SysNetBSD,
LOGF_SysSolaris,
LOGF_SysSunOS,
+ LOGF_SysTimex,
LOGF_SysWinnt,
LOGF_TempComp,
LOGF_RtcLinux,
@@ -112,10 +124,15 @@ extern void LOG_Initialise(void);
extern void LOG_Finalise(void);
/* Line logging function */
+#if DEBUG > 0
FORMAT_ATTRIBUTE_PRINTF(6, 7)
extern void LOG_Message(LOG_Severity severity, LOG_Facility facility,
int line_number, const char *filename,
const char *function_name, const char *format, ...);
+#else
+FORMAT_ATTRIBUTE_PRINTF(2, 3)
+extern void LOG_Message(LOG_Severity severity, const char *format, ...);
+#endif
/* Set debug level:
0, 1 - only non-debug messages are logged
@@ -142,7 +159,6 @@ extern LOG_FileID LOG_FileOpen(const char *name, const char *banner);
FORMAT_ATTRIBUTE_PRINTF(2, 3)
extern void LOG_FileWrite(LOG_FileID id, const char *format, ...);
-extern void LOG_CreateLogFileDir(void);
extern void LOG_CycleLogFiles(void);
#endif /* GOT_LOGGING_H */
diff --git a/main.c b/main.c
index 393b12e..342704d 100644
--- a/main.c
+++ b/main.c
@@ -4,7 +4,7 @@
**********************************************************************
* Copyright (C) Richard P. Curnow 1997-2003
* Copyright (C) John G. Hasler 2009
- * Copyright (C) Miroslav Lichvar 2012-2014
+ * Copyright (C) Miroslav Lichvar 2012-2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
@@ -51,6 +51,7 @@
#include "nameserv.h"
#include "smooth.h"
#include "tempcomp.h"
+#include "util.h"
/* ================================================== */
@@ -94,10 +95,10 @@ MAI_CleanupAndExit(void)
MNL_Finalise();
CLG_Finalise();
NSR_Finalise();
+ SST_Finalise();
NCR_Finalise();
- CAM_Finalise();
NIO_Finalise();
- SST_Finalise();
+ CAM_Finalise();
KEY_Finalise();
RCL_Finalise();
SRC_Finalise();
@@ -264,7 +265,7 @@ write_lockfile(void)
if (!out) {
LOG_FATAL(LOGF_Main, "could not open lockfile %s for writing", pidfile);
} else {
- fprintf(out, "%d\n", getpid());
+ fprintf(out, "%d\n", (int)getpid());
fclose(out);
}
}
@@ -274,11 +275,6 @@ write_lockfile(void)
static void
go_daemon(void)
{
-#ifdef WINNT
-
-
-#else
-
int pid, fd, pipefd[2];
/* Create pipe which will the daemon use to notify the grandparent
@@ -337,8 +333,6 @@ go_daemon(void)
LOG_SetParentFd(pipefd[1]);
}
}
-
-#endif
}
/* ================================================== */
@@ -349,10 +343,11 @@ int main
const char *conf_file = DEFAULT_CONF_FILE;
const char *progname = argv[0];
char *user = NULL;
+ struct passwd *pw;
int debug = 0, nofork = 0, address_family = IPADDR_UNSPEC;
int do_init_rtc = 0, restarted = 0;
int other_pid;
- int lock_memory = 0, sched_priority = 0;
+ int scfilter_level = 0, lock_memory = 0, sched_priority = 0;
int system_log = 1;
int config_args = 0;
@@ -382,6 +377,10 @@ int main
} else {
user = *argv;
}
+ } else if (!strcmp("-F", *argv)) {
+ ++argv, --argc;
+ if (argc == 0 || sscanf(*argv, "%d", &scfilter_level) != 1)
+ LOG_FATAL(LOGF_Main, "Bad syscall filter level");
} else if (!strcmp("-s", *argv)) {
do_init_rtc = 1;
} else if (!strcmp("-v", *argv) || !strcmp("--version",*argv)) {
@@ -472,6 +471,12 @@ int main
RCL_Initialise();
KEY_Initialise();
+ /* Open privileged ports before dropping root */
+ CAM_Initialise(address_family);
+ NIO_Initialise(address_family);
+ NCR_Initialise();
+ CNF_SetupAccessRestrictions();
+
/* Command-line switch must have priority */
if (!sched_priority) {
sched_priority = CNF_GetSchedPriority();
@@ -487,17 +492,19 @@ int main
if (!user) {
user = CNF_GetUser();
}
- if (user && strcmp(user, "root")) {
- SYS_DropRoot(user);
- }
- LOG_CreateLogFileDir();
+ if ((pw = getpwnam(user)) == NULL)
+ LOG_FATAL(LOGF_Main, "Could not get %s uid/gid", user);
+
+ /* Create all directories before dropping root */
+ CNF_CreateDirs(pw->pw_uid, pw->pw_gid);
+
+ /* Drop root privileges if the user has non-zero uid or gid */
+ if (pw->pw_uid || pw->pw_gid)
+ SYS_DropRoot(pw->pw_uid, pw->pw_gid);
REF_Initialise();
SST_Initialise();
- NIO_Initialise(address_family);
- CAM_Initialise(address_family);
- NCR_Initialise();
NSR_Initialise();
CLG_Initialise();
MNL_Initialise();
@@ -507,7 +514,12 @@ int main
/* From now on, it is safe to do finalisation on exit */
initialised = 1;
- CNF_SetupAccessRestrictions();
+ UTI_SetQuitSignalsHandler(signal_cleanup);
+
+ CAM_OpenUnixSocket();
+
+ if (scfilter_level)
+ SYS_EnableSystemCallFilter(scfilter_level);
if (ref_mode == REF_ModeNormal && CNF_GetInitSources() > 0) {
ref_mode = REF_ModeInitStepSlew;
@@ -522,13 +534,6 @@ int main
post_init_rtc_hook(NULL);
}
- signal(SIGINT, signal_cleanup);
- signal(SIGTERM, signal_cleanup);
-#if !defined(WINNT)
- signal(SIGQUIT, signal_cleanup);
- signal(SIGHUP, signal_cleanup);
-#endif /* WINNT */
-
/* The program normally runs under control of the main loop in
the scheduler. */
SCH_MainLoop();
diff --git a/mkdirpp.c b/mkdirpp.c
deleted file mode 100644
index ed4b23d..0000000
--- a/mkdirpp.c
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- chronyd/chronyc - Programs for keeping computer clocks accurate.
-
- **********************************************************************
- * Copyright (C) Richard P. Curnow 1997-2002
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of version 2 of the GNU General Public License as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- **********************************************************************
-
- =======================================================================
-
- A function for creating a directory and any parent directories that
- don't exist.
-
- */
-
-#include "config.h"
-
-#include "sysincl.h"
-
-#include "memory.h"
-#include "mkdirpp.h"
-
-static int
-do_dir(char *p)
-{
- int status;
- struct stat buf;
-
-#if defined(TEST)
- fprintf(stderr, "do_dir(%s)\n", p);
-#endif
-
- /* See if directory exists */
- status = stat(p, &buf);
-
- if (status < 0) {
- if (errno == ENOENT) {
- /* Try to create directory */
- status = mkdir(p, 0755);
- return status;
- } else {
- return status;
- }
- }
-
- if (!S_ISDIR(buf.st_mode)) {
- return -1;
- }
-
- return 0;
-}
-
-/* ================================================== */
-/* Return 0 if the directory couldn't be created, 1 if it could (or
- already existed) */
-
-int
-mkdir_and_parents(const char *path)
-{
- char *p;
- int len;
- int i, j, k, last;
- len = strlen(path);
-
- p = (char *)Malloc(1 + len);
-
- i = k = 0;
- while (1) {
- p[i++] = path[k++];
-
- if (path[k] == '/' || !path[k]) {
- p[i] = 0;
-
- if (do_dir(p) < 0) {
- Free(p);
- return 0;
- }
-
- if (!path[k]) {
- /* End of the string */
- break;
- }
-
- /* check whether its a trailing / or group of / */
- last = 1;
- j = k+1;
- while (path[j]) {
- if (path[j] != '/') {
- k = j - 1; /* Pick up a / into p[] thru the assignment at the top of the loop */
- last = 0;
- break;
- }
- j++;
- }
-
- if (last) {
- break;
- }
- }
-
- if (!path[k]) break;
-
- }
-
- Free(p);
- return 1;
-
-}
-
-/* ================================================== */
-
-#if defined(TEST)
-int main(int argc, char **argv) {
- if (argc > 1) {
- /* Invert sense of result */
- return mkdir_and_parents(argv[1]) ? 0 : 1;
- } else {
- return 1;
- }
-}
-#endif
-
diff --git a/mkdirpp.h b/mkdirpp.h
deleted file mode 100644
index 5304833..0000000
--- a/mkdirpp.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- chronyd/chronyc - Programs for keeping computer clocks accurate.
-
- **********************************************************************
- * Copyright (C) Richard P. Curnow 1997-2002
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of version 2 of the GNU General Public License as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- **********************************************************************
-
- =======================================================================
-
- */
-
-#ifndef GOT_MKDIRPP_H
-#define GOT_MKDIRPP_H
-
-extern int mkdir_and_parents(const char *path);
-
-#endif
diff --git a/nameserv_async.h b/nameserv_async.h
index cea2d82..b8479e1 100644
--- a/nameserv_async.h
+++ b/nameserv_async.h
@@ -34,8 +34,7 @@
typedef void (*DNS_NameResolveHandler)(DNS_Status status, int n_addrs, IPAddr *ip_addrs, void *anything);
/* Request resolving of a name to IP address. The handler will be
- called when the result is available, but it may be also called
- directly from this function call. */
+ called when the result is available. */
extern void DNS_Name2IPAddressAsync(const char *name, DNS_NameResolveHandler handler, void *anything);
#endif
diff --git a/ntp_io.c b/ntp_io.c
index 571292a..24b1190 100644
--- a/ntp_io.c
+++ b/ntp_io.c
@@ -99,10 +99,10 @@ prepare_socket(int family, int port_number, int client_only)
if (sock_fd < 0) {
if (!client_only) {
LOG(LOGS_ERR, LOGF_NtpIO, "Could not open %s NTP socket : %s",
- family == AF_INET ? "IPv4" : "IPv6", strerror(errno));
+ UTI_SockaddrFamilyToString(family), strerror(errno));
} else {
DEBUG_LOG(LOGF_NtpIO, "Could not open %s NTP socket : %s",
- family == AF_INET ? "IPv4" : "IPv6", strerror(errno));
+ UTI_SockaddrFamilyToString(family), strerror(errno));
}
return INVALID_SOCK_FD;
}
@@ -189,7 +189,7 @@ prepare_socket(int family, int port_number, int client_only)
#endif
if (family == AF_INET) {
-#ifdef IP_PKTINFO
+#ifdef HAVE_IN_PKTINFO
/* We want the local IP info on server sockets */
if (setsockopt(sock_fd, IPPROTO_IP, IP_PKTINFO, (char *)&on_off, sizeof(on_off)) < 0) {
LOG(LOGS_ERR, LOGF_NtpIO, "Could not set packet info socket option");
@@ -206,22 +206,24 @@ prepare_socket(int family, int port_number, int client_only)
}
#endif
+#ifdef HAVE_IN6_PKTINFO
#ifdef IPV6_RECVPKTINFO
if (setsockopt(sock_fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, (char *)&on_off, sizeof(on_off)) < 0) {
LOG(LOGS_ERR, LOGF_NtpIO, "Could not set IPv6 packet info socket option");
}
-#elif defined(IPV6_PKTINFO)
+#else
if (setsockopt(sock_fd, IPPROTO_IPV6, IPV6_PKTINFO, (char *)&on_off, sizeof(on_off)) < 0) {
LOG(LOGS_ERR, LOGF_NtpIO, "Could not set IPv6 packet info socket option");
}
#endif
+#endif
}
#endif
/* Bind the socket if a port or address was specified */
if (my_addr_len > 0 && bind(sock_fd, &my_addr.u, my_addr_len) < 0) {
LOG(LOGS_ERR, LOGF_NtpIO, "Could not bind %s NTP socket : %s",
- family == AF_INET ? "IPv4" : "IPv6", strerror(errno));
+ UTI_SockaddrFamilyToString(family), strerror(errno));
close(sock_fd);
return INVALID_SOCK_FD;
}
@@ -531,7 +533,7 @@ read_from_socket(void *anything)
local_addr.sock_fd = sock_fd;
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
-#ifdef IP_PKTINFO
+#ifdef HAVE_IN_PKTINFO
if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO) {
struct in_pktinfo ipi;
@@ -541,7 +543,7 @@ read_from_socket(void *anything)
}
#endif
-#if defined(IPV6_PKTINFO) && defined(HAVE_IN6_PKTINFO)
+#ifdef HAVE_IN6_PKTINFO
if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
struct in6_pktinfo ipi;
@@ -629,7 +631,7 @@ send_packet(void *packet, int packetlen, NTP_Remote_Address *remote_addr, NTP_Lo
msg.msg_flags = 0;
cmsglen = 0;
-#ifdef IP_PKTINFO
+#ifdef HAVE_IN_PKTINFO
if (local_addr->ip_addr.family == IPADDR_INET4) {
struct cmsghdr *cmsg;
struct in_pktinfo *ipi;
@@ -647,7 +649,7 @@ send_packet(void *packet, int packetlen, NTP_Remote_Address *remote_addr, NTP_Lo
}
#endif
-#if defined(IPV6_PKTINFO) && defined(HAVE_IN6_PKTINFO)
+#ifdef HAVE_IN6_PKTINFO
if (local_addr->ip_addr.family == IPADDR_INET6) {
struct cmsghdr *cmsg;
struct in6_pktinfo *ipi;
diff --git a/ntp_sources.c b/ntp_sources.c
index 9c56255..eca681c 100644
--- a/ntp_sources.c
+++ b/ntp_sources.c
@@ -703,6 +703,23 @@ NSR_HandleBadSource(IPAddr *address)
/* ================================================== */
+void
+NSR_RefreshAddresses(void)
+{
+ SourceRecord *record;
+ unsigned int i;
+
+ for (i = 0; i < ARR_GetSize(records); i++) {
+ record = get_record(i);
+ if (!record->remote_addr || !record->name)
+ continue;
+
+ resolve_source_replacement(record);
+ }
+}
+
+/* ================================================== */
+
static void remove_tentative_pool_sources(int pool)
{
SourceRecord *record;
diff --git a/ntp_sources.h b/ntp_sources.h
index 828a446..9bd2d3b 100644
--- a/ntp_sources.h
+++ b/ntp_sources.h
@@ -80,6 +80,9 @@ extern void NSR_RemoveAllSources(void);
/* Procedure to try to find a replacement for a bad source */
extern void NSR_HandleBadSource(IPAddr *address);
+/* Procedure to resolve all names again */
+extern void NSR_RefreshAddresses(void);
+
/* This routine is called by ntp_io when a new packet arrives off the network */
extern void NSR_ProcessReceive(NTP_Packet *message, struct timeval *now, double now_err, NTP_Remote_Address *remote_addr, NTP_Local_Address *local_addr, int length);
diff --git a/pktlength.c b/pktlength.c
index be773c2..e123ef4 100644
--- a/pktlength.c
+++ b/pktlength.c
@@ -150,6 +150,8 @@ command_unpadded_length(CMD_Request *r)
return offsetof(CMD_Request, data.null.EOR);
case REQ_SMOOTHTIME:
return offsetof(CMD_Request, data.smoothtime.EOR);
+ case REQ_REFRESH:
+ return offsetof(CMD_Request, data.null.EOR);
default:
/* If we fall through the switch, it most likely means we've forgotten to implement a new case */
assert(0);
@@ -304,6 +306,8 @@ PKL_CommandPaddingLength(CMD_Request *r)
return PADDING_LENGTH(data.null.EOR, data.smoothing.EOR);
case REQ_SMOOTHTIME:
return PADDING_LENGTH(data.smoothtime.EOR, data.null.EOR);
+ case REQ_REFRESH:
+ return PADDING_LENGTH(data.null.EOR, data.null.EOR);
default:
/* If we fall through the switch, it most likely means we've forgotten to implement a new case */
assert(0);
diff --git a/reference.c b/reference.c
index 4213a58..d5e6388 100644
--- a/reference.c
+++ b/reference.c
@@ -789,7 +789,7 @@ update_leap_status(NTP_Leap leap, time_t now, int reset)
}
}
- if (reset || (leap_sec != our_leap_sec && !REF_IsLeapSecondClose())) {
+ if (leap_sec != our_leap_sec && !REF_IsLeapSecondClose()) {
our_leap_sec = leap_sec;
switch (leap_mode) {
@@ -805,6 +805,8 @@ update_leap_status(NTP_Leap leap, time_t now, int reset)
assert(0);
break;
}
+ } else if (reset) {
+ set_leap_timeout(now);
}
our_leap_status = leap;
diff --git a/rtc.c b/rtc.c
index 2d0f9cd..8d076c6 100644
--- a/rtc.c
+++ b/rtc.c
@@ -39,11 +39,12 @@
/* ================================================== */
static int driver_initialised = 0;
+static int driver_preinit_ok = 0;
static struct {
int (*init)(void);
void (*fini)(void);
- int (*time_pre_init)(void);
+ int (*time_pre_init)(time_t driftfile_time);
void (*time_init)(void (*after_hook)(void*), void *anything);
void (*start_measurements)(void);
int (*write_parameters)(void);
@@ -73,29 +74,37 @@ static struct {
};
/* ================================================== */
-/* Set the system clock to the time of last modification of driftfile
- if it's in the future */
+/* Get the last modification time of the driftfile */
-static void
-fallback_time_init(void)
+static time_t
+get_driftfile_time(void)
{
- struct timeval now;
struct stat buf;
char *drift_file;
drift_file = CNF_GetDriftFile();
if (!drift_file)
- return;
+ return 0;
if (stat(drift_file, &buf))
- return;
+ return 0;
+
+ return buf.st_mtime;
+}
+
+/* ================================================== */
+/* Set the system time to the driftfile time if it's in the future */
+
+static void
+apply_driftfile_time(time_t t)
+{
+ struct timeval now;
LCL_ReadCookedTime(&now, NULL);
- if (now.tv_sec < buf.st_mtime) {
- if (LCL_ApplyStepOffset(now.tv_sec - buf.st_mtime))
- LOG(LOGS_INFO, LOGF_Rtc, "System clock set from driftfile %s",
- drift_file);
+ if (now.tv_sec < t) {
+ if (LCL_ApplyStepOffset(now.tv_sec - t))
+ LOG(LOGS_INFO, LOGF_Rtc, "System time restored from driftfile");
}
}
@@ -104,15 +113,24 @@ fallback_time_init(void)
void
RTC_Initialise(int initial_set)
{
+ time_t driftfile_time;
char *file_name;
- /* Do an initial read of the RTC and set the system time to it. This
- is analogous to what /sbin/hwclock -s would do on Linux. If that fails
- or RTC is not supported, set the clock to the time of the last
- modification of driftfile, so we at least get closer to the truth. */
+ /* If the -s option was specified, try to do an initial read of the RTC and
+ set the system time to it. Also, read the last modification time of the
+ driftfile (i.e. system time when chronyd was previously stopped) and set
+ the system time to it if it's in the future to bring the clock closer to
+ the true time when the RTC is broken (e.g. it has no battery), is missing,
+ or there is no RTC driver. */
if (initial_set) {
- if (!driver.time_pre_init || !driver.time_pre_init()) {
- fallback_time_init();
+ driftfile_time = get_driftfile_time();
+
+ if (driver.time_pre_init && driver.time_pre_init(driftfile_time)) {
+ driver_preinit_ok = 1;
+ } else {
+ driver_preinit_ok = 0;
+ if (driftfile_time)
+ apply_driftfile_time(driftfile_time);
}
}
@@ -150,9 +168,9 @@ RTC_Finalise(void)
/* ================================================== */
/* Start the processing to get a single measurement from the real time
clock, and use it to trim the system time, based on knowing the
- drift rate of the RTC and the error the last time we set it. The
- TimePreInit routine has already run, so we can be sure that the
- trim required is not *too* large.
+ drift rate of the RTC and the error the last time we set it. If the
+ TimePreInit routine has succeeded, we can be sure that the trim required
+ is not *too* large.
We are called with a hook to a function to be called after the
initialisation is complete. We also call this if we cannot do the
@@ -161,7 +179,7 @@ RTC_Finalise(void)
void
RTC_TimeInit(void (*after_hook)(void *), void *anything)
{
- if (driver_initialised) {
+ if (driver_initialised && driver_preinit_ok) {
(driver.time_init)(after_hook, anything);
} else {
(after_hook)(anything);
diff --git a/rtc_linux.c b/rtc_linux.c
index 40befb3..86d8261 100644
--- a/rtc_linux.c
+++ b/rtc_linux.c
@@ -367,6 +367,9 @@ t_from_rtc(struct tm *stm) {
t2 = mktime(&temp2);
diff = t2 - t1;
+ if (t1 - diff == -1)
+ DEBUG_LOG(LOGF_RtcLinux, "Could not convert RTC time");
+
return t1 - diff;
}
@@ -379,13 +382,13 @@ read_hwclock_file(const char *hwclock_file)
char line[256];
int i;
- if (!hwclock_file)
+ if (!hwclock_file || !hwclock_file[0])
return;
in = fopen(hwclock_file, "r");
if (!in) {
- LOG(LOGS_WARN, LOGF_RtcLinux, "Could not open hwclockfile %s",
- hwclock_file);
+ LOG(LOGS_WARN, LOGF_RtcLinux, "Could not open %s : %s",
+ hwclock_file, strerror(errno));
return;
}
@@ -402,7 +405,7 @@ read_hwclock_file(const char *hwclock_file)
} else if (i == 3 && !strncmp(line, "UTC", 3)) {
rtc_on_utc = 1;
} else {
- LOG(LOGS_WARN, LOGF_RtcLinux, "Could not read LOCAL/UTC setting from hwclockfile %s",
+ LOG(LOGS_WARN, LOGF_RtcLinux, "Could not read RTC LOCAL/UTC setting from %s",
hwclock_file);
}
}
@@ -445,7 +448,7 @@ read_coefs_from_file(void)
&file_ref_offset,
&file_rate_ppm) == 4) {
} else {
- LOG(LOGS_WARN, LOGF_RtcLinux, "Could not read coefficients from RTC file %s",
+ LOG(LOGS_WARN, LOGF_RtcLinux, "Could not read coefficients from %s",
coefs_file_name);
}
fclose(in);
@@ -607,14 +610,16 @@ switch_interrupts(int onoff)
if (onoff) {
status = ioctl(fd, RTC_UIE_ON, 0);
if (status < 0) {
- LOG(LOGS_ERR, LOGF_RtcLinux, "Could not start measurement : %s", strerror(errno));
+ LOG(LOGS_ERR, LOGF_RtcLinux, "Could not %s RTC interrupt : %s",
+ "enable", strerror(errno));
return;
}
skip_interrupts = 1;
} else {
status = ioctl(fd, RTC_UIE_OFF, 0);
if (status < 0) {
- LOG(LOGS_ERR, LOGF_RtcLinux, "Could not stop measurement : %s", strerror(errno));
+ LOG(LOGS_ERR, LOGF_RtcLinux, "Could not %s RTC interrupt : %s",
+ "disable", strerror(errno));
return;
}
}
@@ -694,10 +699,11 @@ handle_initial_trim(void)
/* sys_error_now is positive if the system clock is fast */
sys_error_now = rtc_error_now - coef_seconds_fast;
- LOG(LOGS_INFO, LOGF_RtcLinux, "System trim from RTC = %f", sys_error_now);
LCL_AccumulateOffset(sys_error_now, 0.0);
+ LOG(LOGS_INFO, LOGF_RtcLinux, "System clock off from RTC by %f seconds (slew)",
+ sys_error_now);
} else {
- LOG(LOGS_WARN, LOGF_RtcLinux, "No valid file coefficients, cannot trim system time");
+ LOG(LOGS_WARN, LOGF_RtcLinux, "No valid rtcfile coefficients");
}
coefs_valid = 0;
@@ -722,7 +728,7 @@ handle_relock_after_trim(void)
if (valid) {
write_coefs_to_file(1,ref,fast,saved_coef_gain_rate);
} else {
- LOG(LOGS_WARN, LOGF_RtcLinux, "Could not do regression after trim");
+ DEBUG_LOG(LOGF_RtcLinux, "Could not do regression after trim");
}
coefs_valid = 0;
@@ -857,7 +863,6 @@ read_from_device(void *any)
rtc_t = t_from_rtc(&rtc_tm);
if (rtc_t == (time_t)(-1)) {
- LOG(LOGS_ERR, LOGF_RtcLinux, "Could not convert RTC time to timeval");
error = 1;
goto turn_off_interrupt;
}
@@ -883,7 +888,7 @@ turn_off_interrupt:
switch (operating_mode) {
case OM_INITIAL:
if (error) {
- LOG(LOGS_WARN, LOGF_RtcLinux, "Could not complete initial step due to errors");
+ DEBUG_LOG(LOGF_RtcLinux, "Could not complete initial step due to errors");
operating_mode = OM_NORMAL;
(after_init_hook)(after_init_hook_arg);
@@ -897,7 +902,7 @@ turn_off_interrupt:
case OM_AFTERTRIM:
if (error) {
- LOG(LOGS_WARN, LOGF_RtcLinux, "Could not complete after trim relock due to errors");
+ DEBUG_LOG(LOGF_RtcLinux, "Could not complete after trim relock due to errors");
operating_mode = OM_NORMAL;
switch_interrupts(0);
@@ -974,7 +979,7 @@ RTC_Linux_WriteParameters(void)
RTC behaviour than we do for the rest of the module. */
int
-RTC_Linux_TimePreInit(void)
+RTC_Linux_TimePreInit(time_t driftfile_time)
{
int fd, status;
struct rtc_time rtc_raw, rtc_raw_retry;
@@ -1039,18 +1044,23 @@ RTC_Linux_TimePreInit(void)
UTI_AddDoubleToTimeval(&new_sys_time, -accumulated_error, &new_sys_time);
+ if (new_sys_time.tv_sec < driftfile_time) {
+ LOG(LOGS_WARN, LOGF_RtcLinux, "RTC time before last driftfile modification (ignored)");
+ return 0;
+ }
+
UTI_DiffTimevalsToDouble(&sys_offset, &old_sys_time, &new_sys_time);
/* Set system time only if the step is larger than 1 second */
if (fabs(sys_offset) >= 1.0) {
if (LCL_ApplyStepOffset(sys_offset))
- LOG(LOGS_INFO, LOGF_RtcLinux, "Set system time, error in RTC = %f",
- accumulated_error);
+ LOG(LOGS_INFO, LOGF_RtcLinux, "System time set from RTC");
}
} else {
- LOG(LOGS_WARN, LOGF_RtcLinux, "Could not convert RTC reading to seconds since 1/1/1970");
return 0;
}
+ } else {
+ return 0;
}
return 1;
@@ -1090,7 +1100,8 @@ RTC_Linux_Trim(void)
if (fabs(coef_seconds_fast) > 1.0) {
- LOG(LOGS_INFO, LOGF_RtcLinux, "Trimming RTC, error = %.3f seconds", coef_seconds_fast);
+ LOG(LOGS_INFO, LOGF_RtcLinux, "RTC wrong by %.3f seconds (step)",
+ coef_seconds_fast);
/* Do processing to set clock. Let R be the value we set the
RTC to, then in 500ms the RTC ticks (R+1) (see comments in
diff --git a/rtc_linux.h b/rtc_linux.h
index 8cf23a6..fa33ef1 100644
--- a/rtc_linux.h
+++ b/rtc_linux.h
@@ -30,7 +30,7 @@
extern int RTC_Linux_Initialise(void);
extern void RTC_Linux_Finalise(void);
-extern int RTC_Linux_TimePreInit(void);
+extern int RTC_Linux_TimePreInit(time_t driftile_time);
extern void RTC_Linux_TimeInit(void (*after_hook)(void *), void *anything);
extern void RTC_Linux_StartMeasurements(void);
diff --git a/sources.c b/sources.c
index c6a67c5..017f3bc 100644
--- a/sources.c
+++ b/sources.c
@@ -44,7 +44,6 @@
#include "logging.h"
#include "reports.h"
#include "nameserv.h"
-#include "mkdirpp.h"
#include "sched.h"
#include "regress.h"
@@ -71,6 +70,7 @@ typedef enum {
SRC_OK, /* OK so far, not a final status! */
SRC_UNSELECTABLE, /* Has noselect option set */
SRC_BAD_STATS, /* Doesn't have valid stats data */
+ SRC_BAD_DISTANCE, /* Has root distance longer than allowed maximum */
SRC_WAITS_STATS, /* Others have bad stats, selection postponed */
SRC_STALE, /* Has older samples than others */
SRC_FALSETICKER, /* Doesn't agree with others */
@@ -156,6 +156,7 @@ static int selected_source_index; /* Which source index is currently
/* Number of updates needed to reset the distant status */
#define DISTANT_PENALTY 32
+static double max_distance;
static double reselect_distance;
static double stratum_weight;
static double combine_limit;
@@ -180,6 +181,7 @@ void SRC_Initialise(void) {
n_sources = 0;
max_n_sources = 0;
selected_source_index = INVALID_SOURCE;
+ max_distance = CNF_GetMaxDistance();
reselect_distance = CNF_GetReselectDistance();
stratum_weight = CNF_GetStratumWeight();
combine_limit = CNF_GetCombineLimit();
@@ -654,6 +656,12 @@ SRC_SelectSource(SRC_Instance updated_inst)
continue;
}
+ /* Require the root distance to be below the allowed maximum */
+ if (si->root_distance > max_distance) {
+ sources[i]->status = SRC_BAD_DISTANCE;
+ continue;
+ }
+
sources[i]->status = SRC_OK; /* For now */
if (sources[i]->reachability && max_reach_sample_ago < first_sample_ago)
@@ -1093,25 +1101,23 @@ SRC_DumpSources(void)
direc_len = strlen(direc);
file_len = direc_len + 24;
filename = MallocArray(char, file_len); /* a bit of slack */
- if (mkdir_and_parents(direc)) {
- for (i=0; i<n_sources; i++) {
- a = (sources[i]->ref_id) >> 24;
- b = ((sources[i]->ref_id) >> 16) & 0xff;
- c = ((sources[i]->ref_id) >> 8) & 0xff;
- d = ((sources[i]->ref_id)) & 0xff;
-
- snprintf(filename, file_len-1, "%s/%d.%d.%d.%d.dat", direc, a, b, c, d);
- out = fopen(filename, "w");
- if (!out) {
- LOG(LOGS_WARN, LOGF_Sources, "Could not open dump file %s", filename);
- } else {
- SST_SaveToFile(sources[i]->stats, out);
- fclose(out);
- }
+
+ for (i = 0; i < n_sources; i++) {
+ a = (sources[i]->ref_id) >> 24;
+ b = ((sources[i]->ref_id) >> 16) & 0xff;
+ c = ((sources[i]->ref_id) >> 8) & 0xff;
+ d = ((sources[i]->ref_id)) & 0xff;
+
+ snprintf(filename, file_len - 1, "%s/%d.%d.%d.%d.dat", direc, a, b, c, d);
+ out = fopen(filename, "w");
+ if (!out) {
+ LOG(LOGS_WARN, LOGF_Sources, "Could not open dump file %s", filename);
+ } else {
+ SST_SaveToFile(sources[i]->stats, out);
+ fclose(out);
}
- } else {
- LOG(LOGS_ERR, LOGF_Sources, "Could not create directory %s", direc);
}
+
Free(filename);
}
@@ -1219,6 +1225,7 @@ SRC_ReportSource(int index, RPT_SourceReport *report, struct timeval *now)
switch (src->status) {
case SRC_UNSELECTABLE:
case SRC_BAD_STATS:
+ case SRC_BAD_DISTANCE:
case SRC_STALE:
case SRC_WAITS_STATS:
report->state = RPT_UNREACH;
diff --git a/strerror.c b/strerror.c
deleted file mode 100644
index 8396142..0000000
--- a/strerror.c
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- chronyd/chronyc - Programs for keeping computer clocks accurate.
-
- **********************************************************************
- * Copyright (C) Richard P. Curnow 1997-2002
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of version 2 of the GNU General Public License as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- **********************************************************************
-
- =======================================================================
-
- Replacement strerror function for systems that don't have it
- */
-
-#include "config.h"
-
-#ifdef SUNOS
-
-#include <errno.h>
-extern char *sys_errlist[];
-
-char *strerror(int n) {
- return sys_errlist[n];
-}
-
-#endif /* SUNOS */
diff --git a/stubs.c b/stubs.c
index 01d85e3..7a623c7 100644
--- a/stubs.c
+++ b/stubs.c
@@ -2,7 +2,7 @@
chronyd/chronyc - Programs for keeping computer clocks accurate.
**********************************************************************
- * Copyright (C) Miroslav Lichvar 2014
+ * Copyright (C) Miroslav Lichvar 2014-2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
@@ -32,12 +32,14 @@
#include "keys.h"
#include "logging.h"
#include "manual.h"
+#include "memory.h"
#include "nameserv.h"
#include "nameserv_async.h"
#include "ntp_core.h"
#include "ntp_io.h"
#include "ntp_sources.h"
#include "refclock.h"
+#include "sched.h"
#ifndef FEAT_ASYNCDNS
@@ -45,20 +47,43 @@
/* This is a blocking implementation used when asynchronous resolving is not available */
-void
-DNS_Name2IPAddressAsync(const char *name, DNS_NameResolveHandler handler, void *anything)
+struct DNS_Async_Instance {
+ const char *name;
+ DNS_NameResolveHandler handler;
+ void *arg;
+};
+
+static void
+resolve_name(void *anything)
{
+ struct DNS_Async_Instance *inst;
IPAddr addrs[MAX_ADDRESSES];
DNS_Status status;
int i;
- status = DNS_Name2IPAddress(name, addrs, MAX_ADDRESSES);
+ inst = (struct DNS_Async_Instance *)anything;
+ status = DNS_Name2IPAddress(inst->name, addrs, MAX_ADDRESSES);
for (i = 0; status == DNS_Success && i < MAX_ADDRESSES &&
- addrs[i].family != IPADDR_UNSPEC; i++)
+ addrs[i].family != IPADDR_UNSPEC; i++)
;
- (handler)(status, i, addrs, anything);
+ (inst->handler)(status, i, addrs, inst->arg);
+
+ Free(inst);
+}
+
+void
+DNS_Name2IPAddressAsync(const char *name, DNS_NameResolveHandler handler, void *anything)
+{
+ struct DNS_Async_Instance *inst;
+
+ inst = MallocNew(struct DNS_Async_Instance);
+ inst->name = name;
+ inst->handler = handler;
+ inst->arg = anything;
+
+ SCH_AddTimeoutByDelay(0.0, resolve_name, inst);
}
#endif /* !FEAT_ASYNCDNS */
@@ -75,6 +100,11 @@ CAM_Finalise(void)
{
}
+void
+CAM_OpenUnixSocket(void)
+{
+}
+
int
CAM_AddAccessRestriction(IPAddr *ip_addr, int subnet_bits, int allow, int all)
{
@@ -170,6 +200,11 @@ NSR_HandleBadSource(IPAddr *address)
}
void
+NSR_RefreshAddresses(void)
+{
+}
+
+void
NSR_SetSourceResolvingEndHandler(NSR_SourceResolvingEndHandler handler)
{
if (handler)
diff --git a/sys.c b/sys.c
index f0c81df..4009796 100644
--- a/sys.c
+++ b/sys.c
@@ -27,26 +27,20 @@
#include "config.h"
+#include "sysincl.h"
+
#include "sys.h"
#include "logging.h"
-#if defined (LINUX)
+#if defined(LINUX)
#include "sys_linux.h"
-#endif
-
-#if defined (SOLARIS)
+#elif defined(SOLARIS)
#include "sys_solaris.h"
-#endif
-
-#if defined (SUNOS)
+#elif defined(SUNOS)
#include "sys_sunos.h"
-#endif
-
-#if defined (__NetBSD__)
+#elif defined(NETBSD) || defined(FREEBSD)
#include "sys_netbsd.h"
-#endif
-
-#if defined (MACOSX)
+#elif defined(MACOSX)
#include "sys_macosx.h"
#endif
@@ -55,27 +49,19 @@
void
SYS_Initialise(void)
{
-
#if defined(LINUX)
SYS_Linux_Initialise();
-#endif
-
-#if defined(SOLARIS)
+#elif defined(SOLARIS)
SYS_Solaris_Initialise();
-#endif
-
-#if defined(SUNOS)
+#elif defined(SUNOS)
SYS_SunOS_Initialise();
-#endif
-
-#if defined(__NetBSD__)
+#elif defined(NETBSD) || defined(FREEBSD)
SYS_NetBSD_Initialise();
-#endif
-
-#if defined(MACOSX)
+#elif defined(MACOSX)
SYS_MacOSX_Initialise();
+#else
+#error Unknown system
#endif
-
}
/* ================================================== */
@@ -83,34 +69,29 @@ SYS_Initialise(void)
void
SYS_Finalise(void)
{
-
#if defined(LINUX)
SYS_Linux_Finalise();
-#endif
-
-#if defined(SOLARIS)
+#elif defined(SOLARIS)
SYS_Solaris_Finalise();
-#endif
-
-#if defined(SUNOS)
+#elif defined(SUNOS)
SYS_SunOS_Finalise();
-#endif
-
-#if defined(__NetBSD__)
+#elif defined(NETBSD) || defined(FREEBSD)
SYS_NetBSD_Finalise();
-#endif
-
-#if defined(MACOSX)
+#elif defined(MACOSX)
SYS_MacOSX_Finalise();
+#else
+#error Unknown system
#endif
}
/* ================================================== */
-void SYS_DropRoot(char *user)
+void SYS_DropRoot(uid_t uid, gid_t gid)
{
#if defined(LINUX) && defined (FEAT_PRIVDROP)
- SYS_Linux_DropRoot(user);
+ SYS_Linux_DropRoot(uid, gid);
+#elif defined(NETBSD) && defined(FEAT_PRIVDROP)
+ SYS_NetBSD_DropRoot(uid, gid);
#else
LOG_FATAL(LOGF_Sys, "dropping root privileges not supported");
#endif
@@ -118,10 +99,23 @@ void SYS_DropRoot(char *user)
/* ================================================== */
+void SYS_EnableSystemCallFilter(int level)
+{
+#if defined(LINUX) && defined(FEAT_SCFILTER)
+ SYS_Linux_EnableSystemCallFilter(level);
+#else
+ LOG_FATAL(LOGF_Sys, "system call filter not supported");
+#endif
+}
+
+/* ================================================== */
+
void SYS_SetScheduler(int SchedPriority)
{
#if defined(LINUX) && defined(HAVE_SCHED_SETSCHEDULER)
SYS_Linux_SetScheduler(SchedPriority);
+#elif defined(MACOSX)
+ SYS_MacOSX_SetScheduler(SchedPriority);
#else
LOG_FATAL(LOGF_Sys, "scheduler priority setting not supported");
#endif
diff --git a/sys.h b/sys.h
index 569ecdb..bd990e2 100644
--- a/sys.h
+++ b/sys.h
@@ -35,8 +35,12 @@ extern void SYS_Initialise(void);
/* Called at the end of the run to do final clean-up */
extern void SYS_Finalise(void);
-/* Drop root privileges to the specified user */
-extern void SYS_DropRoot(char *user);
+/* Drop root privileges to the specified user and group */
+extern void SYS_DropRoot(uid_t uid, gid_t gid);
+
+/* Enable a system call filter to allow only system calls
+ which chronyd normally needs after initialization */
+extern void SYS_EnableSystemCallFilter(int level);
extern void SYS_SetScheduler(int SchedPriority);
extern void SYS_LockMemory(void);
diff --git a/sys_generic.c b/sys_generic.c
index db343e5..9d5c87c 100644
--- a/sys_generic.c
+++ b/sys_generic.c
@@ -2,7 +2,7 @@
chronyd/chronyc - Programs for keeping computer clocks accurate.
**********************************************************************
- * Copyright (C) Miroslav Lichvar 2014
+ * Copyright (C) Miroslav Lichvar 2014-2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
@@ -43,6 +43,8 @@
static lcl_ReadFrequencyDriver drv_read_freq;
static lcl_SetFrequencyDriver drv_set_freq;
static lcl_SetSyncStatusDriver drv_set_sync_status;
+static lcl_AccrueOffsetDriver drv_accrue_offset;
+static lcl_OffsetCorrectionDriver drv_get_offset_correction;
/* Current frequency as requested by the local module (in ppm) */
static double base_freq;
@@ -85,6 +87,16 @@ static double correction_rate;
real frequency of the clock */
static double slew_error;
+/* Minimum offset that the system driver can slew faster than the maximum
+ frequency offset that it allows to be set directly */
+static double fastslew_min_offset;
+
+/* Maximum slew rate of the system driver */
+static double fastslew_max_rate;
+
+/* Flag indicating that the system driver is currently slewing */
+static int fastslew_active;
+
/* ================================================== */
static void handle_end_of_slew(void *anything);
@@ -109,6 +121,38 @@ handle_step(struct timeval *raw, struct timeval *cooked, double dfreq,
/* ================================================== */
+static void
+start_fastslew(void)
+{
+ if (!drv_accrue_offset)
+ return;
+
+ drv_accrue_offset(offset_register, 0.0);
+
+ DEBUG_LOG(LOGF_SysGeneric, "fastslew offset=%e", offset_register);
+
+ offset_register = 0.0;
+ fastslew_active = 1;
+}
+
+/* ================================================== */
+
+static void
+stop_fastslew(struct timeval *now)
+{
+ double corr;
+
+ if (!drv_get_offset_correction || !fastslew_active)
+ return;
+
+ /* Cancel the remaining offset */
+ drv_get_offset_correction(now, &corr, NULL);
+ drv_accrue_offset(corr, 0.0);
+ offset_register -= corr;
+}
+
+/* ================================================== */
+
static double
clamp_freq(double freq)
{
@@ -138,6 +182,8 @@ update_slew(void)
UTI_DiffTimevalsToDouble(&duration, &now, &slew_start);
offset_register -= slew_freq * duration;
+ stop_fastslew(&now);
+
/* Estimate how long should the next slew take */
if (fabs(offset_register) < MIN_OFFSET_CORRECTION) {
duration = MAX_SLEW_TIMEOUT;
@@ -155,6 +201,14 @@ update_slew(void)
else if (corr_freq > max_corr_freq)
corr_freq = max_corr_freq;
+ /* Let the system driver perform the slew if the requested frequency
+ offset is too large for the frequency driver */
+ if (drv_accrue_offset && fabs(corr_freq) >= fastslew_max_rate &&
+ fabs(offset_register) > fastslew_min_offset) {
+ start_fastslew();
+ corr_freq = 0.0;
+ }
+
/* Get the new real frequency and clamp it */
total_freq = clamp_freq(base_freq + corr_freq * (1.0e6 - base_freq));
@@ -175,8 +229,8 @@ update_slew(void)
/* Compute the duration of the slew and clamp it. If the slewing frequency
is zero or has wrong sign (e.g. due to rounding in the frequency driver or
- when base_freq is larger than max_freq), use maximum timeout and try again
- on the next update. */
+ when base_freq is larger than max_freq, or fast slew is active), use the
+ maximum timeout and try again on the next update. */
if (fabs(offset_register) < MIN_OFFSET_CORRECTION ||
offset_register * slew_freq <= 0.0) {
duration = MAX_SLEW_TIMEOUT;
@@ -246,13 +300,25 @@ static void
offset_convert(struct timeval *raw,
double *corr, double *err)
{
- double duration;
+ double duration, fastslew_corr, fastslew_err;
UTI_DiffTimevalsToDouble(&duration, raw, &slew_start);
- *corr = slew_freq * duration - offset_register;
- if (err)
- *err = fabs(duration) <= max_freq_change_delay ? slew_error : 0.0;
+ if (drv_get_offset_correction && fastslew_active) {
+ drv_get_offset_correction(raw, &fastslew_corr, &fastslew_err);
+ if (fastslew_corr == 0.0 && fastslew_err == 0.0)
+ fastslew_active = 0;
+ } else {
+ fastslew_corr = fastslew_err = 0.0;
+ }
+
+ *corr = slew_freq * duration + fastslew_corr - offset_register;
+
+ if (err) {
+ *err = fastslew_err;
+ if (fabs(duration) <= max_freq_change_delay)
+ *err += slew_error;
+ }
}
/* ================================================== */
@@ -303,6 +369,9 @@ SYS_Generic_CompleteFreqDriver(double max_set_freq_ppm, double max_set_freq_dela
lcl_ReadFrequencyDriver sys_read_freq,
lcl_SetFrequencyDriver sys_set_freq,
lcl_ApplyStepOffsetDriver sys_apply_step_offset,
+ double min_fastslew_offset, double max_fastslew_rate,
+ lcl_AccrueOffsetDriver sys_accrue_offset,
+ lcl_OffsetCorrectionDriver sys_get_offset_correction,
lcl_SetLeapDriver sys_set_leap,
lcl_SetSyncStatusDriver sys_set_sync_status)
{
@@ -310,6 +379,8 @@ SYS_Generic_CompleteFreqDriver(double max_set_freq_ppm, double max_set_freq_dela
max_freq_change_delay = max_set_freq_delay * (1.0 + max_freq / 1.0e6);
drv_read_freq = sys_read_freq;
drv_set_freq = sys_set_freq;
+ drv_accrue_offset = sys_accrue_offset;
+ drv_get_offset_correction = sys_get_offset_correction;
drv_set_sync_status = sys_set_sync_status;
base_freq = (*drv_read_freq)();
@@ -318,6 +389,10 @@ SYS_Generic_CompleteFreqDriver(double max_set_freq_ppm, double max_set_freq_dela
max_corr_freq = CNF_GetMaxSlewRate() / 1.0e6;
+ fastslew_min_offset = min_fastslew_offset;
+ fastslew_max_rate = max_fastslew_rate / 1.0e6;
+ fastslew_active = 0;
+
lcl_RegisterSystemDrivers(read_frequency, set_frequency,
accrue_offset, sys_apply_step_offset ?
sys_apply_step_offset : apply_step_offset,
@@ -331,6 +406,8 @@ SYS_Generic_CompleteFreqDriver(double max_set_freq_ppm, double max_set_freq_dela
void
SYS_Generic_Finalise(void)
{
+ struct timeval now;
+
/* Must *NOT* leave a slew running - clock could drift way off
if the daemon is not restarted */
if (slew_timer_running) {
@@ -339,6 +416,9 @@ SYS_Generic_Finalise(void)
}
(*drv_set_freq)(clamp_freq(base_freq));
+
+ LCL_ReadRawTime(&now);
+ stop_fastslew(&now);
}
/* ================================================== */
diff --git a/sys_generic.h b/sys_generic.h
index 4532083..d9b252e 100644
--- a/sys_generic.h
+++ b/sys_generic.h
@@ -35,6 +35,9 @@ extern void SYS_Generic_CompleteFreqDriver(double max_set_freq_ppm, double max_s
lcl_ReadFrequencyDriver sys_read_freq,
lcl_SetFrequencyDriver sys_set_freq,
lcl_ApplyStepOffsetDriver sys_apply_step_offset,
+ double min_fastslew_offset, double max_fastslew_rate,
+ lcl_AccrueOffsetDriver sys_accrue_offset,
+ lcl_OffsetCorrectionDriver sys_get_offset_correction,
lcl_SetLeapDriver sys_set_leap,
lcl_SetSyncStatusDriver sys_set_sync_status);
diff --git a/sys_linux.c b/sys_linux.c
index e5ca9a6..092fd84 100644
--- a/sys_linux.c
+++ b/sys_linux.c
@@ -4,7 +4,7 @@
**********************************************************************
* Copyright (C) Richard P. Curnow 1997-2003
* Copyright (C) John G. Hasler 2009
- * Copyright (C) Miroslav Lichvar 2009-2012, 2014
+ * Copyright (C) Miroslav Lichvar 2009-2012, 2014-2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
@@ -35,31 +35,48 @@
#if defined(HAVE_SCHED_SETSCHEDULER)
# include <sched.h>
-int SchedPriority = 0;
#endif
#if defined(HAVE_MLOCKALL)
# include <sys/mman.h>
#include <sys/resource.h>
-int LockAll = 0;
#endif
#ifdef FEAT_PRIVDROP
-#include <sys/types.h>
-#include <pwd.h>
#include <sys/prctl.h>
#include <sys/capability.h>
#include <grp.h>
#endif
-#include "sys_generic.h"
+#ifdef FEAT_SCFILTER
+#include <sys/prctl.h>
+#include <seccomp.h>
+#ifdef FEAT_PHC
+#include <linux/ptp_clock.h>
+#endif
+#ifdef FEAT_PPS
+#include <linux/pps.h>
+#endif
+#ifdef FEAT_RTC
+#include <linux/rtc.h>
+#endif
+#endif
+
#include "sys_linux.h"
+#include "sys_timex.h"
#include "conf.h"
#include "logging.h"
-#include "wrap_adjtimex.h"
-/* The threshold for adjtimex maxerror when the kernel sets the UNSYNC flag */
-#define UNSYNC_MAXERROR 16.0
+/* Frequency scale to convert from ppm to the timex freq */
+#define FREQ_SCALE (double)(1 << 16)
+
+/* Definitions used if missed in the system headers */
+#ifndef ADJ_SETOFFSET
+#define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
+#endif
+#ifndef ADJ_NANO
+#define ADJ_NANO 0x2000 /* select nanosecond resolution */
+#endif
/* This is the uncompensated system tick value */
static int nominal_tick;
@@ -103,11 +120,19 @@ our_round(double x)
static int
apply_step_offset(double offset)
{
- if (TMX_ApplyStepOffset(-offset) < 0) {
- DEBUG_LOG(LOGF_SysLinux, "adjtimex() failed");
- return 0;
+ struct timex txc;
+
+ txc.modes = ADJ_SETOFFSET | ADJ_NANO;
+ txc.time.tv_sec = -offset;
+ txc.time.tv_usec = 1.0e9 * (-offset - txc.time.tv_sec);
+ if (txc.time.tv_usec < 0) {
+ txc.time.tv_sec--;
+ txc.time.tv_usec += 1000000000;
}
+ if (SYS_Timex_Adjust(&txc, 1) < 0)
+ return 0;
+
return 1;
}
@@ -121,6 +146,7 @@ apply_step_offset(double offset)
static double
set_frequency(double freq_ppm)
{
+ struct timex txc;
long required_tick;
double required_freq;
int required_delta_tick;
@@ -144,14 +170,15 @@ set_frequency(double freq_ppm)
required_freq = -(freq_ppm - dhz * required_delta_tick);
required_tick = nominal_tick - required_delta_tick;
- if (TMX_SetFrequency(&required_freq, required_tick) < 0) {
- LOG_FATAL(LOGF_SysLinux, "adjtimex failed for set_frequency, freq_ppm=%10.4e required_freq=%10.4e required_tick=%ld",
- freq_ppm, required_freq, required_tick);
- }
+ txc.modes = ADJ_TICK | ADJ_FREQUENCY;
+ txc.freq = required_freq * FREQ_SCALE;
+ txc.tick = required_tick;
+
+ SYS_Timex_Adjust(&txc, 0);
current_delta_tick = required_delta_tick;
- return dhz * current_delta_tick - required_freq;
+ return dhz * current_delta_tick - txc.freq / FREQ_SCALE;
}
/* ================================================== */
@@ -160,61 +187,15 @@ set_frequency(double freq_ppm)
static double
read_frequency(void)
{
- long tick;
- double freq;
-
- if (TMX_GetFrequency(&freq, &tick) < 0) {
- LOG_FATAL(LOGF_SysLinux, "adjtimex() failed");
- }
-
- current_delta_tick = nominal_tick - tick;
-
- return dhz * current_delta_tick - freq;
-}
-
-/* ================================================== */
-
-static void
-set_leap(int leap)
-{
- int current_leap;
-
- if (TMX_GetLeap(&current_leap) < 0) {
- LOG_FATAL(LOGF_SysLinux, "adjtimex() failed in set_leap");
- }
-
- if (current_leap == leap)
- return;
+ struct timex txc;
- if (TMX_SetLeap(leap) < 0) {
- LOG_FATAL(LOGF_SysLinux, "adjtimex() failed in set_leap");
- }
-
- LOG(LOGS_INFO, LOGF_SysLinux, "System clock status set to %s leap second",
- leap ? (leap > 0 ? "insert" : "delete") : "not insert/delete");
-}
+ txc.modes = 0;
-/* ================================================== */
-
-static void
-set_sync_status(int synchronised, double est_error, double max_error)
-{
- if (synchronised) {
- if (est_error > UNSYNC_MAXERROR)
- est_error = UNSYNC_MAXERROR;
- if (max_error >= UNSYNC_MAXERROR) {
- max_error = UNSYNC_MAXERROR;
- synchronised = 0;
- }
- } else {
- est_error = max_error = UNSYNC_MAXERROR;
- }
+ SYS_Timex_Adjust(&txc, 0);
- /* Clear the UNSYNC flag only if rtcsync is enabled */
- if (!CNF_GetRtcSync())
- synchronised = 0;
+ current_delta_tick = nominal_tick - txc.tick;
- TMX_SetSync(synchronised, est_error, max_error);
+ return dhz * current_delta_tick - txc.freq / FREQ_SCALE;
}
/* ================================================== */
@@ -225,10 +206,16 @@ set_sync_status(int synchronised, double est_error, double max_error)
* a +/- 10% movement of tick away from the nominal value 1e6/USER_HZ. */
static int
-guess_hz(int tick)
+guess_hz(void)
{
- int i, tick_lo, tick_hi, ihz;
+ struct timex txc;
+ int i, tick, tick_lo, tick_hi, ihz;
double tick_nominal;
+
+ txc.modes = 0;
+ SYS_Timex_Adjust(&txc, 0);
+ tick = txc.tick;
+
/* Pick off the hz=100 case first */
if (tick >= 9000 && tick <= 11000) {
return 100;
@@ -246,6 +233,8 @@ guess_hz(int tick)
}
/* oh dear. doomed. */
+ LOG_FATAL(LOGF_SysLinux, "Can't determine hz from tick %d", tick);
+
return 0;
}
@@ -287,21 +276,12 @@ static void
get_version_specific_details(void)
{
int major, minor, patch;
- long tick;
- double freq;
struct utsname uts;
hz = get_hz();
- if (!hz) {
- if (TMX_GetFrequency(&freq, &tick) < 0)
- LOG_FATAL(LOGF_SysLinux, "adjtimex() failed");
-
- hz = guess_hz(tick);
-
- if (!hz)
- LOG_FATAL(LOGF_SysLinux, "Can't determine hz from tick %ld", tick);
- }
+ if (!hz)
+ hz = guess_hz();
dhz = (double) hz;
nominal_tick = (1000000L + (hz/2))/hz; /* Mirror declaration in kernel */
@@ -345,6 +325,48 @@ get_version_specific_details(void)
}
/* ================================================== */
+
+static void
+reset_adjtime_offset(void)
+{
+ struct timex txc;
+
+ /* Reset adjtime() offset */
+ txc.modes = ADJ_OFFSET_SINGLESHOT;
+ txc.offset = 0;
+
+ SYS_Timex_Adjust(&txc, 0);
+}
+
+/* ================================================== */
+
+static int
+test_step_offset(void)
+{
+ struct timex txc;
+
+ /* Zero maxerror and check it's reset to a maximum after ADJ_SETOFFSET.
+ This seems to be the only way how to verify that the kernel really
+ supports the ADJ_SETOFFSET mode as it doesn't return an error on unknown
+ mode. */
+
+ txc.modes = MOD_MAXERROR;
+ txc.maxerror = 0;
+
+ if (SYS_Timex_Adjust(&txc, 1) < 0 || txc.maxerror != 0)
+ return 0;
+
+ txc.modes = ADJ_SETOFFSET | ADJ_NANO;
+ txc.time.tv_sec = 0;
+ txc.time.tv_usec = 0;
+
+ if (SYS_Timex_Adjust(&txc, 1) < 0 || txc.maxerror < 100000)
+ return 0;
+
+ return 1;
+}
+
+/* ================================================== */
/* Initialisation code for this module */
void
@@ -352,20 +374,18 @@ SYS_Linux_Initialise(void)
{
get_version_specific_details();
- if (TMX_ResetOffset() < 0) {
- LOG_FATAL(LOGF_SysLinux, "adjtimex() failed");
- }
+ reset_adjtime_offset();
- if (have_setoffset && TMX_TestStepOffset() < 0) {
+ if (have_setoffset && !test_step_offset()) {
LOG(LOGS_INFO, LOGF_SysLinux, "adjtimex() doesn't support ADJ_SETOFFSET");
have_setoffset = 0;
}
- SYS_Generic_CompleteFreqDriver(1.0e6 * max_tick_bias / nominal_tick,
- 1.0 / tick_update_hz,
- read_frequency, set_frequency,
- have_setoffset ? apply_step_offset : NULL,
- set_leap, set_sync_status);
+ SYS_Timex_InitialiseWithFunctions(1.0e6 * max_tick_bias / nominal_tick,
+ 1.0 / tick_update_hz,
+ read_frequency, set_frequency,
+ have_setoffset ? apply_step_offset : NULL,
+ 0.0, 0.0, NULL, NULL);
}
/* ================================================== */
@@ -374,25 +394,17 @@ SYS_Linux_Initialise(void)
void
SYS_Linux_Finalise(void)
{
- SYS_Generic_Finalise();
+ SYS_Timex_Finalise();
}
/* ================================================== */
#ifdef FEAT_PRIVDROP
void
-SYS_Linux_DropRoot(char *user)
+SYS_Linux_DropRoot(uid_t uid, gid_t gid)
{
- struct passwd *pw;
cap_t cap;
- if (user == NULL)
- return;
-
- if ((pw = getpwnam(user)) == NULL) {
- LOG_FATAL(LOGF_SysLinux, "getpwnam(%s) failed", user);
- }
-
if (prctl(PR_SET_KEEPCAPS, 1)) {
LOG_FATAL(LOGF_SysLinux, "prctl() failed");
}
@@ -401,12 +413,12 @@ SYS_Linux_DropRoot(char *user)
LOG_FATAL(LOGF_SysLinux, "setgroups() failed");
}
- if (setgid(pw->pw_gid)) {
- LOG_FATAL(LOGF_SysLinux, "setgid(%d) failed", pw->pw_gid);
+ if (setgid(gid)) {
+ LOG_FATAL(LOGF_SysLinux, "setgid(%d) failed", gid);
}
- if (setuid(pw->pw_uid)) {
- LOG_FATAL(LOGF_SysLinux, "setuid(%d) failed", pw->pw_uid);
+ if (setuid(uid)) {
+ LOG_FATAL(LOGF_SysLinux, "setuid(%d) failed", uid);
}
if ((cap = cap_from_text("cap_net_bind_service,cap_sys_time=ep")) == NULL) {
@@ -419,7 +431,146 @@ SYS_Linux_DropRoot(char *user)
cap_free(cap);
- DEBUG_LOG(LOGF_SysLinux, "Privileges dropped to user %s", user);
+ DEBUG_LOG(LOGF_SysLinux, "Root dropped to uid %d gid %d", uid, gid);
+}
+#endif
+
+/* ================================================== */
+
+#ifdef FEAT_SCFILTER
+static
+void check_seccomp_applicability(void)
+{
+ int mail_enabled;
+ double mail_threshold;
+ char *mail_user;
+
+ CNF_GetMailOnChange(&mail_enabled, &mail_threshold, &mail_user);
+ if (mail_enabled)
+ LOG_FATAL(LOGF_SysLinux, "mailonchange directive cannot be used with -F enabled");
+}
+
+/* ================================================== */
+
+void
+SYS_Linux_EnableSystemCallFilter(int level)
+{
+ const int syscalls[] = {
+ /* Clock */
+ SCMP_SYS(adjtimex), SCMP_SYS(gettimeofday), SCMP_SYS(settimeofday),
+ SCMP_SYS(time),
+ /* Process */
+ SCMP_SYS(clone), SCMP_SYS(exit), SCMP_SYS(exit_group),
+ SCMP_SYS(rt_sigreturn), SCMP_SYS(sigreturn),
+ /* Memory */
+ SCMP_SYS(brk), SCMP_SYS(madvise), SCMP_SYS(mmap), SCMP_SYS(mmap2),
+ SCMP_SYS(mprotect), SCMP_SYS(munmap), SCMP_SYS(shmdt),
+ /* Filesystem */
+ SCMP_SYS(chmod), SCMP_SYS(chown), SCMP_SYS(chown32), SCMP_SYS(fstat),
+ SCMP_SYS(fstat64), SCMP_SYS(lseek), SCMP_SYS(rename), SCMP_SYS(stat),
+ SCMP_SYS(stat64), SCMP_SYS(unlink),
+ /* Socket */
+ SCMP_SYS(bind), SCMP_SYS(connect), SCMP_SYS(getsockname),
+ SCMP_SYS(recvfrom), SCMP_SYS(recvmsg), SCMP_SYS(sendmmsg),
+ SCMP_SYS(sendmsg), SCMP_SYS(sendto),
+ /* TODO: check socketcall arguments */
+ SCMP_SYS(socketcall),
+ /* General I/O */
+ SCMP_SYS(_newselect), SCMP_SYS(close), SCMP_SYS(open), SCMP_SYS(pipe),
+ SCMP_SYS(poll), SCMP_SYS(read), SCMP_SYS(futex), SCMP_SYS(select),
+ SCMP_SYS(set_robust_list), SCMP_SYS(write),
+ /* Miscellaneous */
+ SCMP_SYS(uname),
+ };
+
+ const int socket_domains[] = {
+ AF_NETLINK, AF_UNIX, AF_INET,
+#ifdef FEAT_IPV6
+ AF_INET6,
+#endif
+ };
+
+ const static int socket_options[][2] = {
+ { SOL_IP, IP_PKTINFO }, { SOL_IP, IP_FREEBIND },
+#ifdef FEAT_IPV6
+ { SOL_IPV6, IPV6_V6ONLY }, { SOL_IPV6, IPV6_RECVPKTINFO },
+#endif
+ { SOL_SOCKET, SO_BROADCAST }, { SOL_SOCKET, SO_REUSEADDR },
+ { SOL_SOCKET, SO_TIMESTAMP },
+ };
+
+ const static int fcntls[] = { F_GETFD, F_SETFD };
+
+ const static unsigned long ioctls[] = {
+ FIONREAD,
+#ifdef FEAT_PPS
+ PTP_SYS_OFFSET,
+#endif
+#ifdef FEAT_PPS
+ PPS_FETCH,
+#endif
+#ifdef FEAT_RTC
+ RTC_RD_TIME, RTC_SET_TIME, RTC_UIE_ON, RTC_UIE_OFF,
+#endif
+ };
+
+ scmp_filter_ctx *ctx;
+ int i;
+
+ /* Check if the chronyd configuration is supported */
+ check_seccomp_applicability();
+
+ ctx = seccomp_init(level > 0 ? SCMP_ACT_KILL : SCMP_ACT_TRAP);
+ if (ctx == NULL)
+ LOG_FATAL(LOGF_SysLinux, "Failed to initialize seccomp");
+
+ /* Add system calls that are always allowed */
+ for (i = 0; i < (sizeof (syscalls) / sizeof (*syscalls)); i++) {
+ if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscalls[i], 0) < 0)
+ goto add_failed;
+ }
+
+ /* Allow sockets to be created only in selected domains */
+ for (i = 0; i < sizeof (socket_domains) / sizeof (*socket_domains); i++) {
+ if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(socket), 1,
+ SCMP_A0(SCMP_CMP_EQ, socket_domains[i])) < 0)
+ goto add_failed;
+ }
+
+ /* Allow setting only selected sockets options */
+ for (i = 0; i < sizeof (socket_options) / sizeof (*socket_options); i++) {
+ if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(setsockopt), 3,
+ SCMP_A1(SCMP_CMP_EQ, socket_options[i][0]),
+ SCMP_A2(SCMP_CMP_EQ, socket_options[i][1]),
+ SCMP_A4(SCMP_CMP_LE, sizeof (int))) < 0)
+ goto add_failed;
+ }
+
+ /* Allow only selected fcntl calls */
+ for (i = 0; i < sizeof (fcntls) / sizeof (*fcntls); i++) {
+ if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(fcntl), 1,
+ SCMP_A1(SCMP_CMP_EQ, fcntls[i])) < 0 ||
+ seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(fcntl64), 1,
+ SCMP_A1(SCMP_CMP_EQ, fcntls[i])) < 0)
+ goto add_failed;
+ }
+
+ /* Allow only selected ioctls */
+ for (i = 0; i < sizeof (ioctls) / sizeof (*ioctls); i++) {
+ if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(ioctl), 1,
+ SCMP_A1(SCMP_CMP_EQ, ioctls[i])) < 0)
+ goto add_failed;
+ }
+
+ if (seccomp_load(ctx) < 0)
+ LOG_FATAL(LOGF_SysLinux, "Failed to load seccomp rules");
+
+ LOG(LOGS_INFO, LOGF_SysLinux, "Loaded seccomp filter");
+ seccomp_release(ctx);
+ return;
+
+add_failed:
+ LOG_FATAL(LOGF_SysLinux, "Failed to add seccomp rules");
}
#endif
diff --git a/sys_linux.h b/sys_linux.h
index 46caf35..f2c6d59 100644
--- a/sys_linux.h
+++ b/sys_linux.h
@@ -31,7 +31,9 @@ extern void SYS_Linux_Initialise(void);
extern void SYS_Linux_Finalise(void);
-extern void SYS_Linux_DropRoot(char *user);
+extern void SYS_Linux_DropRoot(uid_t uid, gid_t gid);
+
+extern void SYS_Linux_EnableSystemCallFilter(int level);
extern void SYS_Linux_MemLockAll(int LockAll);
diff --git a/sys_macosx.c b/sys_macosx.c
index 30945a4..200b62c 100644
--- a/sys_macosx.c
+++ b/sys_macosx.c
@@ -42,8 +42,13 @@
#include <stdio.h>
#include <signal.h>
+#include <mach/mach.h>
+#include <mach/mach_time.h>
+#include <pthread.h>
+
#include "sys_macosx.h"
#include "localp.h"
+#include "sched.h"
#include "logging.h"
#include "util.h"
@@ -69,10 +74,27 @@ static double current_freq;
static double adjustment_requested;
-/* Kernel parameters to calculate adjtime error. */
+/* Interval in seconds between adjustments to cancel systematic drift */
+
+#define DRIFT_REMOVAL_INTERVAL (4.0)
+#define DRIFT_REMOVAL_INTERVAL_MIN (0.5)
+
+/* If current_drift_removal_interval / drift_removal_interval exceeds this
+ ratio, then restart the drift removal timer */
+
+#define DRIFT_REMOVAL_RESTART_RATIO (8.0)
-static int kern_tickadj;
-static long kern_bigadj;
+static double drift_removal_interval;
+static double current_drift_removal_interval;
+static struct timeval Tdrift;
+
+/* weighting applied to error in calculating drift_removal_interval */
+#define ERROR_WEIGHT (0.5)
+
+/* minimum resolution of current_frequency */
+#define FREQUENCY_RES (1.0e-9)
+
+#define NANOS_PER_MSEC (1000000ULL)
/* ================================================== */
@@ -84,10 +106,13 @@ clock_initialise(void)
offset_register = 0.0;
adjustment_requested = 0.0;
current_freq = 0.0;
+ drift_removal_interval = DRIFT_REMOVAL_INTERVAL;
+ current_drift_removal_interval = DRIFT_REMOVAL_INTERVAL;
if (gettimeofday(&T0, NULL) < 0) {
LOG_FATAL(LOGF_SysMacOSX, "gettimeofday() failed");
}
+ Tdrift = T0;
newadj.tv_sec = 0;
newadj.tv_usec = 0;
@@ -112,10 +137,8 @@ start_adjust(void)
{
struct timeval newadj, oldadj;
struct timeval T1;
- double elapsed, accrued_error;
+ double elapsed, accrued_error, predicted_error, drift_removal_elapsed;
double adjust_required;
- struct timeval exact_newadj;
- long delta, tickdelta;
double rounding_error;
double old_adjust_remaining;
@@ -127,26 +150,24 @@ start_adjust(void)
UTI_DiffTimevalsToDouble(&elapsed, &T1, &T0);
accrued_error = elapsed * current_freq;
- adjust_required = - (accrued_error + offset_register);
+ UTI_DiffTimevalsToDouble(&drift_removal_elapsed, &T1, &Tdrift);
- UTI_DoubleToTimeval(adjust_required, &exact_newadj);
+ /* To allow for the clock being stepped either forward or backwards, clamp
+ the elapsed time to bounds [ 0.0, current_drift_removal_interval ] */
+ drift_removal_elapsed = MIN(MAX(0.0, drift_removal_elapsed), current_drift_removal_interval);
- /* At this point, we need to round the required adjustment the
- same way the kernel does. */
+ predicted_error = (current_drift_removal_interval - drift_removal_elapsed) / 2.0 * current_freq;
- delta = exact_newadj.tv_sec * 1000000 + exact_newadj.tv_usec;
- if (delta > kern_bigadj || delta < -kern_bigadj)
- tickdelta = 10 * kern_tickadj;
- else
- tickdelta = kern_tickadj;
- if (delta % tickdelta)
- delta = delta / tickdelta * tickdelta;
- newadj.tv_sec = 0;
- newadj.tv_usec = (int)delta;
- UTI_NormaliseTimeval(&newadj);
+ DEBUG_LOG(LOGF_SysMacOSX, "drift_removal_elapsed: %.3f current_drift_removal_interval: %.3f predicted_error: %.3f",
+ 1.0e6 * drift_removal_elapsed,
+ 1.0e6 * current_drift_removal_interval,
+ 1.0e6 * predicted_error);
- /* Add rounding error back onto offset register. */
- UTI_DiffTimevalsToDouble(&rounding_error, &newadj, &exact_newadj);
+ adjust_required = - (accrued_error + offset_register + predicted_error);
+
+ UTI_DoubleToTimeval(adjust_required, &newadj);
+ UTI_TimevalToDouble(&newadj, &adjustment_requested);
+ rounding_error = adjust_required - adjustment_requested;
if (adjtime(&newadj, &oldadj) < 0) {
LOG_FATAL(LOGF_SysMacOSX, "adjtime() failed");
@@ -154,10 +175,9 @@ start_adjust(void)
UTI_TimevalToDouble(&oldadj, &old_adjust_remaining);
- offset_register = rounding_error - old_adjust_remaining;
+ offset_register = rounding_error - old_adjust_remaining - predicted_error;
T0 = T1;
- UTI_TimevalToDouble(&newadj, &adjustment_requested);
}
/* ================================================== */
@@ -272,33 +292,129 @@ get_offset_correction(struct timeval *raw,
/* ================================================== */
-void
-SYS_MacOSX_Initialise(void)
+/* Cancel systematic drift */
+
+static int drift_removal_running = 0;
+static SCH_TimeoutID drift_removal_id;
+
+/* ================================================== */
+/* This is the timer callback routine which is called periodically to
+ invoke a time adjustment to take out the machine's drift.
+ Otherwise, times reported through this software (e.g. by running
+ ntpdate from another machine) show the machine being correct (since
+ they correct for drift build-up), but any program on this machine
+ that reads the system time will be given an erroneous value, the
+ degree of error depending on how long it is since
+ get_offset_correction was last called. */
+
+static void
+drift_removal_timeout(SCH_ArbitraryArgument not_used)
+{
+
+ stop_adjust();
+
+ if (gettimeofday(&Tdrift, NULL) < 0) {
+ LOG_FATAL(LOGF_SysMacOSX, "gettimeofday() failed");
+ }
+
+ current_drift_removal_interval = drift_removal_interval;
+
+ start_adjust();
+
+ drift_removal_id = SCH_AddTimeoutByDelay(drift_removal_interval, drift_removal_timeout, NULL);
+}
+
+/* ================================================== */
+
+/* use est_error to calculate the drift_removal_interval */
+
+static void
+set_sync_status(int synchronised, double est_error, double max_error)
{
- int result;
- size_t len;
- struct clockinfo clockinfo;
- int mib[2];
+ double interval;
- mib[0] = CTL_KERN;
- mib[1] = KERN_CLOCKRATE;
+ if (!synchronised) {
+ drift_removal_interval = MAX(drift_removal_interval, DRIFT_REMOVAL_INTERVAL);
+ } else {
+ interval = ERROR_WEIGHT * est_error / (fabs(current_freq) + FREQUENCY_RES);
+ drift_removal_interval = MAX(interval, DRIFT_REMOVAL_INTERVAL_MIN);
+
+ DEBUG_LOG(LOGF_SysMacOSX, "est_error: %.3f current_freq: %.3f est drift_removal_interval: %.3f act drift_removal_interval: %.3f",
+ est_error * 1.0e6, current_freq * 1.0e6, interval, drift_removal_interval);
+ }
+
+ if (current_drift_removal_interval / drift_removal_interval > DRIFT_REMOVAL_RESTART_RATIO) {
+ /* recover from a large est_error by resetting the timer */
+ SCH_ArbitraryArgument unused;
+ SCH_RemoveTimeout(drift_removal_id);
+ unused = NULL;
+ drift_removal_timeout(unused);
+ }
+}
+
+/* ================================================== */
+/*
+ Give chronyd real time priority so that time critical calculations
+ are not pre-empted by the kernel.
+*/
+
+static int
+set_realtime(void)
+{
+ /* https://developer.apple.com/library/ios/technotes/tn2169/_index.html */
+
+ mach_timebase_info_data_t timebase_info;
+ double clock2abs;
+ thread_time_constraint_policy_data_t policy;
+ int kr;
+
+ mach_timebase_info(&timebase_info);
+ clock2abs = ((double)timebase_info.denom / (double)timebase_info.numer) * NANOS_PER_MSEC;
+
+ policy.period = 0;
+ policy.computation = (uint32_t)(5 * clock2abs); /* 5 ms of work */
+ policy.constraint = (uint32_t)(10 * clock2abs);
+ policy.preemptible = 0;
+
+ kr = thread_policy_set(
+ pthread_mach_thread_np(pthread_self()),
+ THREAD_TIME_CONSTRAINT_POLICY,
+ (thread_policy_t)&policy,
+ THREAD_TIME_CONSTRAINT_POLICY_COUNT);
+
+ if (kr != KERN_SUCCESS) {
+ LOG(LOGS_WARN, LOGF_SysMacOSX, "Cannot set real-time priority: %d", kr);
+ return -1;
+ }
+ return 0;
+}
- len = sizeof(clockinfo);
- result = sysctl(mib, 2, &clockinfo, &len, NULL, 0);
+/* ================================================== */
- if(result < 0) {
- LOG_FATAL(LOGF_SysMacOSX, "Cannot read clockinfo");
+void
+SYS_MacOSX_SetScheduler(int SchedPriority)
+{
+ if (SchedPriority) {
+ set_realtime();
}
- kern_tickadj = clockinfo.tickadj;
- kern_bigadj = clockinfo.tick;
+}
+
+/* ================================================== */
+void
+SYS_MacOSX_Initialise(void)
+{
clock_initialise();
lcl_RegisterSystemDrivers(read_frequency, set_frequency,
accrue_offset, apply_step_offset,
get_offset_correction,
NULL /* set_leap */,
- NULL /* set_sync_status */);
+ set_sync_status);
+
+
+ drift_removal_id = SCH_AddTimeoutByDelay(drift_removal_interval, drift_removal_timeout, NULL);
+ drift_removal_running = 1;
}
/* ================================================== */
@@ -306,6 +422,10 @@ SYS_MacOSX_Initialise(void)
void
SYS_MacOSX_Finalise(void)
{
+ if (drift_removal_running) {
+ SCH_RemoveTimeout(drift_removal_id);
+ }
+
clock_finalise();
}
diff --git a/sys_macosx.h b/sys_macosx.h
index b579415..707700d 100644
--- a/sys_macosx.h
+++ b/sys_macosx.h
@@ -30,8 +30,8 @@
#ifndef GOT_SYS_MACOSX_H
#define GOT_SYS_MACOSX_H
+void SYS_MacOSX_SetScheduler(int SchedPriority);
void SYS_MacOSX_Initialise(void);
-
void SYS_MacOSX_Finalise(void);
#endif
diff --git a/sys_netbsd.c b/sys_netbsd.c
index 237f35f..11d8d04 100644
--- a/sys_netbsd.c
+++ b/sys_netbsd.c
@@ -4,6 +4,7 @@
**********************************************************************
* Copyright (C) Richard P. Curnow 1997-2001
* Copyright (C) J. Hannken-Illjes 2001
+ * Copyright (C) Miroslav Lichvar 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
@@ -27,302 +28,117 @@
#include "config.h"
-#ifdef __NetBSD__
-
-#include <kvm.h>
-#include <nlist.h>
-#include <fcntl.h>
-#include <assert.h>
-#include <sys/time.h>
-
-#include <stdio.h>
-#include <signal.h>
+#include "sysincl.h"
#include "sys_netbsd.h"
-#include "localp.h"
+#include "sys_timex.h"
#include "logging.h"
#include "util.h"
-/* ================================================== */
-
-/* This register contains the number of seconds by which the local
- clock was estimated to be fast of reference time at the epoch when
- gettimeofday() returned T0 */
-
-static double offset_register;
-
-/* This register contains the epoch to which the offset is referenced */
-
-static struct timeval T0;
-
-/* This register contains the current estimate of the system
- frequency, in absolute (NOT ppm) */
-
-static double current_freq;
-
-/* This register contains the number of seconds of adjustment that
- were passed to adjtime last time it was called. */
-
-static double adjustment_requested;
-
-/* Kernel parameters to calculate adjtime error. */
-
-static int kern_tickadj;
-static long kern_bigadj;
-
-/* ================================================== */
+/* Maximum frequency offset accepted by the kernel (in ppm) */
+#define MAX_FREQ 500.0
-static void
-clock_initialise(void)
-{
- struct timeval newadj, oldadj;
-
- offset_register = 0.0;
- adjustment_requested = 0.0;
- current_freq = 0.0;
-
- if (gettimeofday(&T0, NULL) < 0) {
- LOG_FATAL(LOGF_SysNetBSD, "gettimeofday() failed");
- }
+/* Minimum assumed rate at which the kernel updates the clock frequency */
+#define MIN_TICK_RATE 100
- newadj.tv_sec = 0;
- newadj.tv_usec = 0;
+/* Interval between kernel updates of the adjtime() offset */
+#define ADJTIME_UPDATE_INTERVAL 1.0
- if (adjtime(&newadj, &oldadj) < 0) {
- LOG_FATAL(LOGF_SysNetBSD, "adjtime() failed");
- }
+/* Maximum adjtime() slew rate (in ppm) */
+#define MAX_ADJTIME_SLEWRATE 5000.0
-}
+/* Minimum offset adjtime() slews faster than MAX_FREQ */
+#define MIN_FASTSLEW_OFFSET 1.0
/* ================================================== */
-static void
-clock_finalise(void)
-{
- /* Nothing to do yet */
-
-}
-
-/* ================================================== */
+/* Positive offset means system clock is fast of true time, therefore
+ slew backwards */
static void
-start_adjust(void)
+accrue_offset(double offset, double corr_rate)
{
struct timeval newadj, oldadj;
- struct timeval T1;
- double elapsed, accrued_error;
- double adjust_required;
- struct timeval exact_newadj;
- long delta, tickdelta;
- double rounding_error;
- double old_adjust_remaining;
-
- /* Determine the amount of error built up since the last adjustment */
- if (gettimeofday(&T1, NULL) < 0) {
- LOG_FATAL(LOGF_SysNetBSD, "gettimeofday() failed");
- }
-
- UTI_DiffTimevalsToDouble(&elapsed, &T1, &T0);
- accrued_error = elapsed * current_freq;
-
- adjust_required = - (accrued_error + offset_register);
- UTI_DoubleToTimeval(adjust_required, &exact_newadj);
+ UTI_DoubleToTimeval(-offset, &newadj);
- /* At this point, we need to round the required adjustment the
- same way the kernel does. */
-
- delta = exact_newadj.tv_sec * 1000000 + exact_newadj.tv_usec;
- if (delta > kern_bigadj || delta < -kern_bigadj)
- tickdelta = 10 * kern_tickadj;
- else
- tickdelta = kern_tickadj;
- if (delta % tickdelta)
- delta = delta / tickdelta * tickdelta;
- newadj.tv_sec = 0;
- newadj.tv_usec = delta;
- UTI_NormaliseTimeval(&newadj);
-
- /* Add rounding error back onto offset register. */
- UTI_DiffTimevalsToDouble(&rounding_error, &newadj, &exact_newadj);
-
- if (adjtime(&newadj, &oldadj) < 0) {
+ if (adjtime(&newadj, &oldadj) < 0)
LOG_FATAL(LOGF_SysNetBSD, "adjtime() failed");
- }
-
- UTI_TimevalToDouble(&oldadj, &old_adjust_remaining);
-
- offset_register = rounding_error - old_adjust_remaining;
-
- T0 = T1;
- UTI_TimevalToDouble(&newadj, &adjustment_requested);
+ /* Add the old remaining adjustment if not zero */
+ UTI_TimevalToDouble(&oldadj, &offset);
+ if (offset != 0.0) {
+ UTI_AddDoubleToTimeval(&newadj, offset, &newadj);
+ if (adjtime(&newadj, NULL) < 0)
+ LOG_FATAL(LOGF_SysNetBSD, "adjtime() failed");
+ }
}
/* ================================================== */
static void
-stop_adjust(void)
+get_offset_correction(struct timeval *raw,
+ double *corr, double *err)
{
- struct timeval T1;
- struct timeval zeroadj, remadj;
- double adjustment_remaining, adjustment_achieved;
- double elapsed, elapsed_plus_adjust;
-
- zeroadj.tv_sec = 0;
- zeroadj.tv_usec = 0;
+ struct timeval remadj;
+ double adjustment_remaining;
- if (adjtime(&zeroadj, &remadj) < 0) {
+ if (adjtime(NULL, &remadj) < 0)
LOG_FATAL(LOGF_SysNetBSD, "adjtime() failed");
- }
- if (gettimeofday(&T1, NULL) < 0) {
- LOG_FATAL(LOGF_SysNetBSD, "gettimeofday() failed");
- }
-
- UTI_DiffTimevalsToDouble(&elapsed, &T1, &T0);
UTI_TimevalToDouble(&remadj, &adjustment_remaining);
- adjustment_achieved = adjustment_requested - adjustment_remaining;
- elapsed_plus_adjust = elapsed - adjustment_achieved;
-
- offset_register += current_freq * elapsed_plus_adjust - adjustment_remaining;
-
- adjustment_requested = 0.0;
- T0 = T1;
-
-}
-
-/* ================================================== */
-
-/* Positive offset means system clock is fast of true time, therefore
- slew backwards */
-
-static void
-accrue_offset(double offset, double corr_rate)
-{
- stop_adjust();
- offset_register += offset;
- start_adjust();
-
-}
-
-/* ================================================== */
-
-/* Positive offset means system clock is fast of true time, therefore
- step backwards */
-
-static int
-apply_step_offset(double offset)
-{
- struct timeval old_time, new_time, T1;
-
- stop_adjust();
-
- if (gettimeofday(&old_time, NULL) < 0) {
- LOG_FATAL(LOGF_SysNetBSD, "gettimeofday() failed");
- }
-
- UTI_AddDoubleToTimeval(&old_time, -offset, &new_time);
-
- if (settimeofday(&new_time, NULL) < 0) {
- DEBUG_LOG(LOGF_SysNetBSD, "settimeofday() failed");
- return 0;
+ *corr = adjustment_remaining;
+ if (err) {
+ if (*corr != 0.0)
+ *err = 1.0e-6 * MAX_ADJTIME_SLEWRATE / ADJTIME_UPDATE_INTERVAL;
+ else
+ *err = 0.0;
}
-
- UTI_AddDoubleToTimeval(&T0, offset, &T1);
- T0 = T1;
-
- start_adjust();
-
- return 1;
-}
-
-/* ================================================== */
-
-static double
-set_frequency(double new_freq_ppm)
-{
- stop_adjust();
- current_freq = new_freq_ppm * 1.0e-6;
- start_adjust();
-
- return current_freq * 1.0e6;
}
/* ================================================== */
-static double
-read_frequency(void)
+void
+SYS_NetBSD_Initialise(void)
{
- return current_freq * 1.0e6;
+ SYS_Timex_InitialiseWithFunctions(MAX_FREQ, 1.0 / MIN_TICK_RATE,
+ NULL, NULL, NULL,
+ MIN_FASTSLEW_OFFSET, MAX_ADJTIME_SLEWRATE,
+ accrue_offset, get_offset_correction);
}
/* ================================================== */
-static void
-get_offset_correction(struct timeval *raw,
- double *corr, double *err)
+void
+SYS_NetBSD_Finalise(void)
{
- stop_adjust();
- *corr = -offset_register;
- start_adjust();
- if (err)
- *err = 0.0;
+ SYS_Timex_Finalise();
}
/* ================================================== */
+#ifdef FEAT_PRIVDROP
void
-SYS_NetBSD_Initialise(void)
+SYS_NetBSD_DropRoot(uid_t uid, gid_t gid)
{
- static struct nlist nl[] = {
- {"_tickadj"},
- {"_bigadj"},
- {NULL}
- };
-
- kvm_t *kt;
+ int fd;
- kt = kvm_open(NULL, NULL, NULL, O_RDONLY, NULL);
- if (!kt) {
- LOG_FATAL(LOGF_SysNetBSD, "Cannot open kvm");
- }
+ if (setgroups(0, NULL))
+ LOG_FATAL(LOGF_SysNetBSD, "setgroups() failed : %s", strerror(errno));
- if (kvm_nlist(kt, nl) < 0) {
- LOG_FATAL(LOGF_SysNetBSD, "Cannot read kernel symbols");
- }
+ if (setgid(gid))
+ LOG_FATAL(LOGF_SysNetBSD, "setgid(%d) failed : %s", gid, strerror(errno));
- if (kvm_read(kt, nl[0].n_value, (char *)(&kern_tickadj), sizeof(int)) < 0) {
- LOG_FATAL(LOGF_SysNetBSD, "Cannot read from _tickadj");
- }
-
- if (kvm_read(kt, nl[1].n_value, (char *)(&kern_bigadj), sizeof(long)) < 0) {
- /* kernel doesn't have the symbol, use one second instead */
- kern_bigadj = 1000000;
- }
+ if (setuid(uid))
+ LOG_FATAL(LOGF_SysNetBSD, "setuid(%d) failed : %s", uid, strerror(errno));
- kvm_close(kt);
-
- clock_initialise();
-
- lcl_RegisterSystemDrivers(read_frequency, set_frequency,
- accrue_offset, apply_step_offset,
- get_offset_correction,
- NULL /* set_leap */,
- NULL /* set_sync_status */);
+ DEBUG_LOG(LOGF_SysNetBSD, "Root dropped to uid %d gid %d", uid, gid);
+ /* Check if we have write access to /dev/clockctl */
+ fd = open("/dev/clockctl", O_WRONLY);
+ if (fd < 0)
+ LOG_FATAL(LOGF_SysNetBSD, "Can't write to /dev/clockctl");
+ close(fd);
}
-
-/* ================================================== */
-
-void
-SYS_NetBSD_Finalise(void)
-{
- clock_finalise();
-}
-
-/* ================================================== */
-
-
-#endif /* __NetBSD__ */
+#endif
diff --git a/sys_netbsd.h b/sys_netbsd.h
index a697304..052f5b7 100644
--- a/sys_netbsd.h
+++ b/sys_netbsd.h
@@ -32,4 +32,6 @@ void SYS_NetBSD_Initialise(void);
void SYS_NetBSD_Finalise(void);
+void SYS_NetBSD_DropRoot(uid_t uid, gid_t gid);
+
#endif
diff --git a/sys_solaris.c b/sys_solaris.c
index fe8b63a..86f6f79 100644
--- a/sys_solaris.c
+++ b/sys_solaris.c
@@ -26,420 +26,18 @@
#include "config.h"
-#ifdef SOLARIS
-
-#include <kvm.h>
-#include <fcntl.h>
-#include <nlist.h>
-#include <assert.h>
-#include <sys/time.h>
-#include <sys/utsname.h>
-
-#include <stdio.h>
+#include "sysincl.h"
#include "sys_solaris.h"
-#include "localp.h"
-#include "sched.h"
-#include "logging.h"
-#include "util.h"
-
-/* ================================================== */
-
-/* This register contains the number of seconds by which the local
- clock was estimated to be fast of reference time at the epoch when
- gettimeofday() returned T0 */
-
-static double offset_register;
-
-/* This register contains the epoch to which the offset is referenced */
-
-static struct timeval T0;
-
-/* This register contains the current estimate of the system
- frequency, in absolute (NOT ppm) */
-
-static double current_freq;
-
-/* This register contains the number of seconds of adjustment that
- were passed to adjtime last time it was called. */
-
-static double adjustment_requested;
-
-/* ================================================== */
-/* On Solaris 2.5 & 2.5.1, passing an argument of zero as the new
- delta to adjtime does not zero out the adjustment - the remaining
- adjustment is returned as the old delta arg, but the adjustment keeps
- running. To get round this, we set adjustments of +/-1us when we
- really want zero. Alternate adjustments are used to avoid a drift
- from building up. */
-
-static struct timeval zeroes[2] = {
- {0, 1},
- {-1, 999999}
-};
-
-static int index=0;
-
-/* If 1, need to run dosynctodr(). If 0, don't */
-static int need_dosynctodr = -1;
-
-
-#define GET_ZERO (zeroes[index^=1])
-
-/* ================================================== */
-
-static void
-clock_initialise(void)
-{
- struct timeval newadj, oldadj;
-
- offset_register = 0.0;
- adjustment_requested = 0.0;
- current_freq = 0.0;
-
- if (gettimeofday(&T0, NULL) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "gettimeofday() failed");
- }
-
- newadj = GET_ZERO;
-
- if (adjtime(&newadj, &oldadj) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "adjtime() failed");
- }
-
- if (adjtime(&newadj, &oldadj) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "adjtime() failed");
- }
-}
-
-/* ================================================== */
-
-static void
-clock_finalise(void)
-{
- /* Nothing to do yet */
-}
-
-/* ================================================== */
-
-static void
-start_adjust(void)
-{
- struct timeval newadj, oldadj;
- struct timeval T1;
- double elapsed, accrued_error;
- double adjust_required;
- struct timeval exact_newadj;
- double rounding_error;
- double old_adjust_remaining;
-
- /* Determine the amount of error built up since the last adjustment */
- if (gettimeofday(&T1, NULL) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "gettimeofday() failed");
- }
-
- UTI_DiffTimevalsToDouble(&elapsed, &T1, &T0);
- accrued_error = elapsed * current_freq;
-
- adjust_required = - (accrued_error + offset_register);
-
- UTI_DoubleToTimeval(adjust_required, &exact_newadj);
-
- /* At this point, we will need to call the adjustment rounding
- algorithm in the system-specific layer. For now, just assume the
- adjustment can be applied exactly. */
-
- newadj = exact_newadj;
-
- /* Want to *add* rounding error back onto offset register */
- UTI_DiffTimevalsToDouble(&rounding_error, &exact_newadj, &newadj);
-
- if (adjtime(&newadj, &oldadj) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "adjtime() failed");
- }
-
- UTI_TimevalToDouble(&oldadj, &old_adjust_remaining);
-
- offset_register = rounding_error - old_adjust_remaining;
-
- T0 = T1;
- UTI_TimevalToDouble(&newadj, &adjustment_requested);
-
-}
-
-/* ================================================== */
-
-static void
-stop_adjust(void)
-{
- struct timeval T1;
- struct timeval zeroadj, remadj;
- double adjustment_remaining, adjustment_achieved;
- double elapsed, elapsed_plus_adjust;
-
-
- zeroadj = GET_ZERO;
-
- if (adjtime(&zeroadj, &remadj) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "adjtime() failed");
- }
-
- if (gettimeofday(&T1, NULL) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "gettimeofday() failed");
- }
-
- UTI_DiffTimevalsToDouble(&elapsed, &T1, &T0);
- UTI_TimevalToDouble(&remadj, &adjustment_remaining);
-
- adjustment_achieved = adjustment_requested - adjustment_remaining;
- elapsed_plus_adjust = elapsed - adjustment_achieved;
-
- offset_register += current_freq * elapsed_plus_adjust - adjustment_remaining;
-
- adjustment_requested = 0.0;
- T0 = T1;
-
-}
-
-/* ================================================== */
-
-/* Positive offset means system clock is fast of true time, therefore
- slew backwards */
-
-static void
-accrue_offset(double offset, double corr_rate)
-{
- stop_adjust();
- offset_register += offset;
- start_adjust();
-}
-
-/* ================================================== */
-
-/* Positive offset means system clock is fast of true time, therefore
- step backwards */
-
-static int
-apply_step_offset(double offset)
-{
- struct timeval old_time, new_time, rounded_new_time, T1;
- double rounding_error;
-
- stop_adjust();
- if (gettimeofday(&old_time, NULL) < 0) {
- LOG_FATAL(LOGF_SysSolaris, "gettimeofday() failed");
- }
-
- UTI_AddDoubleToTimeval(&old_time, -offset, &new_time);
-
- /* The settimeofday function (on Solaris 2.5/Sparc20 at least) does
- not work quite as we would want. The time we want to set is
- rounded to the nearest second and that time is used. Also, the
- clock appears to start from that second boundary plus about 4ms.
- For now we'll tolerate this small error. */
-
- rounded_new_time.tv_usec = 0;
- if (new_time.tv_usec >= 500000) {
- rounded_new_time.tv_sec = new_time.tv_sec + 1;
- } else {
- rounded_new_time.tv_sec = new_time.tv_sec;
- }
-
- UTI_DiffTimevalsToDouble(&rounding_error, &rounded_new_time, &new_time);
-
- if (settimeofday(&new_time, NULL) < 0) {
- DEBUG_LOG(LOGF_SysSolaris, "settimeofday() failed");
- return 0;
- }
-
- UTI_AddDoubleToTimeval(&T0, offset, &T1);
- T0 = T1;
-
- offset_register += rounding_error;
-
- start_adjust();
-
- return 1;
-}
-
-/* ================================================== */
-
-static double
-set_frequency(double new_freq_ppm)
-{
- stop_adjust();
- current_freq = new_freq_ppm * 1.0e-6;
- start_adjust();
-
- return current_freq * 1.0e6;
-}
-
-/* ================================================== */
-
-static double
-read_frequency(void)
-{
- return current_freq * 1.0e6;
-}
-
-/* ================================================== */
-
-static void
-get_offset_correction(struct timeval *raw,
- double *corr, double *err)
-{
- stop_adjust();
- *corr = -offset_register;
- start_adjust();
- if (err)
- *err = 0.0;
-}
-
-/* ================================================== */
-
-static void
-immediate_step(void)
-{
-}
-
-/* ================================================== */
-
-/* Interval in seconds between adjustments to cancel systematic drift */
-#define DRIFT_REMOVAL_INTERVAL (4.0)
-
-static int drift_removal_running = 0;
-static SCH_TimeoutID drift_removal_id;
-
-/* ================================================== */
-/* This is the timer callback routine which is called periodically to
- invoke a time adjustment to take out the machine's drift.
- Otherwise, times reported through this software (e.g. by running
- ntpdate from another machine) show the machine being correct (since
- they correct for drift build-up), but any program on this machine
- that reads the system time will be given an erroneous value, the
- degree of error depending on how long it is since
- get_offset_correction was last called. */
-
-static void
-drift_removal_timeout(SCH_ArbitraryArgument not_used)
-{
- stop_adjust();
- start_adjust();
- drift_removal_id = SCH_AddTimeoutByDelay(DRIFT_REMOVAL_INTERVAL, drift_removal_timeout, NULL);
-}
-
-/* ================================================== */
-
-static void
-check_need_dosynctodr(void)
-{
- struct utsname name;
- int result;
- int major, minor, veryminor, n_fields;
-
- result = uname(&name);
- if (result < 0) {
- LOG(LOGS_ERR, LOGF_SysSolaris, "Cannot use uname to detect Solaris version");
- need_dosynctodr = 0; /* Assume recent Solaris where it isn't needed */
- return;
- }
-
- n_fields = sscanf(name.release, "%d.%d.%d\n", &major, &minor, &veryminor);
-
- if (n_fields < 2) {
- LOG(LOGS_ERR, LOGF_SysSolaris, "Solaris version doesn't appear to be of the form X.Y[.Z]");
- need_dosynctodr = 0; /* Assume recent Solaris where it isn't needed */
- return;
- }
-
- if (major != 5) {
- LOG(LOGS_ERR, LOGF_SysSolaris, "Solaris major version doesn't appear to be 5");
- need_dosynctodr = 0; /* Assume recent Solaris where it isn't needed */
- return;
- }
-
- /* The 'rule of thumb' is that from Solaris 2.6 onwards, dosynctodr() doesn't
- * need to be called, and in fact it is counter-productive to do so. For
- * earlier versions, it is required. */
-
- if (minor < 6) {
- need_dosynctodr = 1;
- } else {
- need_dosynctodr = 0;
- }
-
-}
-
-/* ================================================== */
-
-static void
-set_dosynctodr(unsigned long on_off)
-{
- static struct nlist nl[] = {
- {"dosynctodr"},
- {NULL}
- };
-
- kvm_t *kt;
- unsigned long read_back;
-
- assert(on_off == 1 || on_off == 0);
-
- kt = kvm_open(NULL, NULL, NULL, O_RDWR, NULL);
- if (!kt) {
- LOG(LOGS_ERR, LOGF_SysSolaris, "Cannot open kvm to change dosynctodr");
- return;
- }
-
- if (kvm_nlist(kt, nl) < 0) {
- LOG(LOGS_ERR, LOGF_SysSolaris, "Cannot read dosynctodr in nlist");
- kvm_close(kt);
- return;
- }
-
- if (kvm_write(kt, nl[0].n_value, (char *)(&on_off), sizeof(unsigned long)) < 0) {
- LOG(LOGS_ERR, LOGF_SysSolaris, "Cannot write to dosynctodr");
- kvm_close(kt);
- return;
- }
-
- if (kvm_read(kt, nl[0].n_value, (char *)(&read_back), sizeof(unsigned long)) < 0) {
- LOG(LOGS_ERR, LOGF_SysSolaris, "Cannot read from dosynctodr");
- kvm_close(kt);
- return;
- }
-
- kvm_close(kt);
-
- assert(read_back == on_off);
-}
+#include "sys_timex.h"
/* ================================================== */
void
SYS_Solaris_Initialise(void)
{
-
- check_need_dosynctodr();
-
- /* Need to do KVM stuff to turn off dosynctodr. */
-
- clock_initialise();
-
- lcl_RegisterSystemDrivers(read_frequency, set_frequency,
- accrue_offset, apply_step_offset,
- get_offset_correction,
- NULL /* set_leap */,
- NULL /* set_sync_status */);
-
- /* Turn off the kernel switch that keeps the system clock in step
- with the non-volatile clock */
- if (need_dosynctodr) {
- set_dosynctodr(0);
- }
-
- drift_removal_id = SCH_AddTimeoutByDelay(DRIFT_REMOVAL_INTERVAL, drift_removal_timeout, NULL);
- drift_removal_running = 1;
+ /* The kernel allows the frequency to be set in the full range off int32_t */
+ SYS_Timex_InitialiseWithFunctions(32500, 1.0 / 100, NULL, NULL, NULL);
}
/* ================================================== */
@@ -447,21 +45,5 @@ SYS_Solaris_Initialise(void)
void
SYS_Solaris_Finalise(void)
{
-
- if (drift_removal_running) {
- SCH_RemoveTimeout(drift_removal_id);
- }
-
- clock_finalise();
-
- /* When exiting, we want to return the machine to its 'autonomous'
- tracking mode */
- if (need_dosynctodr) {
- set_dosynctodr(1);
- }
+ SYS_Timex_Finalise();
}
-
-/* ================================================== */
-
-#endif /* SOLARIS */
-
diff --git a/sys_sunos.c b/sys_sunos.c
deleted file mode 100644
index 7d0737e..0000000
--- a/sys_sunos.c
+++ /dev/null
@@ -1,418 +0,0 @@
-/*
- chronyd/chronyc - Programs for keeping computer clocks accurate.
-
- **********************************************************************
- * Copyright (C) Richard P. Curnow 1997-2003
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of version 2 of the GNU General Public License as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- **********************************************************************
-
- =======================================================================
-
- Driver file for the SunOS 4.1.x operating system.
- */
-
-#include "config.h"
-
-#ifdef SUNOS
-
-#include <kvm.h>
-#include <fcntl.h>
-#include <nlist.h>
-#include <assert.h>
-#include <sys/time.h>
-
-#include <stdio.h>
-#include <signal.h>
-
-#include "sys_sunos.h"
-#include "localp.h"
-#include "logging.h"
-#include "util.h"
-#include "sched.h"
-
-/* ================================================== */
-
-/* This register contains the number of seconds by which the local
- clock was estimated to be fast of reference time at the epoch when
- gettimeofday() returned T0 */
-
-static double offset_register;
-
-/* This register contains the epoch to which the offset is referenced */
-
-static struct timeval T0;
-
-/* This register contains the current estimate of the system
- frequency, in absolute (NOT ppm) */
-
-static double current_freq;
-
-/* This register contains the number of seconds of adjustment that
- were passed to adjtime last time it was called. */
-
-static double adjustment_requested;
-
-/* Eventually, this needs to be a user-defined parameter - e.g. user
- might want 5 to get much finer resolution like xntpd. We stick
- with a reasonable number so that slewing can work.
-
- This value has to be a factor of 1 million, otherwise the noddy
- method we use for rounding an adjustment to the nearest multiple of
- this value won't work!!
-
- */
-static unsigned long our_tickadj = 100;
-
-/* ================================================== */
-
-static void
-clock_initialise(void)
-{
- struct timeval newadj, oldadj;
-
- offset_register = 0.0;
- adjustment_requested = 0.0;
- current_freq = 0.0;
-
- if (gettimeofday(&T0, NULL) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "gettimeofday() failed");
- }
-
- newadj.tv_sec = 0;
- newadj.tv_usec = 0;
-
- if (adjtime(&newadj, &oldadj) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "adjtime() failed");
- }
-
- if (adjtime(&newadj, &oldadj) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "adjtime() failed");
- }
-}
-
-/* ================================================== */
-
-static void
-clock_finalise(void)
-{
- /* Nothing to do yet */
-}
-
-/* ================================================== */
-
-static void
-start_adjust(void)
-{
- struct timeval newadj, oldadj;
- struct timeval T1;
- double elapsed, accrued_error;
- double adjust_required;
- struct timeval exact_newadj;
- double rounding_error;
- double old_adjust_remaining;
- long remainder, multiplier;
-
- /* Determine the amount of error built up since the last adjustment */
- if (gettimeofday(&T1, NULL) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "gettimeofday() failed");
- }
-
- UTI_DiffTimevalsToDouble(&elapsed, &T1, &T0);
- accrued_error = elapsed * current_freq;
-
- adjust_required = - (accrued_error + offset_register);
-
- UTI_DoubleToTimeval(adjust_required, &exact_newadj);
-
- /* At this point, we need to round the required adjustment to the
- closest multiple of _tickadj --- because SunOS can't process
- other adjustments exactly and will silently discard the residual.
- Obviously such behaviour can't be tolerated for us. */
-
- newadj = exact_newadj;
- remainder = newadj.tv_usec % our_tickadj;
- multiplier = newadj.tv_usec / our_tickadj;
- if (remainder >= (our_tickadj >> 1)) {
- newadj.tv_usec = (multiplier + 1) * our_tickadj;
- } else {
- newadj.tv_usec = multiplier * our_tickadj;
- }
-
- UTI_NormaliseTimeval(&newadj);
-
- /* Want to *add* rounding error back onto offset register. Note
- that the exact adjustment was the offset register *negated* */
- UTI_DiffTimevalsToDouble(&rounding_error, &newadj, &exact_newadj);
-
- if (adjtime(&newadj, &oldadj) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "adjtime() failed");
- }
-
- UTI_TimevalToDouble(&oldadj, &old_adjust_remaining);
-
- offset_register = rounding_error - old_adjust_remaining;
-
- T0 = T1;
- UTI_TimevalToDouble(&newadj, &adjustment_requested);
-
-}
-
-/* ================================================== */
-
-static void
-stop_adjust(void)
-{
- struct timeval T1;
- struct timeval zeroadj, remadj;
- double adjustment_remaining, adjustment_achieved;
- double gap;
- double elapsed, elapsed_plus_adjust;
-
- zeroadj.tv_sec = 0;
- zeroadj.tv_usec = 0;
-
- if (adjtime(&zeroadj, &remadj) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "adjtime() failed");
- }
-
- if (gettimeofday(&T1, NULL) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "gettimeofday() failed");
- }
-
- UTI_DiffTimevalsToDouble(&elapsed, &T1, &T0);
- UTI_TimevalToDouble(&remadj, &adjustment_remaining);
-
- adjustment_achieved = adjustment_requested - adjustment_remaining;
- elapsed_plus_adjust = elapsed - adjustment_achieved;
-
- offset_register += current_freq * elapsed_plus_adjust - adjustment_remaining;
-
- adjustment_requested = 0.0;
- T0 = T1;
-
-}
-
-/* ================================================== */
-
-/* Positive offset means system clock is fast of true time, therefore
- slew backwards */
-
-static void
-accrue_offset(double offset, double corr_rate)
-{
- stop_adjust();
- offset_register += offset;
- start_adjust();
-}
-
-/* ================================================== */
-
-/* Positive offset means system clock is fast of true time, therefore
- step backwards */
-
-static int
-apply_step_offset(double offset)
-{
- struct timeval old_time, new_time, T1;
-
- stop_adjust();
- if (gettimeofday(&old_time, NULL) < 0) {
- LOG_FATAL(LOGF_SysSunOS, "gettimeofday() failed");
- }
-
- UTI_AddDoubleToTimeval(&old_time, -offset, &new_time);
-
- if (settimeofday(&new_time, NULL) < 0) {
- DEBUG_LOG(LOGF_SysSunOS, "settimeofday() failed");
- return 0;
- }
-
- UTI_AddDoubleToTimeval(&T0, offset, &T1);
- T0 = T1;
-
- start_adjust();
-
- return 1;
-}
-
-/* ================================================== */
-
-static double
-set_frequency(double new_freq_ppm)
-{
- stop_adjust();
- current_freq = new_freq_ppm * 1.0e-6;
- start_adjust();
-
- return current_freq * 1.0e6;
-}
-
-/* ================================================== */
-
-static double
-read_frequency(void)
-{
- return current_freq * 1.0e6;
-}
-
-/* ================================================== */
-
-static void
-get_offset_correction(struct timeval *raw,
- double *corr, double *err)
-{
- stop_adjust();
- *corr = -offset_register;
- start_adjust();
- if (err)
- *err = 0.0;
-}
-
-/* ================================================== */
-
-static void
-immediate_step(void)
-{
-}
-
-/* ================================================== */
-
-/* Interval in seconds between adjustments to cancel systematic drift */
-#define DRIFT_REMOVAL_INTERVAL (4.0)
-
-static int drift_removal_running = 0;
-static SCH_TimeoutID drift_removal_id;
-
-/* ================================================== */
-/* This is the timer callback routine which is called periodically to
- invoke a time adjustment to take out the machine's drift.
- Otherwise, times reported through this software (e.g. by running
- ntpdate from another machine) show the machine being correct (since
- they correct for drift build-up), but any program on this machine
- that reads the system time will be given an erroneous value, the
- degree of error depending on how long it is since
- get_offset_correction was last called. */
-
-static void
-drift_removal_timeout(SCH_ArbitraryArgument not_used)
-{
- stop_adjust();
- start_adjust();
- drift_removal_id = SCH_AddTimeoutByDelay(DRIFT_REMOVAL_INTERVAL, drift_removal_timeout, NULL);
-}
-
-/* ================================================== */
-
-static void
-setup_kernel(unsigned long on_off)
-{
- static struct nlist nl[] = {
- {"_dosynctodr"},
- {"_tick"},
- {"_tickadj"},
- {NULL}
- };
-
- kvm_t *kt;
- unsigned long read_back;
- unsigned long our_tick = 10000;
- unsigned long default_tickadj = 625;
-
- assert(on_off == 1 || on_off == 0);
-
- kt = kvm_open(NULL, NULL, NULL, O_RDWR, NULL);
- if (!kt) {
- LOG(LOGS_ERR, LOGF_SysSunOS, "Cannot open kvm");
- return;
- }
-
- if (kvm_nlist(kt, nl) < 0) {
- LOG(LOGS_ERR, LOGF_SysSunOS, "Cannot read kernel symbols");
- kvm_close(kt);
- return;
- }
-
- if (kvm_write(kt, nl[0].n_value, (char *)(&on_off), sizeof(unsigned long)) < 0) {
- LOG(LOGS_ERR, LOGF_SysSunOS, "Cannot write to _dosynctodr");
- kvm_close(kt);
- return;
- }
-
- if (kvm_write(kt, nl[1].n_value, (char *)(&our_tick), sizeof(unsigned long)) < 0) {
- LOG(LOGS_ERR, LOGF_SysSunOS, "Cannot write to _tick");
- kvm_close(kt);
- return;
- }
-
- if (kvm_write(kt, nl[2].n_value,
- (char *)(on_off ? &default_tickadj : &our_tickadj),
- sizeof(unsigned long)) < 0) {
- LOG(LOGS_ERR, LOGF_SysSunOS, "Cannot write to _tickadj");
- kvm_close(kt);
- return;
- }
-
- kvm_close(kt);
-}
-
-/* ================================================== */
-
-void
-SYS_SunOS_Initialise(void)
-{
-
- /* Need to do KVM stuff to turn off dosynctodr. */
-
- clock_initialise();
-
- lcl_RegisterSystemDrivers(read_frequency, set_frequency,
- accrue_offset, apply_step_offset,
- get_offset_correction,
- NULL /* set_leap */,
- NULL /* set_sync_status */);
-
- /* Turn off the kernel switch that keeps the system clock in step
- with the non-volatile clock */
- setup_kernel(0);
-
- drift_removal_id = SCH_AddTimeoutByDelay(DRIFT_REMOVAL_INTERVAL, drift_removal_timeout, NULL);
- drift_removal_running = 1;
-
-}
-
-/* ================================================== */
-
-void
-SYS_SunOS_Finalise(void)
-{
-
- if (drift_removal_running) {
- SCH_RemoveTimeout(drift_removal_id);
- }
-
- /* Turn dosynctodr back on?? */
-
- clock_finalise();
-
- /* When exiting, we want to return the machine to its 'autonomous'
- tracking mode */
- setup_kernel(1);
-}
-
-/* ================================================== */
-
-
-#endif /* SUNOS */
diff --git a/sys_sunos.h b/sys_sunos.h
deleted file mode 100644
index 84222b6..0000000
--- a/sys_sunos.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- chronyd/chronyc - Programs for keeping computer clocks accurate.
-
- **********************************************************************
- * Copyright (C) Richard P. Curnow 1997-2002
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of version 2 of the GNU General Public License as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- **********************************************************************
-
- =======================================================================
-
- Header file for Solaris driver
- */
-
-#ifndef GOT_SYS_SUNOS_H
-#define GOT_SYS_SUNOS_H
-
-void SYS_SunOS_Initialise(void);
-
-void SYS_SunOS_Finalise(void);
-
-#endif
diff --git a/sys_timex.c b/sys_timex.c
new file mode 100644
index 0000000..60018f1
--- /dev/null
+++ b/sys_timex.c
@@ -0,0 +1,243 @@
+/*
+ chronyd/chronyc - Programs for keeping computer clocks accurate.
+
+ **********************************************************************
+ * Copyright (C) Richard P. Curnow 1997-2003
+ * Copyright (C) Miroslav Lichvar 2009-2012, 2014-2015
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ **********************************************************************
+
+ =======================================================================
+
+ Driver for systems that implement the adjtimex()/ntp_adjtime() system call
+ */
+
+#include "config.h"
+
+#include "sysincl.h"
+
+#include "conf.h"
+#include "sys_generic.h"
+#include "sys_timex.h"
+#include "logging.h"
+
+#ifdef LINUX
+#define NTP_ADJTIME adjtimex
+#define NTP_ADJTIME_NAME "adjtimex"
+#else
+#define NTP_ADJTIME ntp_adjtime
+#define NTP_ADJTIME_NAME "ntp_adjtime"
+#endif
+
+/* Maximum frequency offset accepted by the kernel (in ppm) */
+#define MAX_FREQ 500.0
+
+/* Frequency scale to convert from ppm to the timex freq */
+#define FREQ_SCALE (double)(1 << 16)
+
+/* Threshold for the timex maxerror when the kernel sets the UNSYNC flag */
+#define MAX_SYNC_ERROR 16.0
+
+/* Minimum assumed rate at which the kernel updates the clock frequency */
+#define MIN_TICK_RATE 100
+
+/* Saved timex status */
+static int status;
+
+/* ================================================== */
+
+static double
+read_frequency(void)
+{
+ struct timex txc;
+
+ txc.modes = 0;
+
+ SYS_Timex_Adjust(&txc, 0);
+
+ return txc.freq / -FREQ_SCALE;
+}
+
+/* ================================================== */
+
+static double
+set_frequency(double freq_ppm)
+{
+ struct timex txc;
+
+ txc.modes = MOD_FREQUENCY;
+ txc.freq = freq_ppm * -FREQ_SCALE;
+
+ SYS_Timex_Adjust(&txc, 0);
+
+ return txc.freq / -FREQ_SCALE;
+}
+
+/* ================================================== */
+
+static void
+set_leap(int leap)
+{
+ struct timex txc;
+ int applied;
+
+ applied = 0;
+ if (!leap) {
+ txc.modes = 0;
+ if (SYS_Timex_Adjust(&txc, 1) == TIME_WAIT)
+ applied = 1;
+ }
+
+ status &= ~(STA_INS | STA_DEL);
+
+ if (leap > 0)
+ status |= STA_INS;
+ else if (leap < 0)
+ status |= STA_DEL;
+
+ txc.modes = MOD_STATUS;
+ txc.status = status;
+
+ SYS_Timex_Adjust(&txc, 0);
+
+ LOG(LOGS_INFO, LOGF_SysTimex, "System clock status %s leap second",
+ leap ? (leap > 0 ? "set to insert" : "set to delete") :
+ (applied ? "reset after" : "set to not insert/delete"));
+}
+
+/* ================================================== */
+
+static void
+set_sync_status(int synchronised, double est_error, double max_error)
+{
+ struct timex txc;
+
+ if (synchronised) {
+ if (est_error > MAX_SYNC_ERROR)
+ est_error = MAX_SYNC_ERROR;
+ if (max_error >= MAX_SYNC_ERROR) {
+ max_error = MAX_SYNC_ERROR;
+ synchronised = 0;
+ }
+ } else {
+ est_error = max_error = MAX_SYNC_ERROR;
+ }
+
+#ifdef LINUX
+ /* On Linux clear the UNSYNC flag only if rtcsync is enabled */
+ if (!CNF_GetRtcSync())
+ synchronised = 0;
+#endif
+
+ if (synchronised)
+ status &= ~STA_UNSYNC;
+ else
+ status |= STA_UNSYNC;
+
+ txc.modes = MOD_STATUS | MOD_ESTERROR | MOD_MAXERROR;
+ txc.status = status;
+ txc.esterror = est_error * 1.0e6;
+ txc.maxerror = max_error * 1.0e6;
+
+ SYS_Timex_Adjust(&txc, 1);
+}
+
+/* ================================================== */
+
+static void
+initialise_timex(void)
+{
+ struct timex txc;
+
+ status = STA_UNSYNC;
+
+ /* Reset PLL offset */
+ txc.modes = MOD_OFFSET | MOD_STATUS;
+ txc.status = STA_PLL | status;
+ txc.offset = 0;
+ SYS_Timex_Adjust(&txc, 0);
+
+ /* Turn PLL off */
+ txc.modes = MOD_STATUS;
+ txc.status = status;
+ SYS_Timex_Adjust(&txc, 0);
+}
+
+/* ================================================== */
+
+void
+SYS_Timex_Initialise(void)
+{
+ SYS_Timex_InitialiseWithFunctions(MAX_FREQ, 1.0 / MIN_TICK_RATE, NULL, NULL, NULL,
+ 0.0, 0.0, NULL, NULL);
+}
+
+/* ================================================== */
+
+void
+SYS_Timex_InitialiseWithFunctions(double max_set_freq_ppm, double max_set_freq_delay,
+ lcl_ReadFrequencyDriver sys_read_freq,
+ lcl_SetFrequencyDriver sys_set_freq,
+ lcl_ApplyStepOffsetDriver sys_apply_step_offset,
+ double min_fastslew_offset, double max_fastslew_rate,
+ lcl_AccrueOffsetDriver sys_accrue_offset,
+ lcl_OffsetCorrectionDriver sys_get_offset_correction)
+{
+ initialise_timex();
+
+ SYS_Generic_CompleteFreqDriver(max_set_freq_ppm, max_set_freq_delay,
+ sys_read_freq ? sys_read_freq : read_frequency,
+ sys_set_freq ? sys_set_freq : set_frequency,
+ sys_apply_step_offset,
+ min_fastslew_offset, max_fastslew_rate,
+ sys_accrue_offset, sys_get_offset_correction,
+ set_leap, set_sync_status);
+}
+
+/* ================================================== */
+
+void
+SYS_Timex_Finalise(void)
+{
+ SYS_Generic_Finalise();
+}
+
+/* ================================================== */
+
+int
+SYS_Timex_Adjust(struct timex *txc, int ignore_error)
+{
+ int state;
+
+#ifdef SOLARIS
+ /* The kernel seems to check the constant even when it's not being set */
+ if (!(txc->modes & MOD_TIMECONST))
+ txc->constant = 10;
+#endif
+
+ state = NTP_ADJTIME(txc);
+
+ if (state < 0) {
+ if (!ignore_error)
+ LOG_FATAL(LOGF_SysTimex, NTP_ADJTIME_NAME"(0x%x) failed : %s",
+ txc->modes, strerror(errno));
+ else
+ DEBUG_LOG(LOGF_SysTimex, NTP_ADJTIME_NAME"(0x%x) failed : %s",
+ txc->modes, strerror(errno));
+ }
+
+ return state;
+}
diff --git a/sys_timex.h b/sys_timex.h
new file mode 100644
index 0000000..c15b16c
--- /dev/null
+++ b/sys_timex.h
@@ -0,0 +1,50 @@
+/*
+ chronyd/chronyc - Programs for keeping computer clocks accurate.
+
+ **********************************************************************
+ * Copyright (C) Miroslav Lichvar 2015
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ **********************************************************************
+
+ =======================================================================
+
+ Header file for a driver based on the adjtimex()/ntp_adjtime() function
+ */
+
+#ifndef GOT_SYS_TIMEX_H
+#define GOT_SYS_TIMEX_H
+
+#include <sys/timex.h>
+
+#include "localp.h"
+
+extern void SYS_Timex_Initialise(void);
+
+/* Initialise with some driver functions replaced with special versions */
+extern void SYS_Timex_InitialiseWithFunctions(double max_set_freq_ppm, double max_set_freq_delay,
+ lcl_ReadFrequencyDriver sys_read_freq,
+ lcl_SetFrequencyDriver sys_set_freq,
+ lcl_ApplyStepOffsetDriver sys_apply_step_offset,
+ double min_fastslew_offset, double max_fastslew_rate,
+ lcl_AccrueOffsetDriver sys_accrue_offset,
+ lcl_OffsetCorrectionDriver sys_get_offset_correction);
+
+extern void SYS_Timex_Finalise(void);
+
+/* Wrapper for adjtimex()/ntp_adjtime() */
+extern int SYS_Timex_Adjust(struct timex *txc, int ignore_error);
+
+#endif /* GOT_SYS_GENERIC_H */
diff --git a/sysincl.h b/sysincl.h
index 5c1fb37..30e9b48 100644
--- a/sysincl.h
+++ b/sysincl.h
@@ -29,22 +29,16 @@
#ifndef GOT_SYSINCL_H
#define GOT_SYSINCL_H
-#if defined (SOLARIS) || defined(SUNOS) || defined(LINUX) || defined(__NetBSD__) || defined (MACOSX)
-
-#if !defined(__NetBSD__) && !defined(__FreeBSD__) && !defined(MACOSX)
-#include <alloca.h>
-#endif
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
-#if !defined(__FreeBSD__) && !defined(MACOSX)
-#include <malloc.h>
-#endif
+#include <glob.h>
#include <math.h>
#include <netdb.h>
#include <netinet/in.h>
+#include <pwd.h>
#include <resolv.h>
#include <signal.h>
#include <stdarg.h>
@@ -61,6 +55,7 @@
#include <sys/shm.h>
#include <syslog.h>
#include <time.h>
+#include <unistd.h>
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
@@ -70,62 +65,9 @@
/* Tough */
#endif
-/* One or other of these to make getsid() visible */
-#define __EXTENSIONS__ 1
-#define __USE_XOPEN_EXTENDED 1
-
-#include <unistd.h>
-
-#endif
-
#ifdef FEAT_IPV6
/* For inet_ntop() */
#include <arpa/inet.h>
#endif
-#if defined (SOLARIS) || defined(SUNOS)
-/* Only needed on these platforms, and doesn't exist on some Linux
- versions. */
-#include <nlist.h>
-#endif
-
-#if defined (WINNT)
-
-/* Designed to work with the GCC from the GNAT-3.10 for Win32
- distribution */
-
-#define Win32_Winsock
-#include <assert.h>
-#include <ctype.h>
-
-#if 1
-/* Cheat and inline the necessary bits from <errno.h>. We don't
- include it directly because it redefines some EXXX constants that
- conflict with <windows32/sockets.h> (included by <windows.h>) */
-
-int* _errno();
-int* __doserrno();
-
-#define errno (*_errno())
-#define _doserrno (*__doserrno())
-
-#define ENOENT 2
-#else
-
-#include <errno.h>
-#endif
-
-
-#include <float.h>
-#include <math.h>
-#include <signal.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <time.h>
-#include <windows.h>
-#endif
-
#endif /* GOT_SYSINCL_H */
diff --git a/test/compilation/001-features b/test/compilation/001-features
index b1f1fb6..9da21d2 100755
--- a/test/compilation/001-features
+++ b/test/compilation/001-features
@@ -5,8 +5,14 @@
cd ../..
for opts in \
+ "--enable-debug" \
+ "--enable-scfilter" \
"--disable-asyncdns" \
+ "--disable-ipv6" \
+ "--disable-privdrop" \
+ "--disable-readline" \
"--disable-rtc" \
+ "--disable-sechash" \
"--disable-cmdmon" \
"--disable-ntp" \
"--disable-refclock" \
@@ -15,5 +21,5 @@ for opts in \
"--disable-cmdmon --disable-ntp --disable-refclock"
do
./configure $opts
- make || exit 1
+ make "$@" || exit 1
done
diff --git a/test/kernel/Makefile b/test/kernel/Makefile
new file mode 100644
index 0000000..6ec8341
--- /dev/null
+++ b/test/kernel/Makefile
@@ -0,0 +1,7 @@
+CFLAGS=-O2 -Wall
+PROGS=adjtime ntpadjtime
+
+all: $(PROGS)
+
+clean:
+ rm -f $(PROGS)
diff --git a/test/kernel/adjtime.c b/test/kernel/adjtime.c
new file mode 100644
index 0000000..0ca8ff2
--- /dev/null
+++ b/test/kernel/adjtime.c
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) Miroslav Lichvar 2015
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+/* Test the system adjtime() function. Check the range of supported offset,
+ support for readonly operation, and slew rate with different update
+ intervals and offsets. */
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+static int
+diff_tv(struct timeval *tv1, struct timeval *tv2)
+{
+ return 1000000 * (tv1->tv_sec - tv2->tv_sec) + (tv1->tv_usec - tv2->tv_usec);
+}
+
+static struct timeval
+usec_to_tv(int usec)
+{
+ struct timeval tv;
+
+ tv.tv_sec = usec / 1000000;
+ tv.tv_usec = usec % 1000000;
+
+ return tv;
+}
+
+static int
+try_adjtime(struct timeval *new, struct timeval *old)
+{
+ int r;
+
+ r = adjtime(new, old);
+ if (r)
+ printf("adjtime() failed : %s ", strerror(errno));
+ return r;
+}
+
+static void
+reset_adjtime(void)
+{
+ struct timeval tv;
+
+ tv = usec_to_tv(0);
+ try_adjtime(&tv, NULL);
+}
+
+static void
+test_range(void)
+{
+ struct timeval tv;
+ int i;
+
+ printf("range:\n");
+
+ for (i = 0; i < sizeof (time_t) * 8; i++) {
+ tv.tv_usec = 0;
+ tv.tv_sec = (1ULL << i) - 1;
+ printf("%20lld s : ", (long long)tv.tv_sec);
+ printf("%s\n", !try_adjtime(&tv, NULL) ? "ok" : "");
+ tv.tv_sec = ~tv.tv_sec;
+ printf("%20lld s : ", (long long)tv.tv_sec);
+ printf("%s\n", !try_adjtime(&tv, NULL) ? "ok" : "");
+ }
+}
+
+static void
+test_readonly(void)
+{
+ struct timeval tv1, tv2;
+ int i, r;
+
+ printf("readonly:\n");
+
+ for (i = 0; i <= 20; i++) {
+ tv1 = usec_to_tv(1 << i);
+
+ printf("%9d us : ", 1 << i);
+ try_adjtime(&tv1, NULL);
+ r = !try_adjtime(NULL, &tv2) && !diff_tv(&tv1, &tv2);
+ printf("%s\n", r ? "ok" : "fail");
+ }
+}
+
+static void
+test_readwrite(void)
+{
+ struct timeval tv1, tv2, tv3;
+ int i, r;
+
+ printf("readwrite:\n");
+
+ for (i = 0; i <= 20; i++) {
+ tv1 = usec_to_tv(1 << i);
+ tv3 = usec_to_tv(0);
+
+ printf("%9d us : ", 1 << i);
+ try_adjtime(&tv1, NULL);
+ r = !try_adjtime(&tv3, &tv2) && !diff_tv(&tv1, &tv2);
+ printf("%s\n", r ? "ok" : "fail");
+ }
+}
+
+static void
+xusleep(int usec)
+{
+ struct timeval tv;
+
+ tv = usec_to_tv(usec);
+ select(0, NULL, NULL, NULL, &tv);
+}
+
+static void
+test_slew(void)
+{
+ struct timeval tv1, tv2, tv3;
+ int i, j, k, diff, min, has_min;
+
+ printf("slew:\n");
+
+ for (i = 9; i <= 20; i++) {
+ printf("%9d us : ", 1 << i);
+ for (j = 4; j <= 20; j += 4) {
+ for (min = has_min = 0, k = 4; k < 16; k += 2) {
+
+ tv1 = usec_to_tv(1 << j);
+ tv3 = usec_to_tv(0);
+
+ xusleep(1 << i);
+ reset_adjtime();
+
+ xusleep(1 << i);
+ if (try_adjtime(&tv1, NULL))
+ continue;
+
+ xusleep(1 << i);
+ if (try_adjtime(&tv3, &tv2))
+ continue;
+
+ diff = diff_tv(&tv1, &tv2);
+ if (!has_min || min > diff) {
+ min = diff;
+ has_min = 1;
+ }
+ }
+
+ if (!has_min)
+ continue;
+
+ printf(" %5d (%d)", min, 1 << j);
+ fflush(stdout);
+ }
+ printf("\n");
+ }
+}
+
+int
+main()
+{
+ test_range();
+ test_readonly();
+ test_readwrite();
+ test_slew();
+
+ reset_adjtime();
+
+ return 0;
+}
diff --git a/test/kernel/ntpadjtime.c b/test/kernel/ntpadjtime.c
new file mode 100644
index 0000000..d6be154
--- /dev/null
+++ b/test/kernel/ntpadjtime.c
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) Miroslav Lichvar 2015
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of version 2 of the GNU General Public License as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+/* Check the frequency range of the system ntp_adjtime() implementation */
+
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/time.h>
+#include <sys/timex.h>
+
+static int
+try_ntpadjtime(struct timex *t)
+{
+ int r;
+ r = ntp_adjtime(t);
+ if (r < 0)
+ printf("ntp_adjtime() failed : %s ", strerror(errno));
+ return r;
+}
+
+static void
+reset_ntpadjtime(void)
+{
+ struct timex t;
+
+ t.modes = MOD_OFFSET | MOD_FREQUENCY;
+ t.offset = 0;
+ t.freq = 0;
+ try_ntpadjtime(&t);
+}
+
+static void
+test_freqrange(void)
+{
+ struct timex t;
+ int i;
+
+ printf("freq range:\n");
+
+ for (i = 0; i <= 1000; i += 50) {
+ t.modes = MOD_FREQUENCY;
+ t.freq = i << 16;
+ printf("%4d ppm => ", i);
+ if (try_ntpadjtime(&t) < 0)
+ continue;
+
+ printf("%4ld ppm : ", t.freq / (1 << 16));
+ printf("%s\n", t.freq == i << 16 ? "ok" : "fail");
+ }
+}
+
+int
+main()
+{
+ test_freqrange();
+
+ reset_ntpadjtime();
+
+ return 0;
+}
diff --git a/test/simulation/114-presend b/test/simulation/114-presend
index e9fe66e..8872525 100755
--- a/test/simulation/114-presend
+++ b/test/simulation/114-presend
@@ -6,6 +6,7 @@ test_start "presend option"
min_sync_time=140
max_sync_time=260
client_server_options="presend 6 maxdelay 16"
+client_conf="maxdistance 10"
run_test || test_fail
check_chronyd_exit || test_fail
diff --git a/util.c b/util.c
index 0add5df..247037c 100644
--- a/util.c
+++ b/util.c
@@ -29,12 +29,14 @@
#include "sysincl.h"
+#include "logging.h"
+#include "memory.h"
#include "util.h"
#include "hash.h"
/* ================================================== */
-INLINE_STATIC void
+void
UTI_TimevalToDouble(struct timeval *a, double *b)
{
*b = (double)(a->tv_sec) + 1.0e-6 * (double)(a->tv_usec);
@@ -43,20 +45,22 @@ UTI_TimevalToDouble(struct timeval *a, double *b)
/* ================================================== */
-INLINE_STATIC void
+void
UTI_DoubleToTimeval(double a, struct timeval *b)
{
- long int_part, frac_part;
+ long int_part;
+ double frac_part;
int_part = (long)(a);
- frac_part = (long)(0.5 + 1.0e6 * (a - (double)(int_part)));
+ frac_part = 1.0e6 * (a - (double)(int_part));
+ frac_part = frac_part > 0 ? frac_part + 0.5 : frac_part - 0.5;
b->tv_sec = int_part;
- b->tv_usec = frac_part;
+ b->tv_usec = (long)frac_part;
UTI_NormaliseTimeval(b);
}
/* ================================================== */
-INLINE_STATIC int
+int
UTI_CompareTimevals(struct timeval *a, struct timeval *b)
{
if (a->tv_sec < b->tv_sec) {
@@ -76,7 +80,7 @@ UTI_CompareTimevals(struct timeval *a, struct timeval *b)
/* ================================================== */
-INLINE_STATIC void
+void
UTI_NormaliseTimeval(struct timeval *x)
{
/* Reduce tv_usec to within +-1000000 of zero. JGH */
@@ -95,7 +99,7 @@ UTI_NormaliseTimeval(struct timeval *x)
/* ================================================== */
-INLINE_STATIC void
+void
UTI_DiffTimevals(struct timeval *result,
struct timeval *a,
struct timeval *b)
@@ -112,7 +116,7 @@ UTI_DiffTimevals(struct timeval *result,
/* ================================================== */
/* Calculate result = a - b and return as a double */
-INLINE_STATIC void
+void
UTI_DiffTimevalsToDouble(double *result,
struct timeval *a,
struct timeval *b)
@@ -123,7 +127,7 @@ UTI_DiffTimevalsToDouble(double *result,
/* ================================================== */
-INLINE_STATIC void
+void
UTI_AddDoubleToTimeval(struct timeval *start,
double increment,
struct timeval *end)
@@ -147,7 +151,7 @@ UTI_AddDoubleToTimeval(struct timeval *start,
/* ================================================== */
/* Calculate the average and difference (as a double) of two timevals */
-INLINE_STATIC void
+void
UTI_AverageDiffTimevals (struct timeval *earlier,
struct timeval *later,
struct timeval *average,
@@ -485,6 +489,55 @@ UTI_IPAndPortToSockaddr(IPAddr *ip, unsigned short port, struct sockaddr *sa)
/* ================================================== */
+char *UTI_SockaddrToString(struct sockaddr *sa)
+{
+ unsigned short port;
+ IPAddr ip;
+ char *result;
+
+ result = NEXT_BUFFER;
+
+ switch (sa->sa_family) {
+ case AF_INET:
+#ifdef AF_INET6
+ case AF_INET6:
+#endif
+ UTI_SockaddrToIPAndPort(sa, &ip, &port);
+ snprintf(result, BUFFER_LENGTH, "%s:%hu", UTI_IPToString(&ip), port);
+ break;
+ case AF_UNIX:
+ snprintf(result, BUFFER_LENGTH, "%s", ((struct sockaddr_un *)sa)->sun_path);
+ break;
+ default:
+ snprintf(result, BUFFER_LENGTH, "[UNKNOWN]");
+ }
+
+ return result;
+}
+
+/* ================================================== */
+
+const char *
+UTI_SockaddrFamilyToString(int family)
+{
+ switch (family) {
+ case AF_INET:
+ return "IPv4";
+#ifdef AF_INET6
+ case AF_INET6:
+ return "IPv6";
+#endif
+ case AF_UNIX:
+ return "Unix";
+ case AF_UNSPEC:
+ return "UNSPEC";
+ default:
+ return "?";
+ }
+}
+
+/* ================================================== */
+
char *
UTI_TimeToLogForm(time_t t)
{
@@ -649,11 +702,11 @@ UTI_Log2ToDouble(int l)
if (l >= 0) {
if (l > 31)
l = 31;
- return 1 << l;
+ return (uint32_t)1 << l;
} else {
if (l < -31)
l = -31;
- return 1.0 / (1 << -l);
+ return 1.0 / ((uint32_t)1 << -l);
}
}
@@ -837,3 +890,183 @@ UTI_DecodePasswordFromText(char *key)
return len;
}
}
+
+/* ================================================== */
+
+int
+UTI_SetQuitSignalsHandler(void (*handler)(int))
+{
+ struct sigaction sa;
+
+ sa.sa_handler = handler;
+ sa.sa_flags = SA_RESTART;
+ if (sigemptyset(&sa.sa_mask) < 0)
+ return 0;
+
+#ifdef SIGINT
+ if (sigaction(SIGINT, &sa, NULL) < 0)
+ return 0;
+#endif
+#ifdef SIGTERM
+ if (sigaction(SIGTERM, &sa, NULL) < 0)
+ return 0;
+#endif
+#ifdef SIGQUIT
+ if (sigaction(SIGQUIT, &sa, NULL) < 0)
+ return 0;
+#endif
+#ifdef SIGHUP
+ if (sigaction(SIGHUP, &sa, NULL) < 0)
+ return 0;
+#endif
+
+ return 1;
+}
+
+/* ================================================== */
+
+char *
+UTI_PathToDir(const char *path)
+{
+ char *dir, *slash;
+
+ slash = strrchr(path, '/');
+
+ if (!slash)
+ return Strdup(".");
+
+ if (slash == path)
+ return Strdup("/");
+
+ dir = Malloc(slash - path + 1);
+ snprintf(dir, slash - path + 1, "%s", path);
+
+ return dir;
+}
+
+/* ================================================== */
+
+static int
+create_dir(char *p, mode_t mode, uid_t uid, gid_t gid)
+{
+ int status;
+ struct stat buf;
+
+ /* See if directory exists */
+ status = stat(p, &buf);
+
+ if (status < 0) {
+ if (errno != ENOENT) {
+ LOG(LOGS_ERR, LOGF_Util, "Could not access %s : %s", p, strerror(errno));
+ return 0;
+ }
+ } else {
+ if (S_ISDIR(buf.st_mode))
+ return 1;
+ LOG(LOGS_ERR, LOGF_Util, "%s is not directory", p);
+ return 0;
+ }
+
+ /* Create the directory */
+ if (mkdir(p, mode) < 0) {
+ LOG(LOGS_ERR, LOGF_Util, "Could not create directory %s : %s", p, strerror(errno));
+ return 0;
+ }
+
+ /* Set its owner */
+ if (chown(p, uid, gid) < 0) {
+ LOG(LOGS_ERR, LOGF_Util, "Could not change ownership of %s : %s", p, strerror(errno));
+ /* Don't leave it there with incorrect ownership */
+ rmdir(p);
+ return 0;
+ }
+
+ return 1;
+}
+
+/* ================================================== */
+/* Return 0 if the directory couldn't be created, 1 if it could (or
+ already existed) */
+int
+UTI_CreateDirAndParents(const char *path, mode_t mode, uid_t uid, gid_t gid)
+{
+ char *p;
+ int i, j, k, last;
+
+ /* Don't try to create current directory */
+ if (!strcmp(path, "."))
+ return 1;
+
+ p = (char *)Malloc(1 + strlen(path));
+
+ i = k = 0;
+ while (1) {
+ p[i++] = path[k++];
+
+ if (path[k] == '/' || !path[k]) {
+ /* Check whether its end of string, a trailing / or group of / */
+ last = 1;
+ j = k;
+ while (path[j]) {
+ if (path[j] != '/') {
+ /* Pick up a / into p[] thru the assignment at the top of the loop */
+ k = j - 1;
+ last = 0;
+ break;
+ }
+ j++;
+ }
+
+ p[i] = 0;
+
+ if (!create_dir(p, last ? mode : 0755, last ? uid : 0, last ? gid : 0)) {
+ Free(p);
+ return 0;
+ }
+
+ if (last)
+ break;
+ }
+
+ if (!path[k])
+ break;
+ }
+
+ Free(p);
+ return 1;
+}
+
+/* ================================================== */
+
+int
+UTI_CheckDirPermissions(const char *path, mode_t perm, uid_t uid, gid_t gid)
+{
+ struct stat buf;
+
+ if (stat(path, &buf)) {
+ LOG(LOGS_ERR, LOGF_Util, "Could not access %s : %s", path, strerror(errno));
+ return 0;
+ }
+
+ if (!S_ISDIR(buf.st_mode)) {
+ LOG(LOGS_ERR, LOGF_Util, "%s is not directory", path);
+ return 0;
+ }
+
+ if ((buf.st_mode & 0777) & ~perm) {
+ LOG(LOGS_ERR, LOGF_Util, "Wrong permissions on %s", path);
+ return 0;
+ }
+
+ if (buf.st_uid != uid) {
+ LOG(LOGS_ERR, LOGF_Util, "Wrong owner of %s (%s != %d)", path, "UID", uid);
+ return 0;
+ }
+
+ if (buf.st_gid != gid) {
+ LOG(LOGS_ERR, LOGF_Util, "Wrong owner of %s (%s != %d)", path, "GID", gid);
+ return 0;
+ }
+
+ return 1;
+}
diff --git a/util.h b/util.h
index 6e9fdd1..d3fa9e7 100644
--- a/util.h
+++ b/util.h
@@ -88,6 +88,8 @@ extern int UTI_CompareIPs(IPAddr *a, IPAddr *b, IPAddr *mask);
extern void UTI_SockaddrToIPAndPort(struct sockaddr *sa, IPAddr *ip, unsigned short *port);
extern int UTI_IPAndPortToSockaddr(IPAddr *ip, unsigned short port, struct sockaddr *sa);
+extern char *UTI_SockaddrToString(struct sockaddr *sa);
+extern const char *UTI_SockaddrFamilyToString(int family);
extern char *UTI_TimeToLogForm(time_t t);
@@ -127,11 +129,19 @@ extern int UTI_CheckNTPAuth(int hash_id, const unsigned char *key, int key_len,
/* Decode password encoded in ASCII or HEX */
extern int UTI_DecodePasswordFromText(char *key);
-#if defined (INLINE_UTILITIES)
-#define INLINE_STATIC inline static
-#include "util.c"
-#else
-#define INLINE_STATIC
-#endif /* defined (INLINE_UTILITIES) */
+extern int UTI_SetQuitSignalsHandler(void (*handler)(int));
+
+/* Get directory (as an allocated string) for a path */
+extern char *UTI_PathToDir(const char *path);
+
+/* Create a directory with a specified mode (umasked) and set its uid/gid.
+ Create also any parent directories that don't exist with mode 755 and
+ default uid/gid. Returns 1 if created or already exists (even with
+ different mode/uid/gid), 0 otherwise. */
+extern int UTI_CreateDirAndParents(const char *path, mode_t mode, uid_t uid, gid_t gid);
+
+/* Check if a directory is secure. It must not have other than the specified
+ permissions and its uid/gid must match the specified values. */
+extern int UTI_CheckDirPermissions(const char *path, mode_t perm, uid_t uid, gid_t gid);
#endif /* GOT_UTIL_H */
diff --git a/version.txt b/version.txt
index 3e3c2f1..8bbe6cf 100644
--- a/version.txt
+++ b/version.txt
@@ -1 +1 @@
-2.1.1
+2.2
diff --git a/wrap_adjtimex.c b/wrap_adjtimex.c
deleted file mode 100644
index 50c4ab7..0000000
--- a/wrap_adjtimex.c
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- chronyd/chronyc - Programs for keeping computer clocks accurate.
-
- **********************************************************************
- * Copyright (C) Richard P. Curnow 1997-2002
- * Copyright (C) Miroslav Lichvar 2011-2012, 2014
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of version 2 of the GNU General Public License as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- **********************************************************************
-
- =======================================================================
-
- This is a wrapper around the Linux adjtimex system call.
-
- */
-
-#include "config.h"
-
-#include "wrap_adjtimex.h"
-
-#include <sys/timex.h>
-
-/* Definitions used if missing in the system headers */
-#ifndef ADJ_TAI
-#define ADJ_TAI 0x0080 /* set TAI offset */
-#endif
-#ifndef ADJ_SETOFFSET
-#define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
-#endif
-#ifndef ADJ_NANO
-#define ADJ_NANO 0x2000 /* select nanosecond resolution */
-#endif
-#ifndef ADJ_OFFSET_SS_READ
-#define ADJ_OFFSET_SS_READ 0xa001 /* read-only adjtime */
-#endif
-
-/* Frequency offset scale (shift) */
-#define SHIFT_USEC 16
-
-static int status = 0;
-
-int
-TMX_ResetOffset(void)
-{
- struct timex txc;
-
- /* Reset adjtime() offset */
- txc.modes = ADJ_OFFSET_SINGLESHOT;
- txc.offset = 0;
- if (adjtimex(&txc) < 0)
- return -1;
-
- /* Reset PLL offset */
- txc.modes = ADJ_OFFSET | ADJ_STATUS;
- txc.status = STA_PLL;
- txc.offset = 0;
- if (adjtimex(&txc) < 0)
- return -1;
-
- /* Set status back */
- txc.modes = ADJ_STATUS;
- txc.status = status;
- if (adjtimex(&txc) < 0)
- return -1;
-
- return 0;
-}
-
-int
-TMX_SetFrequency(double *freq, long tick)
-{
- struct timex txc;
-
- txc.modes = ADJ_TICK | ADJ_FREQUENCY;
-
- txc.freq = (long)(*freq * (double)(1 << SHIFT_USEC));
- *freq = txc.freq / (double)(1 << SHIFT_USEC);
- txc.tick = tick;
-
- return adjtimex(&txc);
-}
-
-int
-TMX_GetFrequency(double *freq, long *tick)
-{
- struct timex txc;
- int result;
- txc.modes = 0; /* pure read */
- result = adjtimex(&txc);
- *freq = txc.freq / (double)(1 << SHIFT_USEC);
- *tick = txc.tick;
- return result;
-}
-
-int
-TMX_SetLeap(int leap)
-{
- struct timex txc;
-
- status &= ~(STA_INS | STA_DEL);
-
- if (leap > 0) {
- status |= STA_INS;
- } else if (leap < 0) {
- status |= STA_DEL;
- }
-
- txc.modes = ADJ_STATUS;
- txc.status = status;
-
- return adjtimex(&txc);
-}
-
-int
-TMX_GetLeap(int *leap)
-{
- struct timex txc;
-
- txc.modes = 0;
- if (adjtimex(&txc) < 0)
- return -1;
-
- status &= ~(STA_INS | STA_DEL);
- status |= txc.status & (STA_INS | STA_DEL);
-
- if (status & STA_INS)
- *leap = 1;
- else if (status & STA_DEL)
- *leap = -1;
- else
- *leap = 0;
-
- return 0;
-}
-
-int TMX_SetSync(int sync, double est_error, double max_error)
-{
- struct timex txc;
-
- if (sync) {
- status &= ~STA_UNSYNC;
- } else {
- status |= STA_UNSYNC;
- }
-
- txc.modes = ADJ_STATUS | ADJ_ESTERROR | ADJ_MAXERROR;
- txc.status = status;
- txc.esterror = est_error * 1.0e6;
- txc.maxerror = max_error * 1.0e6;
-
- return adjtimex(&txc);
-}
-
-int
-TMX_TestStepOffset(void)
-{
- struct timex txc;
-
- /* Zero maxerror and check it's reset to a maximum after ADJ_SETOFFSET.
- This seems to be the only way how to verify that the kernel really
- supports the ADJ_SETOFFSET mode as it doesn't return an error on unknown
- mode. */
-
- txc.modes = ADJ_MAXERROR;
- txc.maxerror = 0;
- if (adjtimex(&txc) < 0 || txc.maxerror != 0)
- return -1;
-
- txc.modes = ADJ_SETOFFSET | ADJ_NANO;
- txc.time.tv_sec = 0;
- txc.time.tv_usec = 0;
- if (adjtimex(&txc) < 0 || txc.maxerror < 100000)
- return -1;
-
- return 0;
-}
-
-int
-TMX_ApplyStepOffset(double offset)
-{
- struct timex txc;
-
- txc.modes = ADJ_SETOFFSET | ADJ_NANO;
- txc.time.tv_sec = offset;
- txc.time.tv_usec = 1.0e9 * (offset - txc.time.tv_sec);
- if (txc.time.tv_usec < 0) {
- txc.time.tv_sec--;
- txc.time.tv_usec += 1000000000;
- }
-
- return adjtimex(&txc);
-}
diff --git a/wrap_adjtimex.h b/wrap_adjtimex.h
deleted file mode 100644
index 23587a3..0000000
--- a/wrap_adjtimex.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- chronyd/chronyc - Programs for keeping computer clocks accurate.
-
- **********************************************************************
- * Copyright (C) Richard P. Curnow 1997-2002
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of version 2 of the GNU General Public License as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- **********************************************************************
-
- =======================================================================
-
- The header file for the adjtimex wrapper
- */
-
-#ifndef GOT_WRAP_ADJTIMEX_H
-#define GOT_WRAP_ADJTIMEX_H
-
-int TMX_ResetOffset(void);
-int TMX_SetFrequency(double *freq, long tick);
-int TMX_GetFrequency(double *freq, long *tick);
-int TMX_SetLeap(int leap);
-int TMX_GetLeap(int *leap);
-int TMX_SetSync(int sync, double est_error, double max_error);
-int TMX_TestStepOffset(void);
-int TMX_ApplyStepOffset(double offset);
-
-#endif /* GOT_WRAP_ADJTIMEX_H */
-