1/*  Copyright (C) 1996, 1997, 2000 N.M. Maclaren
2    Copyright (C) 1996, 1997, 2000 The University of Cambridge
3
4This is a complete SNTP implementation, which was easier to write than to port
5xntp to a new version of Unix with any hope of maintaining it thereafter.  It
6supports the full SNTP (RFC 2030) client- and server-side challenge-response
7and broadcast protocols.  It should achieve nearly optimal accuracy with very
8few transactions, provided only that a client has access to a trusted server
9and that communications are not INVARIABLY slow.  As this is the environment in
10which 90-99% of all NTP systems are run ....
11
12The specification of this program is:
13
14    sntp [ --help | -h | -? ] [ -v | -V | -W ]
15        [ -q [ -f savefile ] |
16            [ { -r | -a } [ -P prompt ] [ -l lockfile ] ]
17            [ -c count ] [ -e minerr ][ -E maxerr ]
18            [ -d delay | -x [ separation ] [ -f savefile ] ]
19            [ -4 | -6 ] [ address(es) ] ]
20
21    --help, -h and -? all print the syntax of the command.
22
23    -v indicates that diagnostic messages should be written to standard error,
24and -V requests more output for investigating apparently inconsistent
25timestamps.  -W requests very verbose debugging output, and will interfere with
26the timing when writing to the terminal (because of line buffered output from
27C); it is useful only when debugging the source.  Note that the times produced
28by -V and -W are the corrections needed, and not the error in the local clock.
29
30    -q indicates that it will query a savefile that is being maintained by
31it being run in daemon mode.
32
33     The default is that it should behave as a client, and the following options
34are then relevant:
35
36    -r indicates that the system clock should be reset by 'settimeofday'.
37Naturally, this will work only if the user has enough privilege.
38
39    -a indicates that the system clock should be reset by 'adjtime'.
40Naturally, this will work only if the user has enough privilege.
41
42    -x indicates that the program should run as a daemon (i.e. forever), and
43allow for clock drift.
44
45    -4 or -6 force dns resolving to ipv4 or ipv6 addresses.
46
47    The default is to write the current date and time to the standard output in
48a format like '1996 Oct 15 20:17:25.123 + 4.567 +/- 0.089 secs', indicating the
49estimated true (local) time and the error in the local clock.  In daemon mode,
50it will add drift information in a format like ' + 1.3 +/- 0.1 ppm', and
51display this at roughly 'separation' intervals.
52
53    'minerr' is the maximum ignorable variation between the clocks.  Acceptable
54values are from 0.001 to 1, and the default is 0.1 if 'address' is specified
55and 0.5 otherwise.
56
57    'maxerr' is the maximum value of various delays that are deemed acceptable.
58Acceptable values are from 1 to 60, and the default is 5.  It should sometimes
59be increased if there are problems with the network, NTP server or system
60clock, but take care.
61
62    'prompt' is the maximum clock change that will be made automatically.
63Acceptable values are from 1 to 3600, and the default is 30.  If the program is
64being run interactively, larger values will cause a prompt.  The value may also
65be 'no', and the change will be made without prompting.
66
67    'count' is the maximum number of NTP packets to require.  Acceptable values
68are from 1 to 25 if 'address' is specified and '-x' is not, and from 5 to 25
69otherwise; the default is 5.  If the maximum isn't enough, you need a better
70consistency algorithm than this program uses.  Don't increase it.
71
72    'delay' is a rough limit on the total running time in seconds.  Acceptable
73values are from 1 to 3600, and the default is 15 if 'address' is specified and
74300 otherwise.
75
76    'separation' is the time to wait between calls to the server in minutes if
77'address' is specified, and the minimum time between broadcast packets if not.
78Acceptable values are from 1 to 1440 (a day), and the default is 300.
79
80    'lockfile' may be used in an update mode to ensure that there is only
81one copy of sntp running at once.  The default is installation-dependent,
82but will usually be /etc/sntp.pid.
83
84    'savefile' may be used in daemon mode to store a record of previous
85packets, which may speed up recalculating the drift after sntp has to be
86restarted (e.g. because of network or server outages).  The default is
87installation-dependent, but will usually be /etc/sntp.state.  Note that
88there is no locking of this file, and using it twice may cause chaos.
89
90    'address' is the DNS name or IP number of a host to poll; if no name is
91given, the program waits for broadcasts.  Note that a single component numeric
92address is not allowed.
93
94For sanity, it is also required that 'minerr' < 'maxerr' < 'delay' (if
95listening for broadcasts, 'delay/count' and, in daemon mode, 'separation') and,
96for sordid Unixish reasons, that 2*'count' < 'delay'.  The last could be fixed,
97but isn't worth it.  Note that none of the above values are closely linked to
98the limits described in the NTP protocol (RFC 1305).  Do not increase the
99compiled-in bounds excessively, or the code will fail.
100
101The algorithm used to decide whether to accept a correction is whether it would
102seem to improve matters.  Unlike the 'xntp' suite, little attempt is made to
103handle really knotted scenarios, and diagnostics are written to standard error.
104In non-daemon client mode, it is intended to be run as a command or in a 'cron'
105job.  Unlike 'ntpdate', its default mode is simply to display the clock error.
106
107It assumes that floating-point arithmetic is tolerably efficient, which is true
108for even the cheapest personal computer nowadays.  If, however, you want to
109port this to a toaster, you may have problems!
110
111In its terminating modes, its return code is EXIT_SUCCESS if the operation was
112completed successfully and EXIT_FAILURE otherwise.
113
114In daemon mode, it runs for ever and stops with a return code EXIT_FAILURE
115only after a severe error.  In daemon mode, it will fail if the server is
116inaccessible for a long time or seriously sick, and will need manual
117restarting.
118
119
120WARNING: this program has reached its 'hack count' and needs restructuring,
121badly.  Perhaps the worst code is in run_daemon().  You are advised not to
122fiddle unless you really have to. */
123
124
125
126#include "header.h"
127
128#include <limits.h>
129#include <float.h>
130#include <math.h>
131
132#define MAIN
133#include "kludges.h"
134#undef MAIN
135
136
137
138/* NTP definitions.  Note that these assume 8-bit bytes - sigh.  There is
139little point in parameterising everything, as it is neither feasible nor
140useful.  It would be very useful if more fields could be defined as
141unspecified.  The NTP packet-handling routines contain a lot of extra
142assumptions. */
143
144#define JAN_1970   2208988800.0        /* 1970 - 1900 in seconds */
145#define NTP_SCALE  4294967296.0        /* 2^32, of course! */
146
147#define NTP_PACKET_MIN       48        /* Without authentication */
148#define NTP_PACKET_MAX       68        /* With authentication (ignored) */
149#define NTP_DISP_FIELD        8        /* Offset of dispersion field */
150#define NTP_REFERENCE        16        /* Offset of reference timestamp */
151#define NTP_ORIGINATE        24        /* Offset of originate timestamp */
152#define NTP_RECEIVE          32        /* Offset of receive timestamp */
153#define NTP_TRANSMIT         40        /* Offset of transmit timestamp */
154
155#define NTP_LI_FUDGE          0        /* The current 'status' */
156#define NTP_VERSION           3        /* The current version */
157#define NTP_VERSION_MAX       4        /* The maximum valid version */
158#define NTP_STRATUM          15        /* The current stratum as a server */
159#define NTP_STRATUM_MAX      15        /* The maximum valid stratum */
160#define NTP_POLLING           8        /* The current 'polling interval' */
161#define NTP_PRECISION         0        /* The current 'precision' - 1 sec. */
162
163#define NTP_ACTIVE            1        /* NTP symmetric active request */
164#define NTP_PASSIVE           2        /* NTP symmetric passive response */
165#define NTP_CLIENT            3        /* NTP client request */
166#define NTP_SERVER            4        /* NTP server response */
167#define NTP_BROADCAST         5        /* NTP server broadcast */
168
169#define NTP_INSANITY     3600.0        /* Errors beyond this are hopeless */
170#define RESET_MIN            15        /* Minimum period between resets */
171#define ABSCISSA            3.0        /* Scale factor for standard errors */
172
173
174
175/* Local definitions and global variables (mostly options).  These are all of
176the quantities that control the main actions of the program.  The first three
177are the only ones that are exported to other modules. */
178
179const char *argv0 = NULL;              /* For diagnostics only - not NULL */
180int verbose = 0,                       /* Default = 0, -v = 1, -V = 2, -W = 3 */
181    operation = 0;                     /* Defined in header.h - see action */
182const char *lockname = NULL;           /* The name of the lock file */
183int unprivport = 0;			/* Use an unpriv port for query? */
184
185#define COUNT_MAX          25          /* Do NOT increase this! */
186#define WEEBLE_FACTOR     1.2          /* See run_server() and run_daemon() */
187#define ETHERNET_MAX        5          /* See run_daemon() and run_client() */
188
189#define action_display      1          /* Just display the result */
190#define action_reset        2          /* Reset using 'settimeofday' */
191#define action_adjust       3          /* Reset using 'adjtime' */
192#define action_broadcast    4          /* Behave as a server, broadcasting */
193#define action_server       5          /* Behave as a server for clients */
194#define action_query        6          /* Query a daemon savefile */
195
196#define save_read_only      1          /* Read the saved state only */
197#define save_read_check     2          /* Read and check it */
198#define save_write          3          /* Write the saved state */
199#define save_clear          4          /* Clear the saved state */
200
201static const char version[] = VERSION; /* For reverse engineering :-) */
202static int action = 0,                 /* Defined above - see operation */
203    count = 0,                         /* -c value in seconds */
204    delay = 0,                         /* -d or -x value in seconds */
205    attempts = 0,                      /* Packets transmitted up to 2*count */
206    waiting = 0,                       /* -d/-c except for in daemon mode */
207    locked = 0;                        /* set_lock(1) has been called */
208static double outgoing[2*COUNT_MAX],   /* Transmission timestamps */
209    minerr = 0.0,                      /* -e value in seconds */
210    maxerr = 0.0,                      /* -E value in seconds */
211    prompt = 0.0,                      /* -p value in seconds */
212    dispersion = 0.0;                  /* The source dispersion in seconds */
213static FILE *savefile = NULL;          /* Holds the data to restart from */
214
215
216
217/* The unpacked NTP data structure, with all the fields even remotely relevant
218to SNTP. */
219
220typedef struct NTP_DATA {
221    unsigned char status, version, mode, stratum, polling;
222    signed char precision;
223    double dispersion, reference, originate, receive, transmit, current;
224} ntp_data;
225
226
227
228/* The following structure is used to keep a record of packets in daemon mode;
229it contains only the information that is actually used for the drift and error
230calculations. */
231
232typedef struct {
233    double dispersion, weight, when, offset, error;
234} data_record;
235
236void syntax(int);
237void display_data(ntp_data *);
238void display_packet(unsigned char *, int);
239void pack_ntp(unsigned char *, int, ntp_data *);
240void unpack_ntp(ntp_data *, unsigned char *, int);
241void make_packet(ntp_data *, int);
242int read_packet(int, ntp_data *, double *, double *);
243void format_time(char *, int, double, double, double, double, int);
244double reset_clock(double, double, int);
245void run_server(void);
246double estimate_stats(int *, int *, data_record *, double, double *, double *,
247	double *, double *, double *, double *, int *, int);
248double correct_drift(double *, double *, double);
249void handle_saving(int, int *, int *, int *, data_record *, double *,
250	double *, double *);
251void query_savefile(void);
252void run_daemon(char **, int, int);
253void run_client(char **, int);
254
255void fatal (int syserr, const char *message, const char *insert) {
256
257/* Issue a diagnostic and stop.  Be a little paranoid about recursion. */
258
259    int k = errno;
260    static int called = 0;
261
262    if (message != NULL) {
263        fprintf(stderr,"%s: ",argv0);
264        fprintf(stderr,message,insert);
265        fprintf(stderr,"\n");
266    }
267    errno = k;
268    if (syserr) perror(argv0);
269    if (! called) {
270        called = 1;
271        if (savefile != NULL && fclose(savefile))
272            fatal(1,"unable to close the daemon save file",NULL);
273        if (locked) set_lock(0);
274    }
275    exit(EXIT_FAILURE);
276}
277
278
279
280void syntax (int halt) {
281
282/* The standard, unfriendly Unix error message.  Some errors are diagnosed more
283helpfully.  This is called before any files or sockets are opened. */
284
285    fprintf(stderr,"Syntax: %s [ --help | -h | -? ] [ -v | -V | -W ] \n",argv0);
286    fprintf(stderr,"    [ -q [ -f savefile ] |\n");
287    fprintf(stderr,"        [ { -r | -a } [ -P prompt ] [ -l lockfile ] ]\n");
288    fprintf(stderr,"            [ -c count ] [ -e minerr ] [ -E maxerr ]\n");
289    fprintf(stderr,"            [ -d delay | -x [ separation ] ");
290    fprintf(stderr,"[ -f savefile ] ]\n");
291    fprintf(stderr,"        [ -4 | -6 ] [-u] [ address(es) ] ]\n");
292    if (halt) exit(EXIT_FAILURE);
293}
294
295
296
297void display_data (ntp_data *data) {
298
299/* This formats the essential NTP data, as a debugging aid. */
300
301    fprintf(stderr,"sta=%d ver=%d mod=%d str=%d pol=%d dis=%.6f ref=%.6f\n",
302        data->status,data->version,data->mode,data->stratum,data->polling,
303        data->dispersion,data->reference);
304    fprintf(stderr,"ori=%.6f rec=%.6f\n",data->originate,data->receive);
305    fprintf(stderr,"tra=%.6f cur=%.6f\n",data->transmit,data->current);
306}
307
308
309
310void display_packet (unsigned char *packet, int length) {
311
312/* This formats a possible packet very roughly, as a debugging aid. */
313
314    int i;
315
316    if (length < NTP_PACKET_MIN || length > NTP_PACKET_MAX) return;
317    for (i = 0; i < length; ++i) {
318        if (i != 0 && i%32 == 0)
319            fprintf(stderr,"\n");
320         else if (i != 0 && i%4 == 0)
321             fprintf(stderr," ");
322         fprintf(stderr,"%.2x",packet[i]);
323    }
324    fprintf(stderr,"\n");
325}
326
327
328
329void pack_ntp (unsigned char *packet, int length, ntp_data *data) {
330
331/* Pack the essential data into an NTP packet, bypassing struct layout and
332endian problems.  Note that it ignores fields irrelevant to SNTP. */
333
334    int i, k;
335    double d;
336
337    memset(packet,0,(size_t)length);
338    packet[0] = (data->status<<6)|(data->version<<3)|data->mode;
339    packet[1] = data->stratum;
340    packet[2] = data->polling;
341    packet[3] = data->precision;
342    d = data->originate/NTP_SCALE;
343    for (i = 0; i < 8; ++i) {
344        if ((k = (int)(d *= 256.0)) >= 256) k = 255;
345        packet[NTP_ORIGINATE+i] = k;
346        d -= k;
347    }
348    d = data->receive/NTP_SCALE;
349    for (i = 0; i < 8; ++i) {
350        if ((k = (int)(d *= 256.0)) >= 256) k = 255;
351        packet[NTP_RECEIVE+i] = k;
352        d -= k;
353    }
354    d = data->transmit/NTP_SCALE;
355    for (i = 0; i < 8; ++i) {
356        if ((k = (int)(d *= 256.0)) >= 256) k = 255;
357        packet[NTP_TRANSMIT+i] = k;
358        d -= k;
359    }
360}
361
362
363
364void unpack_ntp (ntp_data *data, unsigned char *packet, int length) {
365
366/* Unpack the essential data from an NTP packet, bypassing struct layout and
367endian problems.  Note that it ignores fields irrelevant to SNTP. */
368
369    int i;
370    double d;
371
372    data->current = current_time(JAN_1970);    /* Best to come first */
373    data->status = (packet[0] >> 6);
374    data->version = (packet[0] >> 3)&0x07;
375    data->mode = packet[0]&0x07;
376    data->stratum = packet[1];
377    data->polling = packet[2];
378    data->precision = packet[3];
379    d = 0.0;
380    for (i = 0; i < 4; ++i) d = 256.0*d+packet[NTP_DISP_FIELD+i];
381    data->dispersion = d/65536.0;
382    d = 0.0;
383    for (i = 0; i < 8; ++i) d = 256.0*d+packet[NTP_REFERENCE+i];
384    data->reference = d/NTP_SCALE;
385    d = 0.0;
386    for (i = 0; i < 8; ++i) d = 256.0*d+packet[NTP_ORIGINATE+i];
387    data->originate = d/NTP_SCALE;
388    d = 0.0;
389    for (i = 0; i < 8; ++i) d = 256.0*d+packet[NTP_RECEIVE+i];
390    data->receive = d/NTP_SCALE;
391    d = 0.0;
392    for (i = 0; i < 8; ++i) d = 256.0*d+packet[NTP_TRANSMIT+i];
393    data->transmit = d/NTP_SCALE;
394}
395
396
397
398void make_packet (ntp_data *data, int mode) {
399
400/* Create an outgoing NTP packet, either from scratch or starting from a
401request from a client.  Note that it implements the NTP specification, even
402when this is clearly misguided, except possibly for the setting of LI.  It
403would be easy enough to add a sanity flag, but I am not in the business of
404designing an alternative protocol (however much better it might be). */
405
406    data->status = NTP_LI_FUDGE<<6;
407    data->stratum = NTP_STRATUM;
408    data->reference = data->dispersion = 0.0;
409    if (mode == NTP_SERVER) {
410        data->mode = (data->mode == NTP_CLIENT ? NTP_SERVER : NTP_PASSIVE);
411        data->originate = data->transmit;
412        data->receive = data->current;
413    } else {
414        data->version = NTP_VERSION;
415        data->mode = mode;
416        data->polling = NTP_POLLING;
417        data->precision = NTP_PRECISION;
418        data->receive = data->originate = 0.0;
419    }
420    data->current = data->transmit = current_time(JAN_1970);
421}
422
423
424
425int read_packet (int which, ntp_data *data, double *off, double *err) {
426
427/* Check the packet and work out the offset and optionally the error.  Note
428that this contains more checking than xntp does.  This returns 0 for success, 1
429for failure and 2 for an ignored broadcast packet (a kludge for servers).  Note
430that it must not change its arguments if it fails. */
431
432    unsigned char receive[NTP_PACKET_MAX+1];
433    double delay1, delay2, x, y;
434    int response = 0, failed, length, i, k;
435
436/* Read the packet and deal with diagnostics. */
437
438    if ((length = read_socket(which,receive,NTP_PACKET_MAX+1,waiting)) <= 0)
439        return 1;
440    if (length < NTP_PACKET_MIN || length > NTP_PACKET_MAX) {
441        if (verbose)
442            fprintf(stderr,"%s: bad length %d for NTP packet on socket %d\n",
443                argv0,length,which);
444        return 1;
445    }
446    if (verbose > 2) {
447        fprintf(stderr,"Incoming packet on socket %d:\n",which);
448        display_packet(receive,length);
449    }
450    unpack_ntp(data,receive,length);
451    if (verbose > 2) display_data(data);
452
453/* Start by checking that the packet looks reasonable.  Be a little paranoid,
454but allow for version 1 semantics and sick clients. */
455
456    if (operation == op_listen)
457        failed = (data->mode != NTP_BROADCAST);
458    else {
459        failed = (data->mode != NTP_SERVER && data->mode != NTP_PASSIVE);
460        response = 1;
461    }
462    if (failed || data->status == 3 || data->version < 1 ||
463            data->version > NTP_VERSION_MAX ||
464            data->stratum > NTP_STRATUM_MAX) {
465        if (verbose)
466            fprintf(stderr,
467                "%s: Unusable NTP packet rejected on socket %d (f=%d, status %d, version %d, stratum %d)\n",
468                argv0, which,
469		failed, data->status, data->version, data->stratum);
470        return 1;
471    }
472
473/* Note that the conventions are very poorly defined in the NTP protocol, so we
474have to guess.  Any full NTP server perpetrating completely unsynchronised
475packets is an abomination, anyway, so reject it. */
476
477    delay1 = data->transmit-data->receive;
478    delay2 = data->current-data->originate;
479    failed = (
480	      (  data->stratum != 0
481	      /* && data->stratum != NTP_STRATUM_MAX */
482	      && data->reference == 0.0
483	      )
484	     || data->transmit == 0.0
485	     );
486    if (response &&
487            (data->originate == 0.0 || data->receive == 0.0 ||
488                (data->reference != 0.0 && data->receive < data->reference) ||
489                delay1 < 0.0 || delay1 > NTP_INSANITY || delay2 < 0.0 ||
490                data->dispersion > NTP_INSANITY))
491        failed = 1;
492    if (failed) {
493        if (verbose)
494            fprintf(stderr,
495                "%s: incomprehensible NTP packet rejected on socket %d\n",
496                argv0,which);
497        return 1;
498    }
499    if (data->stratum == NTP_STRATUM_MAX) {
500	fprintf(stderr,
501	    "%s: unsynch NTP response on socket %d\n",
502	    argv0,which);
503        return 1;
504    }
505
506/* If it is a response, check that it corresponds to one of our requests and
507has got here in a reasonable length of time. */
508
509    if (response) {
510        k = 0;
511        for (i = 0; i < attempts; ++i)
512            if (data->originate == outgoing[i]) {
513                outgoing[i] = 0.0;
514                ++k;
515            }
516        if (k != 1 || delay2 > NTP_INSANITY) {
517            if (verbose)
518                fprintf(stderr,
519                    "%s: bad response from NTP server rejected on socket %d\n",
520                    argv0,which);
521            return 1;
522        }
523    }
524
525/* Now return the time information.  If it is a server response, it contains
526enough information that we can be almost certain that we have not been fooled
527too badly.  Heaven help us with broadcasts - make a wild kludge here, and see
528elsewhere for other kludges. */
529
530    if (dispersion < data->dispersion) dispersion = data->dispersion;
531    if (operation == op_listen) {
532        *off = data->transmit-data->current;
533        *err = NTP_INSANITY;
534    } else {
535        x = data->receive-data->originate;
536        y = (data->transmit == 0.0 ? 0.0 : data->transmit-data->current);
537        *off = 0.5*(x+y);
538        *err = x-y;
539        x = data->current-data->originate;
540        if (0.5*x > *err) *err = 0.5*x;
541    }
542    return 0;
543}
544
545
546
547void format_time (char *text, int length, double offset, double error,
548    double drift, double drifterr, int precision) {
549
550/* Format the current time into a string, with the extra information as
551requested.  Note that the rest of the program uses the correction needed, which
552is what is printed for diagnostics, but this formats the error in the local
553system for display to users.  So the results from this are the negation of
554those printed by the verbose options. */
555
556    int milli, len;
557    time_t now;
558    struct tm *gmt;
559    static const char *months[] = {
560        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
561        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
562    };
563
564/* Work out and format the current local time.  Note that some semi-ANSI
565systems do not set the return value from (s)printf. */
566
567    now = convert_time(current_time(offset),&milli);
568    errno = 0;
569    if ((gmt = localtime(&now)) == NULL)
570        fatal(1,"unable to work out local time",NULL);
571    len = 21;
572    if (length <= len) fatal(0,"internal error calling format_time",NULL);
573    errno = 0;
574    precision /= -3;
575    len += precision;
576    sprintf(text,"%.4d %s %.2d %.2d:%.2d:%.2d.%.*d",
577            gmt->tm_year+1900,months[gmt->tm_mon],gmt->tm_mday,
578            gmt->tm_hour,gmt->tm_min,gmt->tm_sec,precision,milli);
579    if (strlen(text) != len)
580        fatal(1,"unable to format current local time",NULL);
581
582/* Append the information about the offset, if requested. */
583
584    if (error >= 0.0) {
585        if (length < len+30)
586            fatal(0,"internal error calling format_time",NULL);
587        errno = 0;
588        sprintf(&text[len]," %c %.*f +/- %.*f secs",(offset > 0.0 ? '-' : '+'),
589		precision,(offset > 0.0 ? offset : -offset),
590		precision,dispersion+error);
591        if (strlen(&text[len]) < 22)
592            fatal(1,"unable to format clock correction",NULL);
593    }
594
595/* Append the information about the drift, if requested. */
596
597    if (drifterr >= 0.0) {
598        len = strlen(text);
599        if (length < len+25)
600            fatal(0,"internal error calling format_time",NULL);
601        errno = 0;
602        sprintf(&text[len]," %c %.1f +/- %.1f ppm",
603                (drift > 0.0 ? '-' : '+'),1.0e6*fabs(drift),
604                1.0e6*drifterr);
605        if (strlen(&text[len]) < 17)
606            fatal(1,"unable to format clock correction",NULL);
607    }
608
609/* It would be better to check for field overflow, but it is a lot of code to
610trap extremely implausible scenarios.  This will usually stop chaos from
611spreading. */
612
613    if (strlen(text) >= length)
614        fatal(0,"internal error calling format_time",NULL);
615}
616
617
618
619double reset_clock (double offset, double error, int daemon) {
620
621/* Reset the clock, if appropriate, and return the correction actually used.
622This contains most of the checking for whether changes are worthwhile, except
623in daemon mode. */
624
625    double absoff = (offset < 0 ? -offset : offset);
626    char text[50];
627
628/* If the correction is large, ask for confirmation before proceeding. */
629
630    if (absoff > prompt) {
631        if (! daemon && ftty(stdin) && ftty(stdout)) {
632            printf("The time correction is %.3f +/- %.3f+%.3f seconds\n",
633                offset,dispersion,error);
634            printf("Do you want to correct the time anyway? ");
635            fflush(stdout);
636            if (toupper(getchar()) != 'Y') {
637                printf("OK - quitting\n");
638                fatal(0,NULL,NULL);
639            }
640        } else {
641            sprintf(text,"%.3f +/- %.3f+%.3f",offset,dispersion,error);
642            fatal(0,"time correction too large: %s seconds",text);
643        }
644    }
645
646/* See if the correction is reasonably reliable and worth making. */
647
648    if (absoff < (daemon ? 0.5 : 1.0)*minerr) {
649        if (daemon ? verbose > 1 : verbose)
650            fprintf(stderr,"%s: correction %.3f +/- %.3f+%.3f secs - ignored\n",
651                argv0,offset,dispersion,error);
652        return 0.0;
653    } else if (absoff < 2.0*error) {
654        if (daemon ? verbose > 1 : verbose)
655            fprintf(stderr,
656                "%s: correction %.3f +/- %.3f+%.3f secs - suppressed\n",
657                argv0,offset,dispersion,error);
658        return 0.0;
659    }
660
661/* Make the correction.  Provide some protection against the previous
662correction not having completed, but it will rarely help much. */
663
664    adjust_time(offset,(action == action_reset ? 1 : 0),
665        (daemon ? 2.0*minerr : 0.0));
666    if (daemon ? verbose > 1 : verbose) {
667        format_time(text,50,0.0,-1.0,0.0,-1.0,-10);
668        fprintf(stderr,
669            "%s: time changed by %.3f secs to %s +/- %.3f+%.3f\n",
670            argv0,offset,text,dispersion,error);
671    }
672    return offset;
673}
674
675
676double estimate_stats (int *a_total, int *a_index, data_record *record,
677    double correction, double *a_disp, double *a_when, double *a_offset,
678    double *a_error, double *a_drift, double *a_drifterr, int *a_wait,
679    int update) {
680
681/* This updates the running statistics and returns the best estimate of what to
682do now.  It returns the timestamp relevant to the correction.  If broadcasts
683are rare and the drift is large, it will fail - you should then use a better
684synchronisation method.  It will also fail if something goes severely wrong
685(e.g. if the local clock is reset by another process or the transmission errors
686are beyond reason).
687
688There is a kludge for synchronisation loss during down time.  If it detects
689this, it will update only the history data and return zero; this is then
690handled specially in run_daemon().  While it could correct the offset, this
691might not always be the right thing to do. */
692
693    double weight, disp, when, offset, error, drift, drifterr,
694        now, e, w, x, y, z;
695    int total = *a_total, index = *a_index, wait = *a_wait, i;
696    char text[50];
697
698/* Correct the previous data and store a new entry in the circular buffer. */
699
700    for (i = 0; i < total; ++i) {
701        record[i].when += correction;
702        record[i].offset -= correction;
703    }
704    if (update) {
705        record[index].dispersion = *a_disp;
706        record[index].when = *a_when;
707        record[index].offset = *a_offset;
708        if (verbose > 1)
709            fprintf(stderr,"%s: corr=%.3f when=%.3f disp=%.3f off=%.3f",
710                argv0,correction,*a_when,*a_disp,*a_offset); /* See below */
711        if (operation == op_listen) {
712            if (verbose > 1) fprintf(stderr,"\n");
713            record[index].error = minerr;
714            record[index].weight = 1.0;
715        } else {
716            if (verbose > 1) fprintf(stderr," err=%.3f\n",*a_error);
717            record[index].error = x = *a_error;
718            record[index].weight = 1.0/(x > minerr ? x*x : minerr*minerr);
719        }
720        if (++index >= count) index = 0;
721        *a_index = index;
722        if (++total > count) total = count;
723        *a_total = total;
724        if (verbose > 2)
725            fprintf(stderr,"corr=%.6f tot=%d ind=%d\n",correction,total,index);
726    }
727
728/* If there is insufficient data yet, use the latest estimates and return
729forthwith.  Note that this will not work for broadcasts, but they will be
730disabled in run_daemon(). */
731
732    if ((operation == op_listen && total < count && update) || total < 3) {
733        *a_drift = 0.0;
734        *a_drifterr = -1.0;
735        *a_wait = delay;
736        return *a_when;
737    }
738
739/* Work out the average time, offset, error etc.  Note that the dispersion is
740not subject to the central limit theorem.  Unfortunately, the variation in the
741source's dispersion is our only indication of how consistent its clock is. */
742
743    disp = weight = when = offset = y = 0.0;
744    for (i = 0; i < total; ++i) {
745        weight += w = record[i].weight;
746        when += w*record[i].when;
747        offset += w*record[i].offset;
748        y += w*record[i].dispersion;
749        if (disp < record[i].dispersion)
750            disp = record[i].dispersion;
751    }
752    when /= weight;
753    offset /= weight;
754    y /= weight;
755    if (verbose > 2)
756        fprintf(stderr,"disp=%.6f wgt=%.3f when=%.6f off=%.6f\n",
757            disp,weight,when,offset);
758
759/* If there is enough data, estimate the drift and errors by regression.  Note
760that it is essential to calculate the mean square error, not the mean error. */
761
762    error = drift = x = z = 0.0;
763    for (i = 0; i < total; ++i) {
764        w = record[i].weight/weight;
765        x += w*(record[i].when-when)*(record[i].when-when);
766        drift += w*(record[i].when-when)*(record[i].offset-offset);
767        z += w*(record[i].offset-offset)*(record[i].offset-offset);
768        error += w*record[i].error*record[i].error+
769            2.0*w*(record[i].dispersion-y)*(record[i].dispersion-y);
770    }
771    if (verbose > 2)
772        fprintf(stderr,"X2=%.3f XY=%.6f Y2=%.9f E2=%.9f ",x,drift,z,error);
773
774/* When calculating the errors, add some paranoia mainly to check for coding
775errors and complete lunacy, attempting to retry if at all possible.  Because
776glitches at this point are so common, log a reset even in non-verbose mode.
777There will be more thorough checks later.  Note that we cannot usefully check
778the error for broadcasts. */
779
780    z -= drift*drift/x;
781    if (verbose > 2) fprintf(stderr,"S2=%.9f\n",z);
782    if (! update) {
783        if (z > 1.0e6)
784            fatal(0,"stored data too unreliable for time estimation",NULL);
785    } else if (operation == op_client) {
786        e = error+disp*disp+minerr*minerr;
787        if (z > e) {
788            if (verbose || z >= maxerr*maxerr)
789                fprintf(stderr,
790                    "%s: excessively high error %.3f > %.3f > %.3f\n",
791                    argv0,sqrt(z),sqrt(e),sqrt(error));
792            if (total <= 1)
793                return 0.0;
794            else if (z < maxerr*maxerr) {
795                sprintf(text,"resetting on error %.3g > %.3g",
796                    sqrt(z),sqrt(e));
797                log_message(text);
798                return 0.0;
799            } else
800                fatal(0,"incompatible (i.e. erroneous) timestamps",NULL);
801        } else if (z > error && verbose)
802            fprintf(stderr,
803                "%s: anomalously high error %.3f > %.3f, but < %.3f\n",
804                argv0,sqrt(z),sqrt(error),sqrt(e));
805    } else {
806        if (z > maxerr*maxerr)
807            fatal(0,"broadcasts too unreliable for time estimation",NULL);
808    }
809    drift /= x;
810    drifterr = ABSCISSA*sqrt(z/(x*total));
811    error = (operation == op_listen ? minerr : 0.0)+ABSCISSA*sqrt(z/total);
812    if (verbose > 2)
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);
816
817/* Estimate the optimal short-loop period, checking it carefully.  Remember to
818check that this whole process is likely to be accurate enough and that the
819delay function may be inaccurate. */
820
821    wait = delay;
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) {
826        if (verbose > 2)
827            fprintf(stderr,"Drift correction suppressed\n");
828    } else {
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);
832        if (wait > delay)
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);
837        }
838    }
839    if (wait < *a_wait/2) wait = *a_wait/2;
840    if (wait > *a_wait*2) wait = *a_wait*2;
841
842/* Now work out what the correction should be, as distinct from what it should
843have been, remembering that older times are less certain. */
844
845    now = current_time(JAN_1970);
846    x = now-when;
847    offset += x*drift;
848    error += x*drifterr;
849    for (i = 0; i < total; ++i) {
850        x = now-record[i].when;
851        z = record[i].error+x*drifterr;
852        if (z < error) {
853            when = record[i].when;
854            offset = record[i].offset+x*drift;
855            error = z;
856        }
857    }
858    if (verbose > 2)
859        fprintf(stderr,"now=%.6f when=%.6f off=%.6f err=%.6f wait=%d\n",
860            now,when,offset,error,wait);
861
862/* Finally, return the result. */
863
864    *a_disp = disp;
865    *a_when = when;
866    *a_offset = offset;
867    *a_error = error;
868    *a_drift = drift;
869    *a_drifterr = drifterr;
870    *a_wait = wait;
871    return now;
872}
873
874
875
876double correct_drift (double *a_when, double *a_offset, double drift) {
877
878/* Correct for the drift since the last time it was done, provided that a long
879enough time has elapsed.  And do remember to kludge up the time and
880discrepancy, when appropriate. */
881
882    double d, x;
883
884    d = current_time(JAN_1970)-*a_when;
885    *a_when += d;
886    x = *a_offset+d*drift;
887    if (verbose > 2)
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);
892        *a_offset = 0.0;
893        return x;
894    } else {
895        if (verbose > 2) fprintf(stderr,"ignored\n");
896        *a_offset = x;
897        return 0.0;
898    }
899}
900
901
902
903void handle_saving (int operation, int *total, int *index, int *cycle,
904    data_record *record, double *previous, double *when, double *correction) {
905
906/* This handles the saving and restoring of the state to a file.  While it is
907subject to spoofing, this is not a major security problem.  But, out of general
908paranoia, check everything in sight when restoring.  Note that this function
909has no external effect if something goes wrong. */
910
911    struct {
912        data_record record[COUNT_MAX];
913        double previous, when, correction;
914        int operation, delay, count, total, index, cycle, waiting;
915    } buffer;
916    double x, y;
917    int i, j;
918
919    if (savefile == NULL) return;
920
921/* Read the restart file and print its data in diagnostic mode.  Note that some
922care is necessary to avoid introducing a security exposure - but we trust the
923C library not to trash the stack on bad numbers! */
924
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);
929            else if (verbose)
930                fprintf(stderr,"%s: bad daemon restart information\n",argv0);
931            return;
932        }
933        if (verbose > 2) {
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)
941                    fprintf(stderr,
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);
946        }
947
948
949/* Start checking the data for sanity. */
950
951        if (buffer.operation == 0 && buffer.delay == 0 && buffer.count == 0) {
952            if (operation < 0)
953                fatal(0,"the daemon save file has been cleared",NULL);
954            if (verbose)
955                fprintf(stderr,"%s: restarting from a cleared file\n",argv0);
956            return;
957        }
958        if (operation == save_read_check) {
959            if (buffer.operation != operation || buffer.delay != delay ||
960                    buffer.count != count) {
961                if (verbose)
962                    fprintf(stderr,"%s: different parameters for restart\n",
963                        argv0);
964                return;
965            }
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) {
973                if (verbose)
974                    fprintf(stderr,"%s: corrupted restart information\n",argv0);
975                return;
976            }
977
978/* Checking the record is even more tedious. */
979
980            x = *when;
981            y = 0.0;
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) {
991                    if (verbose)
992                        fprintf(stderr,"%s: corrupted restart record\n",argv0);
993                    return;
994                }
995                if (buffer.record[i].when < x) x = buffer.record[i].when;
996                if (buffer.record[i].when > y) y = buffer.record[i].when;
997            }
998
999/* Check for consistency and, finally, whether this is too old. */
1000
1001            if (y > buffer.when || y-x < (buffer.total-1)*delay ||
1002                    y-x > (buffer.total-1)*count*delay) {
1003                if (verbose)
1004                    fprintf(stderr,"%s: corrupted restart times\n",argv0);
1005                return;
1006            }
1007            if (buffer.when < *when-count*delay) {
1008                if (verbose)
1009                    fprintf(stderr,"%s: restart information too old\n",argv0);
1010                return;
1011            }
1012        }
1013
1014/* If we get here, just copy the data back. */
1015
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));
1025
1026/* Print out the data if requested. */
1027
1028        if (verbose > 1) {
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);
1037                else
1038                    fprintf(stderr,"\n");
1039            }
1040        }
1041
1042/* All errors on output are fatal. */
1043
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);
1060        if (verbose > 2) {
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)
1067                    fprintf(stderr,
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);
1071        }
1072
1073/* Clearing the save file is similar. */
1074
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);
1080    } else
1081        fatal(0,"internal error in handle_saving",NULL);
1082}
1083
1084
1085
1086void query_savefile (void) {
1087
1088/* This queries a daemon save file. */
1089
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;
1094    char text[100];
1095
1096/* This is a few lines stripped out of run_daemon() and slightly hacked. */
1097
1098    previous = when = current_time(JAN_1970);
1099    if (verbose > 2) {
1100        format_time(text,50,0.0,-1.0,0.0,-1.0,-10);
1101        fprintf(stderr,"Started=%.6f %s\n",when,text);
1102    }
1103    handle_saving(save_read_only,&total,&index,&cycle,record,&previous,&when,
1104        &correction);
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");
1111    exit(EXIT_SUCCESS);
1112}
1113
1114
1115
1116void run_daemon (char *hostnames[], int nhosts, int initial) {
1117
1118/* This does not adjust the time between calls to the server, but it does
1119adjust the time between clock resets.  This function will survive short periods
1120of server inaccessibility or network glitches, but not long ones, and will then
1121need restarting manually.
1122
1123It is far too complex for a single function, but could really only be
1124simplified by making most of its variables global or by a similarly horrible
1125trick.  Oh, for nested scopes as in Algol 68! */
1126
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];
1135    ntp_data data;
1136    char text[100];
1137
1138/* After initialising, restore from a previous run if possible.  Note that
1139only a few of the variables are actually needed to control the operation and
1140the rest are mainly for diagnostics. */
1141
1142    started = previous = when = current_time(JAN_1970);
1143    if (verbose > 2) {
1144        format_time(text,50,0.0,-1.0,0.0,-1.0,-10);
1145        fprintf(stderr,"Started=%.6f %s\n",when,text);
1146    }
1147    if (initial) {
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");
1153            retry = 0;
1154        }
1155        if (verbose > 2)
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) {
1160            set_lock(1);
1161            locked = 1;
1162        }
1163    }
1164    dispersion = 0.0;
1165    attempts = 0;
1166    for (i = 0; i < count; ++i) history[i] = 0.0;
1167    while (1) {
1168
1169/* Print out a reasonable amount of diagnostics, rather like a server.  Note
1170that it may take a little time, but shouldn't affect the estimates much.  Then
1171check that we aren't in a failing loop. */
1172
1173        if (verbose > 2) fprintf(stderr,"item=%d rej=%d\n",item,rej_level);
1174        x = current_time(JAN_1970)-started;
1175        if (verbose &&
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));
1180            if (i > 0)
1181                fprintf(stderr,"%s: after %d hours %d mins ",argv0,i,j);
1182            else if (j > 0)
1183                fprintf(stderr,"%s: after %d mins %.0f secs ",argv0,j,x);
1184            else
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);
1193            maxoff = 0.0;
1194        }
1195        if (current_time(JAN_1970)-previous > count*delay) {
1196            if (verbose)
1197                fprintf(stderr,"%s: no packets in too long a period\n",argv0);
1198            return;
1199        }
1200
1201/* Listen for the next broadcast packet.  This allows up to ETHERNET_MAX
1202replications per packet, for systems with multiple addresses for receiving
1203broadcasts; the only reason for a limit is to protect against broken NTP
1204servers always returning the same time. */
1205
1206        if (operation == op_listen) {
1207            flushes += flush_socket(0);
1208            if (read_packet(0,&data,&offset,&error)) {
1209                ++rejects;
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);
1216                }
1217                continue;
1218            }
1219            if ((rej_level -= (count < 5 ? count : 5)) < 0) rej_level = 0;
1220            x = data.transmit;
1221            for (i = 0; i < count; ++i)
1222                if (x == history[i]) {
1223                    ++replicates;
1224                    if (++rep_level > ETHERNET_MAX)
1225                        fatal(0,"too many replicated packets",NULL);
1226                    goto continue1;
1227                }
1228            rep_level = 0;
1229            history[item] = x;
1230            if (++item >= count) item = 0;
1231
1232/* Accept a packet only after a long enough period has elapsed. */
1233
1234            when = data.current;
1235            if (! retry && when < previous+delay) {
1236                if (verbose > 2) fprintf(stderr,"Skipping too recent packet\n");
1237                ++skips;
1238                continue;
1239            }
1240            retry = 0;
1241            if (verbose > 2)
1242                fprintf(stderr,"Offset=%.6f @ %.6f disp=%.6f\n",
1243                    offset,when,dispersion);
1244
1245/* Handle the client/server model.  It keeps a record of transmitted times,
1246mainly out of paranoia.  The waiting time is kludged up to attempt to provide
1247reasonable resilience against both lost packets and dead servers.  But it
1248won't handle much of either, and will stop after a while, needing manual
1249restarting.  Running it under cron is the best approach. */
1250
1251        } else {
1252            if (! retry) {
1253               if (verbose > 2) fprintf(stderr,"Sleeping for %d\n",waiting);
1254               do_nothing(waiting);
1255            }
1256            make_packet(&data,NTP_CLIENT);
1257            outgoing[item] = data.transmit;
1258            if (++item >= 2*count) item = 0;
1259            if (attempts < 2*count) ++attempts;
1260            if (verbose > 2) {
1261                fprintf(stderr,"Outgoing packet on socket %d:\n",cycle);
1262                display_data(&data);
1263            }
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);
1268
1269/* Read the packet and check that it is an appropriate response.  Because this
1270is rather more numerically sensitive than simple resynchronisation, reject all
1271very inaccurate packets.  Be careful if you modify this, because the error
1272handling is rather nasty to avoid replicating code. */
1273
1274            k = read_packet(cycle,&data,&offset,&error);
1275            if (++cycle >= nhosts) cycle = 0;
1276            if (! k)
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);
1282            }
1283            if (! k && ! retry && when < previous+delay-2) {
1284                if (verbose)
1285                    fprintf(stderr,"%s: packets out of order on socket %d\n",
1286                        argv0,cycle);
1287                k = 1;
1288            }
1289            if (! k && data.current-data.originate > maxerr) {
1290                if (verbose)
1291                    fprintf(stderr,
1292                        "%s: very slow response rejected on socket %d\n",
1293                        argv0,cycle);
1294                k = 1;
1295            }
1296
1297/* Count the number of rejected packets and fail if there are too many. */
1298
1299            if (k) {
1300                ++rejects;
1301                if (++rej_level > count)
1302                    fatal(0,"too many bad or lost packets",NULL);
1303                else {
1304                    retry = 1;
1305                    continue;
1306                }
1307            } else
1308                retry = 0;
1309            if ((rej_level -= (count < 5 ? count : 5)) < 0) rej_level = 0;
1310            if (verbose > 2)
1311                fprintf(stderr,"Offset=%.6f+/-%.6f @ %.6f disp=%.6f\n",
1312                    offset,error,when,dispersion);
1313        }
1314
1315/* Calculate the statistics, and display the results or make the initial
1316correction.  Note that estimate_stats() will return zero if a timestamp
1317indicates synchronisation loss (usually due to down time or a change of server,
1318somewhere upstream), and that the recovery operation is unstructured, so great
1319care should be taken when modifying it.  Also, we want to clear the saved state
1320is the statistics are bad. */
1321
1322        handle_saving(save_clear,&total,&index,&cycle,record,&previous,&when,
1323            &correction);
1324        ++accepts;
1325        dispersion = data.dispersion;
1326        previous = when =
1327            estimate_stats(&total,&index,record,correction,&dispersion,
1328                &when,&offset,&error,&drift,&drifterr,&waiting,1);
1329        if (verbose > 2) {
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);
1333        }
1334        if (when == 0.0) return;
1335        x = (maxoff < 0.0 ? -maxoff : maxoff);
1336        if ((offset < 0.0 ? -offset : offset) > x) maxoff = offset;
1337        correction = 0.0;
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);
1342            } else {
1343                x = reset_clock(offset,error,1);
1344                correction += x;
1345                offset -= x;
1346            }
1347        } else
1348            waiting = delay;
1349        handle_saving(save_write,&total,&index,&cycle,record,&previous,&when,
1350            &correction);
1351
1352/* Now correct the clock for a while, before getting another packet and
1353updating the statistics. */
1354
1355        while (when < previous+delay-waiting) {
1356            do_nothing(waiting);
1357            if (action == action_display)
1358                when += waiting;
1359            else {
1360                correction += correct_drift(&when,&offset,drift);
1361                handle_saving(save_write,&total,&index,&cycle,record,
1362                    &previous,&when,&correction);
1363            }
1364        }
1365continue1: ;
1366    }
1367}
1368
1369
1370
1371void run_client (char *hostnames[], int nhosts) {
1372
1373/* Get enough responses to do something with; or not, as the case may be.  Note
1374that it allows for half of the packets to be bad, so may make up to twice as
1375many attempts as specified by the -c value.  The deadline checking is merely
1376paranoia, to protect against broken signal handling - it cannot easily be
1377triggered if the signal handling works. */
1378
1379    double history[COUNT_MAX], guesses[COUNT_MAX], offset, error, deadline,
1380        a, b, x, y;
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];
1384    ntp_data data;
1385    char text[100];
1386
1387    if (verbose > 2) {
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);
1390    }
1391    for (k = 0; k < nhosts; ++k) open_socket(k,hostnames[k],delay);
1392    if (action != action_display) {
1393        set_lock(1);
1394        locked = 1;
1395    }
1396    attempts = 0;
1397    deadline = current_time(JAN_1970)+delay;
1398
1399/* Listen to broadcast packets and select the best (i.e. earliest).  This will
1400be sensitive to a bad NTP broadcaster, but I believe such things are very rare
1401in practice.  In any case, if you have one, it is probably the only one on your
1402subnet, so you are knackered!  This allows up to ETHERNET_MAX replications per
1403packet, for systems with multiple addresses for receiving broadcasts; the only
1404reason for a limit is to protect against broken NTP servers always returning
1405the same time. */
1406
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);
1415                else
1416                    continue;
1417            } else {
1418                a = data.transmit;
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);
1423                        goto continue1;
1424                    }
1425                history[accepts] = a;
1426		precs[accepts] = data.precision;
1427                guesses[accepts++] = x;
1428            }
1429            if (verbose > 2)
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);
1434
1435/* Note that bubblesort IS a good method for this amount of data.  */
1436
1437            for (k = accepts-2; k >= 0; --k)
1438                if (guesses[k] < guesses[k+1])
1439                    break;
1440                else {
1441                    x = guesses[k];
1442                    guesses[k] = guesses[k+1];
1443                    guesses[k+1] = x;
1444		    precision = precs[k];
1445		    precs[k] = precs[k+1];
1446		    precs[k+1] = precision;
1447                }
1448continue1:  ;
1449        }
1450        offset = guesses[0];
1451	precision = precs[0];
1452        error = minerr+guesses[count <= 5 ? count-1 : 5]-offset;
1453        if (verbose > 2)
1454            fprintf(stderr,"accepts=%d rejects=%d flushes=%d replicates=%d\n",
1455                accepts,rejects,flushes,replicates);
1456
1457/* Handle the client/server model.  It keeps a record of transmitted times,
1458mainly out of paranoia. */
1459
1460    } else {
1461        offset = 0.0;
1462	precision = 0;
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;
1470            if (verbose > 2) {
1471                fprintf(stderr,"Outgoing packet on socket %d:\n",cycle);
1472                display_data(&data);
1473            }
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);
1481                else
1482                    continue;
1483            } else
1484                ++accepts;
1485            if (++cycle >= nhosts) cycle = 0;
1486
1487/* Work out the most accurate time, and check that it isn't more accurate than
1488the results warrant. */
1489
1490            if (verbose > 2)
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;
1497            b = error+y;
1498            if (y < error) {
1499                offset = x;
1500                error = y;
1501		precision = data.precision;
1502            }
1503            if (verbose > 2)
1504                fprintf(stderr,"best=%.6f+/-%.6f\n",offset,error);
1505            if (a > b) {
1506                sprintf(text,"%d",cycle);
1507                fatal(0,"inconsistent times got from NTP server on socket %s",
1508                    text);
1509            }
1510            if (error <= minerr) break;
1511        }
1512        if (verbose > 2)
1513            fprintf(stderr,"accepts=%d rejects=%d flushes=%d\n",
1514                accepts,rejects,flushes);
1515    }
1516
1517/* Tidy up the socket, issues diagnostics and perform the action. */
1518
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);
1523    if (verbose > 2)
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);
1529    } else
1530        (void)reset_clock(offset,error,0);
1531    if (locked) set_lock(0);
1532    if (verbose > 2) fprintf(stderr,"Stopped normally\n");
1533    exit(EXIT_SUCCESS);
1534}
1535
1536
1537
1538int main (int argc, char *argv[]) {
1539
1540/* This is the entry point and all that.  It decodes the arguments and calls
1541one of the specialised routines to do the work. */
1542
1543    char *hostnames[MAX_SOCKETS], *savename = NULL;
1544    int daemon = 0, nhosts = 0, help = 0, args = argc-1, k;
1545    char c;
1546
1547    if (argv[0] == NULL || argv[0][0] == '\0')
1548        argv0 = "sntp";
1549    else if ((argv0 = strrchr(argv[0],'/')) != NULL)
1550        ++argv0;
1551    else
1552        argv0 = argv[0];
1553
1554    setvbuf(stdout,NULL,_IOLBF,BUFSIZ);
1555    setvbuf(stderr,NULL,_IOLBF,BUFSIZ);
1556
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;
1561
1562/* Decode the arguments. */
1563
1564    while (argc > 1) {
1565        k = 1;
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)
1571            ++unprivport;
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) {
1579            lockname = argv[2];
1580            k = 2;
1581        } else if ((strcmp(argv[1],"-x") == 0) &&
1582                daemon == 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]);
1586                k = 2;
1587            } else
1588                daemon = 300;
1589        } else if (strcmp(argv[1],"-f") == 0 && savename == NULL && argc > 2) {
1590            savename = argv[2];
1591            k = 2;
1592        } else if ((strcmp(argv[1],"--help") == 0 ||
1593                    strcmp(argv[1],"-h") == 0 || strcmp(argv[1],"-?") == 0) &&
1594                help == 0)
1595            help = 1;
1596        else if (strcmp(argv[1],"-v") == 0 && verbose == 0)
1597            verbose = 1;
1598        else if (strcmp(argv[1],"-V") == 0 && verbose == 0)
1599            verbose = 2;
1600        else if (strcmp(argv[1],"-W") == 0 && verbose == 0)
1601            verbose = 3;
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");
1606            k = 2;
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");
1611            k = 2;
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;
1615            else {
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");
1619            }
1620            k = 2;
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");
1625            k = 2;
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");
1630            k = 2;
1631        } else
1632            break;
1633        argc -= k;
1634        argv += k;
1635    }
1636
1637/* Check the arguments for consistency and set the defaults. */
1638
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)
1642            syntax(1);
1643    } else {
1644        if (argc < 1 || argc > MAX_SOCKETS || (daemon != 0 && delay != 0))
1645            syntax(1);
1646        if ((prompt || lockname != NULL) &&
1647                action != action_reset && action != action_adjust)
1648            syntax(1);
1649        if (count > 0 && count < argc-1)
1650            fatal(0,"-c value less than number of addresses",NULL);
1651       if (argc > 1) {
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];
1657            }
1658            nhosts = argc-1;
1659        } else {
1660            operation = op_listen;
1661            nhosts = 0;
1662        }
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) &&
1670                lockname == NULL)
1671            lockname = LOCKNAME;
1672
1673/* The '-x' option changes the implications of many other settings, though this
1674is not usually apparent to the caller.  Most of the time delays are to ensure
1675that stuck states terminate, and do not affect the result. */
1676
1677        if (daemon != 0) {
1678            if (minerr >= maxerr || maxerr >= daemon)
1679                fatal(0,"values not in order -e < -E < -x",NULL);
1680            waiting = delay = daemon *= 60;
1681        } else {
1682            if (savename != NULL)
1683                fatal(0,"-f can be specified only with -x",NULL);
1684            if (delay == 0)
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);
1690            } else {
1691                if (minerr >= maxerr || maxerr >= delay)
1692                    fatal(0,"values not in order -e < -E < -d",NULL);
1693            }
1694            if (2*count >= delay) fatal(0,"-c must be less than half -d",NULL);
1695            waiting = delay/count;
1696        }
1697        if (prompt == 0.0) prompt = 30.0;
1698    }
1699    if ((daemon || action == action_query) && savename == NULL)
1700        savename = SAVENAME;
1701
1702/* Diagnose where we are, if requested, and separate out the classes of
1703operation.  The calls do not return. */
1704
1705    if (help) syntax(args == 1);
1706    if (verbose) {
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");
1716    }
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);
1723        query_savefile();
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);
1731    } else
1732        run_client(hostnames,nhosts);
1733    fatal(0,"internal error at end of main",NULL);
1734    return EXIT_FAILURE;
1735}
1736