1 /* $NetBSD: main.c,v 1.5 2006/06/11 19:34:21 kardel Exp $ */
3 /* Copyright (C) 1996, 1997, 2000 N.M. Maclaren
4 Copyright (C) 1996, 1997, 2000 The University of Cambridge
6 This is a complete SNTP implementation, which was easier to write than to port
7 xntp to a new version of Unix with any hope of maintaining it thereafter. It
8 supports the full SNTP (RFC 2030) client- and server-side challenge-response
9 and broadcast protocols. It should achieve nearly optimal accuracy with very
10 few transactions, provided only that a client has access to a trusted server
11 and that communications are not INVARIABLY slow. As this is the environment in
12 which 90-99% of all NTP systems are run ....
14 The specification of this program is:
16 sntp [ --help | -h | -? ] [ -v | -V | -W ]
17 [ -q [ -f savefile ] |
18 [ { -r | -a } [ -P prompt ] [ -l lockfile ] ]
19 [ -c count ] [ -e minerr ][ -E maxerr ]
20 [ -d delay | -x [ separation ] [ -f savefile ] ]
21 [ -4 | -6 ] [ address(es) ] ]
23 --help, -h and -? all print the syntax of the command.
25 -v indicates that diagnostic messages should be written to standard error,
26 and -V requests more output for investigating apparently inconsistent
27 timestamps. -W requests very verbose debugging output, and will interfere with
28 the timing when writing to the terminal (because of line buffered output from
29 C); it is useful only when debugging the source. Note that the times produced
30 by -V and -W are the corrections needed, and not the error in the local clock.
32 -q indicates that it will query a savefile that is being maintained by
33 it being run in daemon mode.
35 The default is that it should behave as a client, and the following options
38 -r indicates that the system clock should be reset by 'settimeofday'.
39 Naturally, this will work only if the user has enough privilege.
41 -a indicates that the system clock should be reset by 'adjtime'.
42 Naturally, this will work only if the user has enough privilege.
44 -x indicates that the program should run as a daemon (i.e. forever), and
45 allow for clock drift.
47 -4 or -6 force dns resolving to ipv4 or ipv6 addresses.
49 The default is to write the current date and time to the standard output in
50 a format like '1996 Oct 15 20:17:25.123 + 4.567 +/- 0.089 secs', indicating the
51 estimated true (local) time and the error in the local clock. In daemon mode,
52 it will add drift information in a format like ' + 1.3 +/- 0.1 ppm', and
53 display this at roughly 'separation' intervals.
55 'minerr' is the maximum ignorable variation between the clocks. Acceptable
56 values are from 0.001 to 1, and the default is 0.1 if 'address' is specified
59 'maxerr' is the maximum value of various delays that are deemed acceptable.
60 Acceptable values are from 1 to 60, and the default is 5. It should sometimes
61 be increased if there are problems with the network, NTP server or system
64 'prompt' is the maximum clock change that will be made automatically.
65 Acceptable values are from 1 to 3600, and the default is 30. If the program is
66 being run interactively, larger values will cause a prompt. The value may also
67 be 'no', and the change will be made without prompting.
69 'count' is the maximum number of NTP packets to require. Acceptable values
70 are from 1 to 25 if 'address' is specified and '-x' is not, and from 5 to 25
71 otherwise; the default is 5. If the maximum isn't enough, you need a better
72 consistency algorithm than this program uses. Don't increase it.
74 'delay' is a rough limit on the total running time in seconds. Acceptable
75 values are from 1 to 3600, and the default is 15 if 'address' is specified and
78 'separation' is the time to wait between calls to the server in minutes if
79 'address' is specified, and the minimum time between broadcast packets if not.
80 Acceptable values are from 1 to 1440 (a day), and the default is 300.
82 'lockfile' may be used in an update mode to ensure that there is only
83 one copy of sntp running at once. The default is installation-dependent,
84 but will usually be /etc/sntp.pid.
86 'savefile' may be used in daemon mode to store a record of previous
87 packets, which may speed up recalculating the drift after sntp has to be
88 restarted (e.g. because of network or server outages). The default is
89 installation-dependent, but will usually be /etc/sntp.state. Note that
90 there is no locking of this file, and using it twice may cause chaos.
92 'address' is the DNS name or IP number of a host to poll; if no name is
93 given, the program waits for broadcasts. Note that a single component numeric
94 address is not allowed.
96 For sanity, it is also required that 'minerr' < 'maxerr' < 'delay' (if
97 listening for broadcasts, 'delay/count' and, in daemon mode, 'separation') and,
98 for sordid Unixish reasons, that 2*'count' < 'delay'. The last could be fixed,
99 but isn't worth it. Note that none of the above values are closely linked to
100 the limits described in the NTP protocol (RFC 1305). Do not increase the
101 compiled-in bounds excessively, or the code will fail.
103 The algorithm used to decide whether to accept a correction is whether it would
104 seem to improve matters. Unlike the 'xntp' suite, little attempt is made to
105 handle really knotted scenarios, and diagnostics are written to standard error.
106 In non-daemon client mode, it is intended to be run as a command or in a 'cron'
107 job. Unlike 'ntpdate', its default mode is simply to display the clock error.
109 It assumes that floating-point arithmetic is tolerably efficient, which is true
110 for even the cheapest personal computer nowadays. If, however, you want to
111 port this to a toaster, you may have problems!
113 In its terminating modes, its return code is EXIT_SUCCESS if the operation was
114 completed successfully and EXIT_FAILURE otherwise.
116 In daemon mode, it runs for ever and stops with a return code EXIT_FAILURE
117 only after a severe error. In daemon mode, it will fail if the server is
118 inaccessible for a long time or seriously sick, and will need manual
122 WARNING: this program has reached its 'hack count' and needs restructuring,
123 badly. Perhaps the worst code is in run_daemon(). You are advised not to
124 fiddle unless you really have to. */
140 /* NTP definitions. Note that these assume 8-bit bytes - sigh. There is
141 little point in parameterising everything, as it is neither feasible nor
142 useful. It would be very useful if more fields could be defined as
143 unspecified. The NTP packet-handling routines contain a lot of extra
146 #define JAN_1970 2208988800.0 /* 1970 - 1900 in seconds */
147 #define NTP_SCALE 4294967296.0 /* 2^32, of course! */
149 #define NTP_PACKET_MIN 48 /* Without authentication */
150 #define NTP_PACKET_MAX 68 /* With authentication (ignored) */
151 #define NTP_DISP_FIELD 8 /* Offset of dispersion field */
152 #define NTP_REFERENCE 16 /* Offset of reference timestamp */
153 #define NTP_ORIGINATE 24 /* Offset of originate timestamp */
154 #define NTP_RECEIVE 32 /* Offset of receive timestamp */
155 #define NTP_TRANSMIT 40 /* Offset of transmit timestamp */
157 #define NTP_LI_FUDGE 0 /* The current 'status' */
158 #define NTP_VERSION 3 /* The current version */
159 #define NTP_VERSION_MAX 4 /* The maximum valid version */
160 #define NTP_STRATUM 15 /* The current stratum as a server */
161 #define NTP_STRATUM_MAX 15 /* The maximum valid stratum */
162 #define NTP_POLLING 8 /* The current 'polling interval' */
163 #define NTP_PRECISION 0 /* The current 'precision' - 1 sec. */
165 #define NTP_ACTIVE 1 /* NTP symmetric active request */
166 #define NTP_PASSIVE 2 /* NTP symmetric passive response */
167 #define NTP_CLIENT 3 /* NTP client request */
168 #define NTP_SERVER 4 /* NTP server response */
169 #define NTP_BROADCAST 5 /* NTP server broadcast */
171 #define NTP_INSANITY 3600.0 /* Errors beyond this are hopeless */
172 #define RESET_MIN 15 /* Minimum period between resets */
173 #define ABSCISSA 3.0 /* Scale factor for standard errors */
177 /* Local definitions and global variables (mostly options). These are all of
178 the quantities that control the main actions of the program. The first three
179 are the only ones that are exported to other modules. */
181 const char *argv0
= NULL
; /* For diagnostics only - not NULL */
182 int verbose
= 0, /* Default = 0, -v = 1, -V = 2, -W = 3 */
183 operation
= 0; /* Defined in header.h - see action */
184 const char *lockname
= NULL
; /* The name of the lock file */
185 int unprivport
= 0; /* Use an unpriv port for query? */
187 #define COUNT_MAX 25 /* Do NOT increase this! */
188 #define WEEBLE_FACTOR 1.2 /* See run_server() and run_daemon() */
189 #define ETHERNET_MAX 5 /* See run_daemon() and run_client() */
191 #define action_display 1 /* Just display the result */
192 #define action_reset 2 /* Reset using 'settimeofday' */
193 #define action_adjust 3 /* Reset using 'adjtime' */
194 #define action_broadcast 4 /* Behave as a server, broadcasting */
195 #define action_server 5 /* Behave as a server for clients */
196 #define action_query 6 /* Query a daemon savefile */
198 #define save_read_only 1 /* Read the saved state only */
199 #define save_read_check 2 /* Read and check it */
200 #define save_write 3 /* Write the saved state */
201 #define save_clear 4 /* Clear the saved state */
203 static const char version
[] = VERSION
; /* For reverse engineering :-) */
204 static int action
= 0, /* Defined above - see operation */
205 count
= 0, /* -c value in seconds */
206 delay
= 0, /* -d or -x value in seconds */
207 attempts
= 0, /* Packets transmitted up to 2*count */
208 waiting
= 0, /* -d/-c except for in daemon mode */
209 locked
= 0; /* set_lock(1) has been called */
210 static double outgoing
[2*COUNT_MAX
], /* Transmission timestamps */
211 minerr
= 0.0, /* -e value in seconds */
212 maxerr
= 0.0, /* -E value in seconds */
213 prompt
= 0.0, /* -p value in seconds */
214 dispersion
= 0.0; /* The source dispersion in seconds */
215 static FILE *savefile
= NULL
; /* Holds the data to restart from */
219 /* The unpacked NTP data structure, with all the fields even remotely relevant
222 typedef struct NTP_DATA
{
223 unsigned char status
, version
, mode
, stratum
, polling
;
224 signed char precision
;
225 double dispersion
, reference
, originate
, receive
, transmit
, current
;
230 /* The following structure is used to keep a record of packets in daemon mode;
231 it contains only the information that is actually used for the drift and error
235 double dispersion
, weight
, when
, offset
, error
;
239 void display_data(ntp_data
*);
240 void display_packet(unsigned char *, int);
241 void pack_ntp(unsigned char *, int, ntp_data
*);
242 void unpack_ntp(ntp_data
*, unsigned char *, int);
243 void make_packet(ntp_data
*, int);
244 int read_packet(int, ntp_data
*, double *, double *);
245 void format_time(char *, int, double, double, double, double, int);
246 double reset_clock(double, double, int);
247 void run_server(void);
248 double estimate_stats(int *, int *, data_record
*, double, double *, double *,
249 double *, double *, double *, double *, int *, int);
250 double correct_drift(double *, double *, double);
251 void handle_saving(int, int *, int *, int *, data_record
*, double *,
253 void query_savefile(void);
254 void run_daemon(char **, int, int);
255 void run_client(char **, int);
257 void fatal (int syserr
, const char *message
, const char *insert
) {
259 /* Issue a diagnostic and stop. Be a little paranoid about recursion. */
262 static int called
= 0;
264 if (message
!= NULL
) {
265 fprintf(stderr
,"%s: ",argv0
);
266 fprintf(stderr
,message
,insert
);
267 fprintf(stderr
,"\n");
270 if (syserr
) perror(argv0
);
273 if (savefile
!= NULL
&& fclose(savefile
))
274 fatal(1,"unable to close the daemon save file",NULL
);
275 if (locked
) set_lock(0);
282 void syntax (int halt
) {
284 /* The standard, unfriendly Unix error message. Some errors are diagnosed more
285 helpfully. This is called before any files or sockets are opened. */
287 fprintf(stderr
,"Syntax: %s [ --help | -h | -? ] [ -v | -V | -W ] \n",argv0
);
288 fprintf(stderr
," [ -q [ -f savefile ] |\n");
289 fprintf(stderr
," [ { -r | -a } [ -P prompt ] [ -l lockfile ] ]\n");
290 fprintf(stderr
," [ -c count ] [ -e minerr ] [ -E maxerr ]\n");
291 fprintf(stderr
," [ -d delay | -x [ separation ] ");
292 fprintf(stderr
,"[ -f savefile ] ]\n");
293 fprintf(stderr
," [ -4 | -6 ] [-u] [ address(es) ] ]\n");
294 if (halt
) exit(EXIT_FAILURE
);
299 void display_data (ntp_data
*data
) {
301 /* This formats the essential NTP data, as a debugging aid. */
303 fprintf(stderr
,"sta=%d ver=%d mod=%d str=%d pol=%d dis=%.6f ref=%.6f\n",
304 data
->status
,data
->version
,data
->mode
,data
->stratum
,data
->polling
,
305 data
->dispersion
,data
->reference
);
306 fprintf(stderr
,"ori=%.6f rec=%.6f\n",data
->originate
,data
->receive
);
307 fprintf(stderr
,"tra=%.6f cur=%.6f\n",data
->transmit
,data
->current
);
312 void display_packet (unsigned char *packet
, int length
) {
314 /* This formats a possible packet very roughly, as a debugging aid. */
318 if (length
< NTP_PACKET_MIN
|| length
> NTP_PACKET_MAX
) return;
319 for (i
= 0; i
< length
; ++i
) {
320 if (i
!= 0 && i
%32 == 0)
321 fprintf(stderr
,"\n");
322 else if (i
!= 0 && i
%4 == 0)
324 fprintf(stderr
,"%.2x",packet
[i
]);
326 fprintf(stderr
,"\n");
331 void pack_ntp (unsigned char *packet
, int length
, ntp_data
*data
) {
333 /* Pack the essential data into an NTP packet, bypassing struct layout and
334 endian problems. Note that it ignores fields irrelevant to SNTP. */
339 memset(packet
,0,(size_t)length
);
340 packet
[0] = (data
->status
<<6)|(data
->version
<<3)|data
->mode
;
341 packet
[1] = data
->stratum
;
342 packet
[2] = data
->polling
;
343 packet
[3] = data
->precision
;
344 d
= data
->originate
/NTP_SCALE
;
345 for (i
= 0; i
< 8; ++i
) {
346 if ((k
= (int)(d
*= 256.0)) >= 256) k
= 255;
347 packet
[NTP_ORIGINATE
+i
] = k
;
350 d
= data
->receive
/NTP_SCALE
;
351 for (i
= 0; i
< 8; ++i
) {
352 if ((k
= (int)(d
*= 256.0)) >= 256) k
= 255;
353 packet
[NTP_RECEIVE
+i
] = k
;
356 d
= data
->transmit
/NTP_SCALE
;
357 for (i
= 0; i
< 8; ++i
) {
358 if ((k
= (int)(d
*= 256.0)) >= 256) k
= 255;
359 packet
[NTP_TRANSMIT
+i
] = k
;
366 void unpack_ntp (ntp_data
*data
, unsigned char *packet
, int length
) {
368 /* Unpack the essential data from an NTP packet, bypassing struct layout and
369 endian problems. Note that it ignores fields irrelevant to SNTP. */
374 data
->current
= current_time(JAN_1970
); /* Best to come first */
375 data
->status
= (packet
[0] >> 6);
376 data
->version
= (packet
[0] >> 3)&0x07;
377 data
->mode
= packet
[0]&0x07;
378 data
->stratum
= packet
[1];
379 data
->polling
= packet
[2];
380 data
->precision
= packet
[3];
382 for (i
= 0; i
< 4; ++i
) d
= 256.0*d
+packet
[NTP_DISP_FIELD
+i
];
383 data
->dispersion
= d
/65536.0;
385 for (i
= 0; i
< 8; ++i
) d
= 256.0*d
+packet
[NTP_REFERENCE
+i
];
386 data
->reference
= d
/NTP_SCALE
;
388 for (i
= 0; i
< 8; ++i
) d
= 256.0*d
+packet
[NTP_ORIGINATE
+i
];
389 data
->originate
= d
/NTP_SCALE
;
391 for (i
= 0; i
< 8; ++i
) d
= 256.0*d
+packet
[NTP_RECEIVE
+i
];
392 data
->receive
= d
/NTP_SCALE
;
394 for (i
= 0; i
< 8; ++i
) d
= 256.0*d
+packet
[NTP_TRANSMIT
+i
];
395 data
->transmit
= d
/NTP_SCALE
;
400 void make_packet (ntp_data
*data
, int mode
) {
402 /* Create an outgoing NTP packet, either from scratch or starting from a
403 request from a client. Note that it implements the NTP specification, even
404 when this is clearly misguided, except possibly for the setting of LI. It
405 would be easy enough to add a sanity flag, but I am not in the business of
406 designing an alternative protocol (however much better it might be). */
408 data
->status
= NTP_LI_FUDGE
<<6;
409 data
->stratum
= NTP_STRATUM
;
410 data
->reference
= data
->dispersion
= 0.0;
411 if (mode
== NTP_SERVER
) {
412 data
->mode
= (data
->mode
== NTP_CLIENT
? NTP_SERVER
: NTP_PASSIVE
);
413 data
->originate
= data
->transmit
;
414 data
->receive
= data
->current
;
416 data
->version
= NTP_VERSION
;
418 data
->polling
= NTP_POLLING
;
419 data
->precision
= NTP_PRECISION
;
420 data
->receive
= data
->originate
= 0.0;
422 data
->current
= data
->transmit
= current_time(JAN_1970
);
427 int read_packet (int which
, ntp_data
*data
, double *off
, double *err
) {
429 /* Check the packet and work out the offset and optionally the error. Note
430 that this contains more checking than xntp does. This returns 0 for success, 1
431 for failure and 2 for an ignored broadcast packet (a kludge for servers). Note
432 that it must not change its arguments if it fails. */
434 unsigned char receive
[NTP_PACKET_MAX
+1];
435 double delay1
, delay2
, x
, y
;
436 int response
= 0, failed
, length
, i
, k
;
438 /* Read the packet and deal with diagnostics. */
440 if ((length
= read_socket(which
,receive
,NTP_PACKET_MAX
+1,waiting
)) <= 0)
442 if (length
< NTP_PACKET_MIN
|| length
> NTP_PACKET_MAX
) {
444 fprintf(stderr
,"%s: bad length %d for NTP packet on socket %d\n",
449 fprintf(stderr
,"Incoming packet on socket %d:\n",which
);
450 display_packet(receive
,length
);
452 unpack_ntp(data
,receive
,length
);
453 if (verbose
> 2) display_data(data
);
455 /* Start by checking that the packet looks reasonable. Be a little paranoid,
456 but allow for version 1 semantics and sick clients. */
458 if (operation
== op_listen
)
459 failed
= (data
->mode
!= NTP_BROADCAST
);
461 failed
= (data
->mode
!= NTP_SERVER
&& data
->mode
!= NTP_PASSIVE
);
464 if (failed
|| data
->status
== 3 || data
->version
< 1 ||
465 data
->version
> NTP_VERSION_MAX
||
466 data
->stratum
> NTP_STRATUM_MAX
) {
469 "%s: Unusable NTP packet rejected on socket %d (f=%d, status %d, version %d, stratum %d)\n",
471 failed
, data
->status
, data
->version
, data
->stratum
);
475 /* Note that the conventions are very poorly defined in the NTP protocol, so we
476 have to guess. Any full NTP server perpetrating completely unsynchronised
477 packets is an abomination, anyway, so reject it. */
479 delay1
= data
->transmit
-data
->receive
;
480 delay2
= data
->current
-data
->originate
;
483 /* && data->stratum != NTP_STRATUM_MAX */
484 && data
->reference
== 0.0
486 || data
->transmit
== 0.0
489 (data
->originate
== 0.0 || data
->receive
== 0.0 ||
490 (data
->reference
!= 0.0 && data
->receive
< data
->reference
) ||
491 delay1
< 0.0 || delay1
> NTP_INSANITY
|| delay2
< 0.0 ||
492 data
->dispersion
> NTP_INSANITY
))
497 "%s: incomprehensible NTP packet rejected on socket %d\n",
501 if (data
->stratum
== NTP_STRATUM_MAX
) {
503 "%s: unsynch NTP response on socket %d\n",
508 /* If it is a response, check that it corresponds to one of our requests and
509 has got here in a reasonable length of time. */
513 for (i
= 0; i
< attempts
; ++i
)
514 if (data
->originate
== outgoing
[i
]) {
518 if (k
!= 1 || delay2
> NTP_INSANITY
) {
521 "%s: bad response from NTP server rejected on socket %d\n",
527 /* Now return the time information. If it is a server response, it contains
528 enough information that we can be almost certain that we have not been fooled
529 too badly. Heaven help us with broadcasts - make a wild kludge here, and see
530 elsewhere for other kludges. */
532 if (dispersion
< data
->dispersion
) dispersion
= data
->dispersion
;
533 if (operation
== op_listen
) {
534 *off
= data
->transmit
-data
->current
;
537 x
= data
->receive
-data
->originate
;
538 y
= (data
->transmit
== 0.0 ? 0.0 : data
->transmit
-data
->current
);
541 x
= data
->current
-data
->originate
;
542 if (0.5*x
> *err
) *err
= 0.5*x
;
549 void format_time (char *text
, int length
, double offset
, double error
,
550 double drift
, double drifterr
, int precision
) {
552 /* Format the current time into a string, with the extra information as
553 requested. Note that the rest of the program uses the correction needed, which
554 is what is printed for diagnostics, but this formats the error in the local
555 system for display to users. So the results from this are the negation of
556 those printed by the verbose options. */
561 static const char *months
[] = {
562 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
563 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
566 /* Work out and format the current local time. Note that some semi-ANSI
567 systems do not set the return value from (s)printf. */
569 now
= convert_time(current_time(offset
),&milli
);
571 if ((gmt
= localtime(&now
)) == NULL
)
572 fatal(1,"unable to work out local time",NULL
);
574 if (length
<= len
) fatal(0,"internal error calling format_time",NULL
);
578 sprintf(text
,"%.4d %s %.2d %.2d:%.2d:%.2d.%.*d",
579 gmt
->tm_year
+1900,months
[gmt
->tm_mon
],gmt
->tm_mday
,
580 gmt
->tm_hour
,gmt
->tm_min
,gmt
->tm_sec
,precision
,milli
);
581 if (strlen(text
) != len
)
582 fatal(1,"unable to format current local time",NULL
);
584 /* Append the information about the offset, if requested. */
588 fatal(0,"internal error calling format_time",NULL
);
590 sprintf(&text
[len
]," %c %.*f +/- %.*f secs",(offset
> 0.0 ? '-' : '+'),
591 precision
,(offset
> 0.0 ? offset
: -offset
),
592 precision
,dispersion
+error
);
593 if (strlen(&text
[len
]) < 22)
594 fatal(1,"unable to format clock correction",NULL
);
597 /* Append the information about the drift, if requested. */
599 if (drifterr
>= 0.0) {
602 fatal(0,"internal error calling format_time",NULL
);
604 sprintf(&text
[len
]," %c %.1f +/- %.1f ppm",
605 (drift
> 0.0 ? '-' : '+'),1.0e6
*fabs(drift
),
607 if (strlen(&text
[len
]) < 17)
608 fatal(1,"unable to format clock correction",NULL
);
611 /* It would be better to check for field overflow, but it is a lot of code to
612 trap extremely implausible scenarios. This will usually stop chaos from
615 if (strlen(text
) >= length
)
616 fatal(0,"internal error calling format_time",NULL
);
621 double reset_clock (double offset
, double error
, int daemon
) {
623 /* Reset the clock, if appropriate, and return the correction actually used.
624 This contains most of the checking for whether changes are worthwhile, except
627 double absoff
= (offset
< 0 ? -offset
: offset
);
630 /* If the correction is large, ask for confirmation before proceeding. */
632 if (absoff
> prompt
) {
633 if (! daemon
&& ftty(stdin
) && ftty(stdout
)) {
634 printf("The time correction is %.3f +/- %.3f+%.3f seconds\n",
635 offset
,dispersion
,error
);
636 printf("Do you want to correct the time anyway? ");
638 if (toupper(getchar()) != 'Y') {
639 printf("OK - quitting\n");
643 sprintf(text
,"%.3f +/- %.3f+%.3f",offset
,dispersion
,error
);
644 fatal(0,"time correction too large: %s seconds",text
);
648 /* See if the correction is reasonably reliable and worth making. */
650 if (absoff
< (daemon
? 0.5 : 1.0)*minerr
) {
651 if (daemon
? verbose
> 1 : verbose
)
652 fprintf(stderr
,"%s: correction %.3f +/- %.3f+%.3f secs - ignored\n",
653 argv0
,offset
,dispersion
,error
);
655 } else if (absoff
< 2.0*error
) {
656 if (daemon
? verbose
> 1 : verbose
)
658 "%s: correction %.3f +/- %.3f+%.3f secs - suppressed\n",
659 argv0
,offset
,dispersion
,error
);
663 /* Make the correction. Provide some protection against the previous
664 correction not having completed, but it will rarely help much. */
666 adjust_time(offset
,(action
== action_reset
? 1 : 0),
667 (daemon
? 2.0*minerr
: 0.0));
668 if (daemon
? verbose
> 1 : verbose
) {
669 format_time(text
,50,0.0,-1.0,0.0,-1.0,-10);
671 "%s: time changed by %.3f secs to %s +/- %.3f+%.3f\n",
672 argv0
,offset
,text
,dispersion
,error
);
678 double estimate_stats (int *a_total
, int *a_index
, data_record
*record
,
679 double correction
, double *a_disp
, double *a_when
, double *a_offset
,
680 double *a_error
, double *a_drift
, double *a_drifterr
, int *a_wait
,
683 /* This updates the running statistics and returns the best estimate of what to
684 do now. It returns the timestamp relevant to the correction. If broadcasts
685 are rare and the drift is large, it will fail - you should then use a better
686 synchronisation method. It will also fail if something goes severely wrong
687 (e.g. if the local clock is reset by another process or the transmission errors
690 There is a kludge for synchronisation loss during down time. If it detects
691 this, it will update only the history data and return zero; this is then
692 handled specially in run_daemon(). While it could correct the offset, this
693 might not always be the right thing to do. */
695 double weight
, disp
, when
, offset
, error
, drift
, drifterr
,
697 int total
= *a_total
, index
= *a_index
, wait
= *a_wait
, i
;
700 /* Correct the previous data and store a new entry in the circular buffer. */
702 for (i
= 0; i
< total
; ++i
) {
703 record
[i
].when
+= correction
;
704 record
[i
].offset
-= correction
;
707 record
[index
].dispersion
= *a_disp
;
708 record
[index
].when
= *a_when
;
709 record
[index
].offset
= *a_offset
;
711 fprintf(stderr
,"%s: corr=%.3f when=%.3f disp=%.3f off=%.3f",
712 argv0
,correction
,*a_when
,*a_disp
,*a_offset
); /* See below */
713 if (operation
== op_listen
) {
714 if (verbose
> 1) fprintf(stderr
,"\n");
715 record
[index
].error
= minerr
;
716 record
[index
].weight
= 1.0;
718 if (verbose
> 1) fprintf(stderr
," err=%.3f\n",*a_error
);
719 record
[index
].error
= x
= *a_error
;
720 record
[index
].weight
= 1.0/(x
> minerr
? x
*x
: minerr
*minerr
);
722 if (++index
>= count
) index
= 0;
724 if (++total
> count
) total
= count
;
727 fprintf(stderr
,"corr=%.6f tot=%d ind=%d\n",correction
,total
,index
);
730 /* If there is insufficient data yet, use the latest estimates and return
731 forthwith. Note that this will not work for broadcasts, but they will be
732 disabled in run_daemon(). */
734 if ((operation
== op_listen
&& total
< count
&& update
) || total
< 3) {
741 /* Work out the average time, offset, error etc. Note that the dispersion is
742 not subject to the central limit theorem. Unfortunately, the variation in the
743 source's dispersion is our only indication of how consistent its clock is. */
745 disp
= weight
= when
= offset
= y
= 0.0;
746 for (i
= 0; i
< total
; ++i
) {
747 weight
+= w
= record
[i
].weight
;
748 when
+= w
*record
[i
].when
;
749 offset
+= w
*record
[i
].offset
;
750 y
+= w
*record
[i
].dispersion
;
751 if (disp
< record
[i
].dispersion
)
752 disp
= record
[i
].dispersion
;
758 fprintf(stderr
,"disp=%.6f wgt=%.3f when=%.6f off=%.6f\n",
759 disp
,weight
,when
,offset
);
761 /* If there is enough data, estimate the drift and errors by regression. Note
762 that it is essential to calculate the mean square error, not the mean error. */
764 error
= drift
= x
= z
= 0.0;
765 for (i
= 0; i
< total
; ++i
) {
766 w
= record
[i
].weight
/weight
;
767 x
+= w
*(record
[i
].when
-when
)*(record
[i
].when
-when
);
768 drift
+= w
*(record
[i
].when
-when
)*(record
[i
].offset
-offset
);
769 z
+= w
*(record
[i
].offset
-offset
)*(record
[i
].offset
-offset
);
770 error
+= w
*record
[i
].error
*record
[i
].error
+
771 2.0*w
*(record
[i
].dispersion
-y
)*(record
[i
].dispersion
-y
);
774 fprintf(stderr
,"X2=%.3f XY=%.6f Y2=%.9f E2=%.9f ",x
,drift
,z
,error
);
776 /* When calculating the errors, add some paranoia mainly to check for coding
777 errors and complete lunacy, attempting to retry if at all possible. Because
778 glitches at this point are so common, log a reset even in non-verbose mode.
779 There will be more thorough checks later. Note that we cannot usefully check
780 the error for broadcasts. */
783 if (verbose
> 2) fprintf(stderr
,"S2=%.9f\n",z
);
786 fatal(0,"stored data too unreliable for time estimation",NULL
);
787 } else if (operation
== op_client
) {
788 e
= error
+disp
*disp
+minerr
*minerr
;
790 if (verbose
|| z
>= maxerr
*maxerr
)
792 "%s: excessively high error %.3f > %.3f > %.3f\n",
793 argv0
,sqrt(z
),sqrt(e
),sqrt(error
));
794 if (z
< maxerr
*maxerr
) {
795 sprintf(text
,"resetting on error %.3g > %.3g",
800 fatal(0,"incompatible (i.e. erroneous) timestamps",NULL
);
801 } else if (z
> error
&& verbose
)
803 "%s: anomalously high error %.3f > %.3f, but < %.3f\n",
804 argv0
,sqrt(z
),sqrt(error
),sqrt(e
));
806 if (z
> maxerr
*maxerr
)
807 fatal(0,"broadcasts too unreliable for time estimation",NULL
);
810 drifterr
= ABSCISSA
*sqrt(z
/(x
*total
));
811 error
= (operation
== op_listen
? minerr
: 0.0)+ABSCISSA
*sqrt(z
/total
);
813 fprintf(stderr
,"err=%.6f drift=%.6f+/-%.6f\n",error
,drift
,drifterr
);
814 if (error
+drifterr
*delay
> NTP_INSANITY
)
815 fatal(0,"unable to get a reasonable drift estimate",NULL
);
817 /* Estimate the optimal short-loop period, checking it carefully. Remember to
818 check that this whole process is likely to be accurate enough and that the
819 delay function may be inaccurate. */
822 x
= (drift
< 0.0 ? -drift
: drift
);
823 if (x
*delay
< 0.5*minerr
) {
824 if (verbose
> 2) fprintf(stderr
,"Drift too small to correct\n");
825 } else if (x
< 2.0*drifterr
) {
827 fprintf(stderr
,"Drift correction suppressed\n");
829 if ((z
= drifterr
*delay
) < 0.5*minerr
) z
= 0.5*minerr
;
830 wait
= (x
< z
/delay
? delay
: (int)(z
/x
+0.5));
831 wait
= (int)(delay
/(int)(delay
/(double)wait
+0.999)+0.999);
833 fatal(0,"internal error in drift calculation",NULL
);
834 if (update
&& (drift
*wait
> maxerr
|| wait
< RESET_MIN
)) {
835 sprintf(text
,"%.6f+/-%.6f",drift
,drifterr
);
836 fatal(0,"drift correction too large: %s",text
);
839 if (wait
< *a_wait
/2) wait
= *a_wait
/2;
840 if (wait
> *a_wait
*2) wait
= *a_wait
*2;
842 /* Now work out what the correction should be, as distinct from what it should
843 have been, remembering that older times are less certain. */
845 now
= current_time(JAN_1970
);
849 for (i
= 0; i
< total
; ++i
) {
850 x
= now
-record
[i
].when
;
851 z
= record
[i
].error
+x
*drifterr
;
853 when
= record
[i
].when
;
854 offset
= record
[i
].offset
+x
*drift
;
859 fprintf(stderr
,"now=%.6f when=%.6f off=%.6f err=%.6f wait=%d\n",
860 now
,when
,offset
,error
,wait
);
862 /* Finally, return the result. */
869 *a_drifterr
= drifterr
;
876 double correct_drift (double *a_when
, double *a_offset
, double drift
) {
878 /* Correct for the drift since the last time it was done, provided that a long
879 enough time has elapsed. And do remember to kludge up the time and
880 discrepancy, when appropriate. */
884 d
= current_time(JAN_1970
)-*a_when
;
886 x
= *a_offset
+d
*drift
;
888 fprintf(stderr
,"Correction %.6f @ %.6f off=%.6f ",x
,*a_when
,*a_offset
);
889 if (d
>= waiting
&& (x
< 0.0 ? -x
: x
) >= 0.5*minerr
) {
890 if (verbose
> 2) fprintf(stderr
,"performed\n");
891 adjust_time(x
,(action
== action_reset
? 1 : 0),0.5*minerr
);
895 if (verbose
> 2) fprintf(stderr
,"ignored\n");
903 void handle_saving (int operation
, int *total
, int *index
, int *cycle
,
904 data_record
*record
, double *previous
, double *when
, double *correction
) {
906 /* This handles the saving and restoring of the state to a file. While it is
907 subject to spoofing, this is not a major security problem. But, out of general
908 paranoia, check everything in sight when restoring. Note that this function
909 has no external effect if something goes wrong. */
912 data_record record
[COUNT_MAX
];
913 double previous
, when
, correction
;
914 int operation
, delay
, count
, total
, index
, cycle
, waiting
;
919 if (savefile
== NULL
) return;
921 /* Read the restart file and print its data in diagnostic mode. Note that some
922 care is necessary to avoid introducing a security exposure - but we trust the
923 C library not to trash the stack on bad numbers! */
925 if (operation
== save_read_only
|| operation
== save_read_check
) {
926 if (fread(&buffer
,sizeof(buffer
),1,savefile
) != 1 || ferror(savefile
)) {
927 if (ferror(savefile
))
928 fatal(1,"unable to read record from daemon save file",NULL
);
930 fprintf(stderr
,"%s: bad daemon restart information\n",argv0
);
934 fprintf(stderr
,"Reading prev=%.6f when=%.6f corr=%.6f\n",
935 buffer
.previous
,buffer
.when
,buffer
.correction
);
936 fprintf(stderr
,"op=%d dly=%d cnt=%d tot=%d ind=%d cyc=%d wait=%d\n",
937 buffer
.operation
,buffer
.delay
,buffer
.count
,buffer
.total
,
938 buffer
.index
,buffer
.cycle
,buffer
.waiting
);
939 if (buffer
.total
< COUNT_MAX
)
940 for (i
= 0; i
< buffer
.total
; ++i
)
942 "disp=%.6f wgt=%.3f when=%.6f off=%.6f err=%.6f\n",
943 buffer
.record
[i
].dispersion
,buffer
.record
[i
].weight
,
944 buffer
.record
[i
].when
,buffer
.record
[i
].offset
,
945 buffer
.record
[i
].error
);
949 /* Start checking the data for sanity. */
951 if (buffer
.operation
== 0 && buffer
.delay
== 0 && buffer
.count
== 0) {
953 fatal(0,"the daemon save file has been cleared",NULL
);
955 fprintf(stderr
,"%s: restarting from a cleared file\n",argv0
);
958 if (operation
== save_read_check
) {
959 if (buffer
.operation
!= operation
|| buffer
.delay
!= delay
||
960 buffer
.count
!= count
) {
962 fprintf(stderr
,"%s: different parameters for restart\n",
966 if (buffer
.total
< 1 || buffer
.total
> count
|| buffer
.index
< 0 ||
967 buffer
.index
>= count
|| buffer
.cycle
< 0 ||
968 buffer
.cycle
>= count
|| buffer
.correction
< -maxerr
||
969 buffer
.correction
> maxerr
|| buffer
.waiting
< RESET_MIN
||
970 buffer
.waiting
> delay
|| buffer
.previous
> buffer
.when
||
971 buffer
.previous
< buffer
.when
-count
*delay
||
972 buffer
.when
>= *when
) {
974 fprintf(stderr
,"%s: corrupted restart information\n",argv0
);
978 /* Checking the record is even more tedious. */
982 for (i
= 0; i
< buffer
.total
; ++i
) {
983 if (buffer
.record
[i
].dispersion
< 0.0 ||
984 buffer
.record
[i
].dispersion
> maxerr
||
985 buffer
.record
[i
].weight
<= 0.0 ||
986 buffer
.record
[i
].weight
> 1.001/(minerr
*minerr
) ||
987 buffer
.record
[i
].offset
< -count
*maxerr
||
988 buffer
.record
[i
].offset
> count
*maxerr
||
989 buffer
.record
[i
].error
< 0.0 ||
990 buffer
.record
[i
].error
> maxerr
) {
992 fprintf(stderr
,"%s: corrupted restart record\n",argv0
);
995 if (buffer
.record
[i
].when
< x
) x
= buffer
.record
[i
].when
;
996 if (buffer
.record
[i
].when
> y
) y
= buffer
.record
[i
].when
;
999 /* Check for consistency and, finally, whether this is too old. */
1001 if (y
> buffer
.when
|| y
-x
< (buffer
.total
-1)*delay
||
1002 y
-x
> (buffer
.total
-1)*count
*delay
) {
1004 fprintf(stderr
,"%s: corrupted restart times\n",argv0
);
1007 if (buffer
.when
< *when
-count
*delay
) {
1009 fprintf(stderr
,"%s: restart information too old\n",argv0
);
1014 /* If we get here, just copy the data back. */
1016 memcpy(record
,buffer
.record
,sizeof(buffer
.record
));
1017 *previous
= buffer
.previous
;
1018 *when
= buffer
.when
;
1019 *correction
= buffer
.correction
;
1020 *total
= buffer
.total
;
1021 *index
= buffer
.index
;
1022 *cycle
= buffer
.cycle
;
1023 waiting
= buffer
.waiting
;
1024 memset(&buffer
,0,sizeof(buffer
));
1026 /* Print out the data if requested. */
1029 fprintf(stderr
,"%s: prev=%.3f when=%.3f corr=%.3f\n",
1030 argv0
,*previous
,*when
,*correction
);
1031 for (i
= 0; i
< *total
; ++i
) {
1032 if ((j
= i
+*index
-*total
) < 0) j
+= *total
;
1033 fprintf(stderr
,"%s: when=%.3f disp=%.3f off=%.3f",
1034 argv0
,record
[j
].when
,record
[j
].dispersion
,record
[j
].offset
);
1035 if (operation
== op_client
)
1036 fprintf(stderr
," err=%.3f\n",record
[j
].error
);
1038 fprintf(stderr
,"\n");
1042 /* All errors on output are fatal. */
1044 } else if (operation
== save_write
) {
1045 memcpy(buffer
.record
,record
,sizeof(buffer
.record
));
1046 buffer
.previous
= *previous
;
1047 buffer
.when
= *when
;
1048 buffer
.correction
= *correction
;
1049 buffer
.operation
= operation
;
1050 buffer
.delay
= delay
;
1051 buffer
.count
= count
;
1052 buffer
.total
= *total
;
1053 buffer
.index
= *index
;
1054 buffer
.cycle
= *cycle
;
1055 buffer
.waiting
= waiting
;
1056 if (fseek(savefile
,0l,SEEK_SET
) != 0 ||
1057 fwrite(&buffer
,sizeof(buffer
),1,savefile
) != 1 ||
1058 fflush(savefile
) != 0 || ferror(savefile
))
1059 fatal(1,"unable to write record to daemon save file",NULL
);
1061 fprintf(stderr
,"Writing prev=%.6f when=%.6f corr=%.6f\n",
1062 *previous
,*when
,*correction
);
1063 fprintf(stderr
,"op=%d dly=%d cnt=%d tot=%d ind=%d cyc=%d wait=%d\n",
1064 operation
,delay
,count
,*total
,*index
,*cycle
,waiting
);
1065 if (*total
< COUNT_MAX
)
1066 for (i
= 0; i
< *total
; ++i
)
1068 "disp=%.6f wgt=%.3f when=%.6f off=%.6f err=%.6f\n",
1069 record
[i
].dispersion
,record
[i
].weight
,
1070 record
[i
].when
,record
[i
].offset
,record
[i
].error
);
1073 /* Clearing the save file is similar. */
1075 } else if (operation
== save_clear
) {
1076 if (fseek(savefile
,0l,SEEK_SET
) != 0 ||
1077 fwrite(&buffer
,sizeof(buffer
),1,savefile
) != 1 ||
1078 fflush(savefile
) != 0 || ferror(savefile
))
1079 fatal(1,"unable to clear daemon save file",NULL
);
1081 fatal(0,"internal error in handle_saving",NULL
);
1086 void query_savefile (void) {
1088 /* This queries a daemon save file. */
1090 double previous
, when
, correction
= 0.0, offset
= 0.0, error
= -1.0,
1091 drift
= 0.0, drifterr
= -1.0;
1092 data_record record
[COUNT_MAX
];
1093 int total
= 0, index
= 0, cycle
= 0;
1096 /* This is a few lines stripped out of run_daemon() and slightly hacked. */
1098 previous
= when
= current_time(JAN_1970
);
1100 format_time(text
,50,0.0,-1.0,0.0,-1.0,-10);
1101 fprintf(stderr
,"Started=%.6f %s\n",when
,text
);
1103 handle_saving(save_read_only
,&total
,&index
,&cycle
,record
,&previous
,&when
,
1105 estimate_stats(&total
,&index
,record
,correction
,&dispersion
,
1106 &when
,&offset
,&error
,&drift
,&drifterr
,&waiting
,0);
1107 format_time(text
,100,offset
,error
,drift
,drifterr
,-10);
1108 printf("%s\n",text
);
1109 if (fclose(savefile
)) fatal(1,"unable to close daemon save file",NULL
);
1110 if (verbose
> 2) fprintf(stderr
,"Stopped normally\n");
1116 void run_daemon (char *hostnames
[], int nhosts
, int initial
) {
1118 /* This does not adjust the time between calls to the server, but it does
1119 adjust the time between clock resets. This function will survive short periods
1120 of server inaccessibility or network glitches, but not long ones, and will then
1121 need restarting manually.
1123 It is far too complex for a single function, but could really only be
1124 simplified by making most of its variables global or by a similarly horrible
1125 trick. Oh, for nested scopes as in Algol 68! */
1127 double history
[COUNT_MAX
], started
, previous
, when
, correction
= 0.0,
1128 weeble
= 1.0, accepts
= 0.0, rejects
= 0.0, flushes
= 0.0,
1129 replicates
= 0.0, skips
= 0.0, offset
= 0.0, error
= -1.0,
1130 drift
= 0.0, drifterr
= -1.0, maxoff
= 0.0, x
;
1131 data_record record
[COUNT_MAX
];
1132 int total
= 0, index
= 0, item
= 0, rej_level
= 0, rep_level
= 0,
1133 cycle
= 0, retry
= 1, i
, j
, k
;
1134 unsigned char transmit
[NTP_PACKET_MIN
];
1138 /* After initialising, restore from a previous run if possible. Note that
1139 only a few of the variables are actually needed to control the operation and
1140 the rest are mainly for diagnostics. */
1142 started
= previous
= when
= current_time(JAN_1970
);
1144 format_time(text
,50,0.0,-1.0,0.0,-1.0,-10);
1145 fprintf(stderr
,"Started=%.6f %s\n",when
,text
);
1148 handle_saving(save_read_check
,&total
,&index
,&cycle
,record
,
1149 &previous
,&when
,&correction
);
1150 cycle
= (nhosts
> 0 ? cycle
%nhosts
: 0);
1151 if (total
> 0 && started
-previous
< delay
) {
1152 if (verbose
> 2) fprintf(stderr
,"Last packet too recent\n");
1156 fprintf(stderr
,"prev=%.6f when=%.6f retry=%d\n",
1157 previous
,when
,retry
);
1158 for (i
= 0; i
< nhosts
; ++i
) open_socket(i
,hostnames
[i
],delay
);
1159 if (action
!= action_display
) {
1166 for (i
= 0; i
< count
; ++i
) history
[i
] = 0.0;
1169 /* Print out a reasonable amount of diagnostics, rather like a server. Note
1170 that it may take a little time, but shouldn't affect the estimates much. Then
1171 check that we aren't in a failing loop. */
1173 if (verbose
> 2) fprintf(stderr
,"item=%d rej=%d\n",item
,rej_level
);
1174 x
= current_time(JAN_1970
)-started
;
1176 x
/3600.0+accepts
+rejects
+flushes
+replicates
+skips
>= weeble
) {
1177 weeble
*= WEEBLE_FACTOR
;
1178 x
-= 3600.0*(i
= (int)(x
/3600.0));
1179 x
-= 60.0*(j
= (int)(x
/60.0));
1181 fprintf(stderr
,"%s: after %d hours %d mins ",argv0
,i
,j
);
1183 fprintf(stderr
,"%s: after %d mins %.0f secs ",argv0
,j
,x
);
1185 fprintf(stderr
,"%s: after %.1f secs ",argv0
,x
);
1186 fprintf(stderr
,"acc. %.0f rej. %.0f flush %.0f",
1187 accepts
,rejects
,flushes
);
1188 if (operation
== op_listen
)
1189 fprintf(stderr
," rep. %.0f skip %.0f",replicates
,skips
);
1190 fprintf(stderr
," max.off. %.3f corr. %.3f\n",maxoff
,correction
);
1191 format_time(text
,100,offset
,error
,drift
,drifterr
,-10);
1192 fprintf(stderr
,"%s: %s\n",argv0
,text
);
1195 if (current_time(JAN_1970
)-previous
> count
*delay
) {
1197 fprintf(stderr
,"%s: no packets in too long a period\n",argv0
);
1201 /* Listen for the next broadcast packet. This allows up to ETHERNET_MAX
1202 replications per packet, for systems with multiple addresses for receiving
1203 broadcasts; the only reason for a limit is to protect against broken NTP
1204 servers always returning the same time. */
1206 if (operation
== op_listen
) {
1207 flushes
+= flush_socket(0);
1208 if (read_packet(0,&data
,&offset
,&error
)) {
1210 if (++rej_level
> count
)
1211 fatal(0,"too many bad or lost packets",NULL
);
1212 if (action
!= action_display
&& drifterr
>= 0.0) {
1213 correction
+= correct_drift(&when
,&offset
,drift
);
1214 handle_saving(save_write
,&total
,&index
,&cycle
,record
,
1215 &previous
,&when
,&correction
);
1219 if ((rej_level
-= (count
< 5 ? count
: 5)) < 0) rej_level
= 0;
1221 for (i
= 0; i
< count
; ++i
)
1222 if (x
== history
[i
]) {
1224 if (++rep_level
> ETHERNET_MAX
)
1225 fatal(0,"too many replicated packets",NULL
);
1230 if (++item
>= count
) item
= 0;
1232 /* Accept a packet only after a long enough period has elapsed. */
1234 when
= data
.current
;
1235 if (! retry
&& when
< previous
+delay
) {
1236 if (verbose
> 2) fprintf(stderr
,"Skipping too recent packet\n");
1242 fprintf(stderr
,"Offset=%.6f @ %.6f disp=%.6f\n",
1243 offset
,when
,dispersion
);
1245 /* Handle the client/server model. It keeps a record of transmitted times,
1246 mainly out of paranoia. The waiting time is kludged up to attempt to provide
1247 reasonable resilience against both lost packets and dead servers. But it
1248 won't handle much of either, and will stop after a while, needing manual
1249 restarting. Running it under cron is the best approach. */
1253 if (verbose
> 2) fprintf(stderr
,"Sleeping for %d\n",waiting
);
1254 do_nothing(waiting
);
1256 make_packet(&data
,NTP_CLIENT
);
1257 outgoing
[item
] = data
.transmit
;
1258 if (++item
>= 2*count
) item
= 0;
1259 if (attempts
< 2*count
) ++attempts
;
1261 fprintf(stderr
,"Outgoing packet on socket %d:\n",cycle
);
1262 display_data(&data
);
1264 pack_ntp(transmit
,NTP_PACKET_MIN
,&data
);
1265 if (verbose
> 2) display_packet(transmit
,NTP_PACKET_MIN
);
1266 flushes
+= flush_socket(cycle
);
1267 write_socket(cycle
,transmit
,NTP_PACKET_MIN
);
1269 /* Read the packet and check that it is an appropriate response. Because this
1270 is rather more numerically sensitive than simple resynchronisation, reject all
1271 very inaccurate packets. Be careful if you modify this, because the error
1272 handling is rather nasty to avoid replicating code. */
1274 k
= read_packet(cycle
,&data
,&offset
,&error
);
1275 if (++cycle
>= nhosts
) cycle
= 0;
1277 when
= (data
.originate
+data
.current
)/2.0;
1278 else if (action
!= action_display
&& drifterr
>= 0.0) {
1279 correction
+= correct_drift(&when
,&offset
,drift
);
1280 handle_saving(save_write
,&total
,&index
,&cycle
,record
,
1281 &previous
,&when
,&correction
);
1283 if (! k
&& ! retry
&& when
< previous
+delay
-2) {
1285 fprintf(stderr
,"%s: packets out of order on socket %d\n",
1289 if (! k
&& data
.current
-data
.originate
> maxerr
) {
1292 "%s: very slow response rejected on socket %d\n",
1297 /* Count the number of rejected packets and fail if there are too many. */
1301 if (++rej_level
> count
)
1302 fatal(0,"too many bad or lost packets",NULL
);
1309 if ((rej_level
-= (count
< 5 ? count
: 5)) < 0) rej_level
= 0;
1311 fprintf(stderr
,"Offset=%.6f+/-%.6f @ %.6f disp=%.6f\n",
1312 offset
,error
,when
,dispersion
);
1315 /* Calculate the statistics, and display the results or make the initial
1316 correction. Note that estimate_stats() will return zero if a timestamp
1317 indicates synchronisation loss (usually due to down time or a change of server,
1318 somewhere upstream), and that the recovery operation is unstructured, so great
1319 care should be taken when modifying it. Also, we want to clear the saved state
1320 is the statistics are bad. */
1322 handle_saving(save_clear
,&total
,&index
,&cycle
,record
,&previous
,&when
,
1325 dispersion
= data
.dispersion
;
1327 estimate_stats(&total
,&index
,record
,correction
,&dispersion
,
1328 &when
,&offset
,&error
,&drift
,&drifterr
,&waiting
,1);
1330 fprintf(stderr
,"tot=%d ind=%d dis=%.3f when=%.3f off=%.3f ",
1331 total
,index
,dispersion
,when
,offset
);
1332 fprintf(stderr
,"err=%.3f wait=%d\n",error
,waiting
);
1334 if (when
== 0.0) return;
1335 x
= (maxoff
< 0.0 ? -maxoff
: maxoff
);
1336 if ((offset
< 0.0 ? -offset
: offset
) > x
) maxoff
= offset
;
1338 if (operation
== op_client
|| accepts
>= count
) {
1339 if (action
== action_display
) {
1340 format_time(text
,100,offset
,error
,drift
,drifterr
,-10);
1341 printf("%s\n",text
);
1343 x
= reset_clock(offset
,error
,1);
1349 handle_saving(save_write
,&total
,&index
,&cycle
,record
,&previous
,&when
,
1352 /* Now correct the clock for a while, before getting another packet and
1353 updating the statistics. */
1355 while (when
< previous
+delay
-waiting
) {
1356 do_nothing(waiting
);
1357 if (action
== action_display
)
1360 correction
+= correct_drift(&when
,&offset
,drift
);
1361 handle_saving(save_write
,&total
,&index
,&cycle
,record
,
1362 &previous
,&when
,&correction
);
1371 void run_client (char *hostnames
[], int nhosts
) {
1373 /* Get enough responses to do something with; or not, as the case may be. Note
1374 that it allows for half of the packets to be bad, so may make up to twice as
1375 many attempts as specified by the -c value. The deadline checking is merely
1376 paranoia, to protect against broken signal handling - it cannot easily be
1377 triggered if the signal handling works. */
1379 double history
[COUNT_MAX
], guesses
[COUNT_MAX
], offset
, error
, deadline
,
1381 int precs
[COUNT_MAX
], precision
= 0;
1382 int accepts
= 0, rejects
= 0, flushes
= 0, replicates
= 0, cycle
= 0, k
;
1383 unsigned char transmit
[NTP_PACKET_MIN
];
1388 format_time(text
,50,0.0,-1.0,0.0,-1.0,-10);
1389 fprintf(stderr
,"Started=%.6f %s\n",current_time(JAN_1970
),text
);
1391 for (k
= 0; k
< nhosts
; ++k
) open_socket(k
,hostnames
[k
],delay
);
1392 if (action
!= action_display
) {
1397 deadline
= current_time(JAN_1970
)+delay
;
1399 /* Listen to broadcast packets and select the best (i.e. earliest). This will
1400 be sensitive to a bad NTP broadcaster, but I believe such things are very rare
1401 in practice. In any case, if you have one, it is probably the only one on your
1402 subnet, so you are knackered! This allows up to ETHERNET_MAX replications per
1403 packet, for systems with multiple addresses for receiving broadcasts; the only
1404 reason for a limit is to protect against broken NTP servers always returning
1407 if (operation
== op_listen
) {
1408 while (accepts
< count
) {
1409 if (current_time(JAN_1970
) > deadline
)
1410 fatal(0,"not enough valid broadcasts received in time",NULL
);
1411 flushes
+= flush_socket(0);
1412 if (read_packet(0,&data
,&x
,&y
)) {
1413 if (++rejects
> count
)
1414 fatal(0,"too many bad or lost packets",NULL
);
1419 for (k
= 0; k
< accepts
; ++k
)
1420 if (a
== history
[k
]) {
1421 if (++replicates
> ETHERNET_MAX
*count
)
1422 fatal(0,"too many replicated packets",NULL
);
1425 history
[accepts
] = a
;
1426 precs
[accepts
] = data
.precision
;
1427 guesses
[accepts
++] = x
;
1430 fprintf(stderr
,"Offset=%.6f disp=%.6f\n",x
,dispersion
);
1431 else if (verbose
> 1)
1432 fprintf(stderr
,"%s: offset=%.3f disp=%.3f\n",
1433 argv0
,x
,dispersion
);
1435 /* Note that bubblesort IS a good method for this amount of data. */
1437 for (k
= accepts
-2; k
>= 0; --k
)
1438 if (guesses
[k
] < guesses
[k
+1])
1442 guesses
[k
] = guesses
[k
+1];
1444 precision
= precs
[k
];
1445 precs
[k
] = precs
[k
+1];
1446 precs
[k
+1] = precision
;
1450 offset
= guesses
[0];
1451 precision
= precs
[0];
1452 error
= minerr
+guesses
[count
<= 5 ? count
-1 : 5]-offset
;
1454 fprintf(stderr
,"accepts=%d rejects=%d flushes=%d replicates=%d\n",
1455 accepts
,rejects
,flushes
,replicates
);
1457 /* Handle the client/server model. It keeps a record of transmitted times,
1458 mainly out of paranoia. */
1463 error
= NTP_INSANITY
;
1464 while (accepts
< count
&& attempts
< 2*count
) {
1465 if (current_time(JAN_1970
) > deadline
)
1466 fatal(0,"not enough valid responses received in time",NULL
);
1467 make_packet(&data
,NTP_CLIENT
);
1468 precs
[attempts
] = data
.precision
;
1469 outgoing
[attempts
++] = data
.transmit
;
1471 fprintf(stderr
,"Outgoing packet on socket %d:\n",cycle
);
1472 display_data(&data
);
1474 pack_ntp(transmit
,NTP_PACKET_MIN
,&data
);
1475 if (verbose
> 2) display_packet(transmit
,NTP_PACKET_MIN
);
1476 flushes
+= flush_socket(cycle
);
1477 write_socket(cycle
,transmit
,NTP_PACKET_MIN
);
1478 if (read_packet(cycle
,&data
,&x
,&y
)) {
1479 if (++rejects
> count
)
1480 fatal(0,"too many bad or lost packets",NULL
);
1485 if (++cycle
>= nhosts
) cycle
= 0;
1487 /* Work out the most accurate time, and check that it isn't more accurate than
1488 the results warrant. */
1491 fprintf(stderr
,"Offset=%.6f+/-%.6f disp=%.6f\n",x
,y
,dispersion
);
1492 else if (verbose
> 1)
1493 fprintf(stderr
,"%s: offset=%.3f+/-%.3f disp=%.3f\n",
1494 argv0
,x
,y
,dispersion
);
1495 if ((a
= x
-offset
) < 0.0) a
= -a
;
1496 if (accepts
<= 1) a
= 0.0;
1501 precision
= data
.precision
;
1504 fprintf(stderr
,"best=%.6f+/-%.6f\n",offset
,error
);
1506 sprintf(text
,"%d",cycle
);
1507 fatal(0,"inconsistent times got from NTP server on socket %s",
1510 if (error
<= minerr
) break;
1513 fprintf(stderr
,"accepts=%d rejects=%d flushes=%d\n",
1514 accepts
,rejects
,flushes
);
1517 /* Tidy up the socket, issues diagnostics and perform the action. */
1519 for (k
= 0; k
< nhosts
; ++k
) close_socket(k
);
1520 if (accepts
== 0) fatal(0,"no acceptable packets received",NULL
);
1521 if (error
> NTP_INSANITY
)
1522 fatal(0,"unable to get a reasonable time estimate",NULL
);
1524 fprintf(stderr
,"Correction: %.6f +/- %.6f disp=%.6f\n",
1525 offset
,error
,dispersion
);
1526 if (action
== action_display
) {
1527 format_time(text
,75,offset
,error
,0.0,-1.0,precision
);
1528 printf("%s\n",text
);
1530 (void)reset_clock(offset
,error
,0);
1531 if (locked
) set_lock(0);
1532 if (verbose
> 2) fprintf(stderr
,"Stopped normally\n");
1538 int main (int argc
, char *argv
[]) {
1540 /* This is the entry point and all that. It decodes the arguments and calls
1541 one of the specialised routines to do the work. */
1543 char *hostnames
[MAX_SOCKETS
], *savename
= NULL
;
1544 int daemon
= 0, nhosts
= 0, help
= 0, args
= argc
-1, k
;
1547 if (argv
[0] == NULL
|| argv
[0][0] == '\0')
1549 else if ((argv0
= strrchr(argv
[0],'/')) != NULL
)
1554 setvbuf(stdout
,NULL
,_IOLBF
,BUFSIZ
);
1555 setvbuf(stderr
,NULL
,_IOLBF
,BUFSIZ
);
1557 if (INT_MAX
< 2147483647) fatal(0,"sntp requires >= 32-bit ints",NULL
);
1558 if (DBL_EPSILON
> 1.0e-13)
1559 fatal(0,"sntp requires doubles with eps <= 1.0e-13",NULL
);
1560 for (k
= 0; k
< MAX_SOCKETS
; ++k
) hostnames
[k
] = NULL
;
1562 /* Decode the arguments. */
1566 if (strcmp(argv
[1],"-4") == 0)
1567 preferred_family(PREF_FAM_INET
);
1568 else if (strcmp(argv
[1],"-6") == 0)
1569 preferred_family(PREF_FAM_INET6
);
1570 else if (strcmp(argv
[1],"-u") == 0)
1572 else if (strcmp(argv
[1],"-q") == 0 && action
== 0)
1573 action
= action_query
;
1574 else if (strcmp(argv
[1],"-r") == 0 && action
== 0)
1575 action
= action_reset
;
1576 else if (strcmp(argv
[1],"-a") == 0 && action
== 0)
1577 action
= action_adjust
;
1578 else if (strcmp(argv
[1],"-l") == 0 && lockname
== NULL
&& argc
> 2) {
1581 } else if ((strcmp(argv
[1],"-x") == 0) &&
1583 if (argc
> 2 && sscanf(argv
[2],"%d%c",&daemon
,&c
) == 1) {
1584 if (daemon
< 1 || daemon
> 1440)
1585 fatal(0,"%s option value out of range",argv
[1]);
1589 } else if (strcmp(argv
[1],"-f") == 0 && savename
== NULL
&& argc
> 2) {
1592 } else if ((strcmp(argv
[1],"--help") == 0 ||
1593 strcmp(argv
[1],"-h") == 0 || strcmp(argv
[1],"-?") == 0) &&
1596 else if (strcmp(argv
[1],"-v") == 0 && verbose
== 0)
1598 else if (strcmp(argv
[1],"-V") == 0 && verbose
== 0)
1600 else if (strcmp(argv
[1],"-W") == 0 && verbose
== 0)
1602 else if (strcmp(argv
[1],"-e") == 0 && minerr
== 0.0 && argc
> 2) {
1603 if (sscanf(argv
[2],"%lf%c",&minerr
,&c
) != 1) syntax(1);
1604 if (minerr
<= 0.000999999 || minerr
> 1.0)
1605 fatal(0,"%s option value out of range","-e");
1607 } else if (strcmp(argv
[1],"-E") == 0 && maxerr
== 0.0 && argc
> 2) {
1608 if (sscanf(argv
[2],"%lf%c",&maxerr
,&c
) != 1) syntax(1);
1609 if (maxerr
< 1.0 || maxerr
> 60.0)
1610 fatal(0,"%s option value out of range","-E");
1612 } else if (strcmp(argv
[1],"-P") == 0 && prompt
== 0.0 && argc
> 2) {
1613 if (strcmp(argv
[2],"no") == 0)
1614 prompt
= (double)INT_MAX
;
1616 if (sscanf(argv
[2],"%lf%c",&prompt
,&c
) != 1) syntax(1);
1617 if (prompt
< 1.0 || prompt
> 3600.0)
1618 fatal(0,"%s option value out of range","-p");
1621 } else if (strcmp(argv
[1],"-d") == 0 && delay
== 0 && argc
> 2) {
1622 if (sscanf(argv
[2],"%d%c",&delay
,&c
) != 1) syntax(1);
1623 if (delay
< 1 || delay
> 3600)
1624 fatal(0,"%s option value out of range","-d");
1626 } else if (strcmp(argv
[1],"-c") == 0 && count
== 0 && argc
> 2) {
1627 if (sscanf(argv
[2],"%d%c",&count
,&c
) != 1) syntax(1);
1628 if (count
< 1 || count
> COUNT_MAX
)
1629 fatal(0,"%s option value out of range","-c");
1637 /* Check the arguments for consistency and set the defaults. */
1639 if (action
== action_query
) {
1640 if (argc
!= 1 || minerr
!= 0.0 || maxerr
!= 0.0 || count
!= 0 ||
1641 delay
!= 0 || daemon
!= 0 || prompt
!= 0.0 || lockname
!= NULL
)
1644 if (argc
< 1 || argc
> MAX_SOCKETS
|| (daemon
!= 0 && delay
!= 0))
1646 if ((prompt
|| lockname
!= NULL
) &&
1647 action
!= action_reset
&& action
!= action_adjust
)
1649 if (count
> 0 && count
< argc
-1)
1650 fatal(0,"-c value less than number of addresses",NULL
);
1652 operation
= op_client
;
1653 for (k
= 1; k
< argc
; ++k
) {
1654 if (argv
[k
][0] == '\0' || argv
[k
][0] == '-')
1655 fatal(0,"invalid Internet address '%s'",argv
[k
]);
1656 hostnames
[k
-1] = argv
[k
];
1660 operation
= op_listen
;
1663 if (action
== 0) action
= action_display
;
1664 if (minerr
<= 0.0) minerr
= (operation
== op_listen
? 0.5 : 0.1);
1665 if (maxerr
<= 0.0) maxerr
= 5.0;
1666 if (count
== 0) count
= (argc
-1 < 5 ? 5 : argc
-1);
1667 if ((argc
== 1 || (daemon
!= 0 && action
!= action_query
)) && count
< 5)
1668 fatal(0,"at least 5 packets needed in this mode",NULL
);
1669 if ((action
== action_reset
|| action
== action_adjust
) &&
1671 lockname
= LOCKNAME
;
1673 /* The '-x' option changes the implications of many other settings, though this
1674 is not usually apparent to the caller. Most of the time delays are to ensure
1675 that stuck states terminate, and do not affect the result. */
1678 if (minerr
>= maxerr
|| maxerr
>= daemon
)
1679 fatal(0,"values not in order -e < -E < -x",NULL
);
1680 waiting
= delay
= daemon
*= 60;
1682 if (savename
!= NULL
)
1683 fatal(0,"-f can be specified only with -x",NULL
);
1685 delay
= (operation
== op_listen
? 300 :
1686 (2*count
>= 15 ? 2*count
+1 :15));
1687 if (operation
== op_listen
) {
1688 if (minerr
>= maxerr
|| maxerr
>= delay
/count
)
1689 fatal(0,"values not in order -e < -E < -d/-c",NULL
);
1691 if (minerr
>= maxerr
|| maxerr
>= delay
)
1692 fatal(0,"values not in order -e < -E < -d",NULL
);
1694 if (2*count
>= delay
) fatal(0,"-c must be less than half -d",NULL
);
1695 waiting
= delay
/count
;
1697 if (prompt
== 0.0) prompt
= 30.0;
1699 if ((daemon
|| action
== action_query
) && savename
== NULL
)
1700 savename
= SAVENAME
;
1702 /* Diagnose where we are, if requested, and separate out the classes of
1703 operation. The calls do not return. */
1705 if (help
) syntax(args
== 1);
1707 fprintf(stderr
,"%s options: a=%d v=%d e=%.3f E=%.3f P=%.3f\n",
1708 argv0
,action
,verbose
,minerr
,maxerr
,prompt
);
1709 fprintf(stderr
," d=%d c=%d %c=%d op=%d l=%s f=%s",
1710 delay
,count
,'x',daemon
,operation
,
1711 (lockname
== NULL
? "" : lockname
),
1712 (savename
== NULL
? "" : savename
));
1713 for (k
= 0; k
< MAX_SOCKETS
; ++k
)
1714 if (hostnames
[k
] != NULL
) fprintf(stderr
," %s",hostnames
[k
]);
1715 fprintf(stderr
,"\n");
1717 if (nhosts
== 0) nhosts
= 1; /* Kludge for broadcasts */
1718 if (action
== action_query
) {
1719 if (savename
== NULL
|| savename
[0] == '\0')
1720 fatal(0,"no daemon save file specified",NULL
);
1721 else if ((savefile
= fopen(savename
,"rb")) == NULL
)
1722 fatal(0,"unable to open the daemon save file",NULL
);
1724 } else if (daemon
!= 0) {
1725 if (savename
!= NULL
&& savename
[0] != '\0' &&
1726 (savefile
= fopen(savename
,"rb+")) == NULL
&&
1727 (savefile
= fopen(savename
,"wb+")) == NULL
)
1728 fatal(0,"unable to open the daemon save file",NULL
);
1729 run_daemon(hostnames
,nhosts
,1);
1730 while (1) run_daemon(hostnames
,nhosts
,0);
1732 run_client(hostnames
,nhosts
);
1733 fatal(0,"internal error at end of main",NULL
);
1734 return EXIT_FAILURE
;