2 * ntp_util.c - stuff I didn't have any other place for
9 #include "ntp_unixtime.h"
10 #include "ntp_filegen.h"
12 #include "ntp_stdlib.h"
13 #include "ntp_assert.h"
14 #include "ntp_calendar.h"
15 #include "ntp_leapsec.h"
16 #include "lib_strbuf.h"
20 #include <sys/types.h>
21 #ifdef HAVE_SYS_IOCTL_H
22 # include <sys/ioctl.h>
41 * Defines used by the leapseconds stuff
43 #define MAX_TAI 100 /* max TAI offset (s) */
44 #define L_DAY 86400UL /* seconds per day */
45 #define L_YEAR (L_DAY * 365) /* days per year */
46 #define L_LYEAR (L_YEAR + L_DAY) /* days per leap year */
47 #define L_4YEAR (L_LYEAR + 3 * L_YEAR) /* days per leap cycle */
48 #define L_CENT (L_4YEAR * 25) /* days per century */
51 * This contains odds and ends, including the hourly stats, various
52 * configuration items, leapseconds stuff, etc.
57 static char *key_file_name; /* keys file name */
58 static char *leapfile_name; /* leapseconds file name */
59 static struct stat leapfile_stat; /* leapseconds file stat() buffer */
60 static int /*BOOL*/have_leapfile = FALSE;
61 static int /*BOOL*/chck_leaphash = TRUE;
62 char *stats_drift_file; /* frequency file name */
63 static char *stats_temp_file; /* temp frequency file name */
64 static double wander_resid; /* last frequency update */
65 double wander_threshold = 1e-7; /* initial frequency threshold */
68 * Statistics file stuff
72 # define NTP_VAR "/var/NTP/" /* NOTE the trailing '/' */
74 # define NTP_VAR "c:\\var\\ntp\\" /* NOTE the trailing '\\' */
75 # endif /* SYS_WINNT */
79 char statsdir[MAXFILENAME] = NTP_VAR;
80 static FILEGEN peerstats;
81 static FILEGEN loopstats;
82 static FILEGEN clockstats;
83 static FILEGEN rawstats;
84 static FILEGEN sysstats;
85 static FILEGEN protostats;
86 static FILEGEN cryptostats;
87 static FILEGEN timingstats;
90 * This controls whether stats are written to the fileset. Provided
91 * so that ntpdc can turn off stats when the file system fills up.
96 * Last frequency written to file.
98 static double prev_drift_comp; /* last frequency update */
101 * Function prototypes
103 static void record_sys_stats(void);
104 void ntpd_time_stepped(void);
105 static void check_leap_expiration(int, uint32_t, const time_t*);
111 void uninit_util(void);
115 * uninit_util - free memory allocated by init_util
121 #if defined(_MSC_VER) && defined (_DEBUG)
124 if (stats_drift_file) {
125 free(stats_drift_file);
126 free(stats_temp_file);
127 stats_drift_file = NULL;
128 stats_temp_file = NULL;
132 key_file_name = NULL;
134 filegen_unregister("peerstats");
135 filegen_unregister("loopstats");
136 filegen_unregister("clockstats");
137 filegen_unregister("rawstats");
138 filegen_unregister("sysstats");
139 filegen_unregister("protostats");
141 filegen_unregister("cryptostats");
144 filegen_unregister("timingstats");
145 #endif /* DEBUG_TIMING */
147 #if defined(_MSC_VER) && defined (_DEBUG)
155 * init_util - initialize the util module of ntpd
160 filegen_register(statsdir, "peerstats", &peerstats);
161 filegen_register(statsdir, "loopstats", &loopstats);
162 filegen_register(statsdir, "clockstats", &clockstats);
163 filegen_register(statsdir, "rawstats", &rawstats);
164 filegen_register(statsdir, "sysstats", &sysstats);
165 filegen_register(statsdir, "protostats", &protostats);
166 filegen_register(statsdir, "cryptostats", &cryptostats);
167 filegen_register(statsdir, "timingstats", &timingstats);
169 * register with libntp ntp_set_tod() to call us back
170 * when time is stepped.
172 step_callback = &ntpd_time_stepped;
174 atexit(&uninit_util);
180 * hourly_stats - print some interesting stats
197 * Sometimes having a Sun can be a drag.
199 * The kernel variable dosynctodr controls whether the system's
200 * soft clock is kept in sync with the battery clock. If it
201 * is zero, then the soft clock is not synced, and the battery
202 * clock is simply left to rot. That means that when the system
203 * reboots, the battery clock (which has probably gone wacky)
204 * sets the soft clock. That means ntpd starts off with a very
205 * confused idea of what time it is. It then takes a large
206 * amount of time to figure out just how wacky the battery clock
207 * has made things drift, etc, etc. The solution is to make the
208 * battery clock sync up to system time. The way to do THAT is
209 * to simply set the time of day to the current time of day, but
210 * as quickly as possible. This may, or may not be a sensible
213 * CAVEAT: settimeofday() steps the sun clock by about 800 us,
214 * so setting DOSYNCTODR seems a bad idea in the
215 * case of us resolution
220 * (prr) getpriority returns -1 on error, but -1 is also a valid
221 * return value (!), so instead we have to zero errno before the
222 * call and check it for non-zero afterwards.
226 o_prio = getpriority(PRIO_PROCESS,0); /* Save setting */
229 * (prr) if getpriority succeeded, call setpriority to raise
230 * scheduling priority as high as possible. If that succeeds
231 * as well, set the prio_set flag so we remember to reset
232 * priority to its previous value below. Note that on Solaris
233 * 2.6 (and beyond?), both getpriority and setpriority will fail
234 * with ESRCH, because sched_setscheduler (called from main) put
235 * us in the real-time scheduling class which setpriority
236 * doesn't know about. Being in the real-time class is better
237 * than anything setpriority can do, anyhow, so this error is
240 if ((errno == 0) && (setpriority(PRIO_PROCESS,0,-20) == 0))
241 prio_set = 1; /* overdrive */
244 (void) getclock(TIMEOFDAY, &ts);
245 tv.tv_sec = ts.tv_sec;
246 tv.tv_usec = ts.tv_nsec / 1000;
247 #else /* not HAVE_GETCLOCK */
248 GETTIMEOFDAY(&tv,(struct timezone *)NULL);
249 #endif /* not HAVE_GETCLOCK */
250 if (ntp_set_tod(&tv,(struct timezone *)NULL) != 0)
251 msyslog(LOG_ERR, "can't sync battery time: %m");
254 setpriority(PRIO_PROCESS, 0, o_prio); /* downshift */
256 #endif /* DOSYNCTODR */
258 if (stats_drift_file != 0) {
261 * When the frequency file is written, initialize the
262 * prev_drift_comp and wander_resid. Thereafter,
263 * reduce the wander_resid by half each hour. When
264 * the difference between the prev_drift_comp and
265 * drift_comp is less than the wander_resid, update
266 * the frequncy file. This minimizes the file writes to
267 * nonvolaile storage.
271 printf("write_stats: frequency %.6lf thresh %.6lf, freq %.6lf\n",
272 (prev_drift_comp - drift_comp) * 1e6, wander_resid *
273 1e6, drift_comp * 1e6);
275 if (fabs(prev_drift_comp - drift_comp) < wander_resid) {
279 prev_drift_comp = drift_comp;
280 wander_resid = wander_threshold;
281 if ((fp = fopen(stats_temp_file, "w")) == NULL) {
282 msyslog(LOG_ERR, "frequency file %s: %m",
286 fprintf(fp, "%.3f\n", drift_comp * 1e6);
290 if (_unlink(stats_drift_file)) /* rename semantics differ under NT */
292 "Unable to remove prior drift file %s, %m",
294 #endif /* SYS_WINNT */
297 if (rename(stats_temp_file, stats_drift_file))
299 "Unable to rename temp drift file %s to %s, %m",
300 stats_temp_file, stats_drift_file);
302 /* we have no rename NFS of ftp in use */
303 if ((fp = fopen(stats_drift_file, "w")) ==
306 "frequency file %s: %m",
315 $DESCRIPTOR(oldvers,";-1");
316 struct dsc$descriptor driftdsc = {
317 strlen(stats_drift_file), 0, 0,
319 while(lib$delete_file(&oldvers,
328 * stats_config - configure the stats operation
333 const char *invalue, /* only one type so far */
344 const char temp_ext[] = ".TEMP";
346 const char temp_ext[] = "-TEMP";
350 * Expand environment strings under Windows NT, since the
351 * command interpreter doesn't do this, the program must.
354 char newvalue[MAX_PATH], parameter[MAX_PATH];
356 if (!ExpandEnvironmentStrings(invalue, newvalue, MAX_PATH)) {
358 case STATS_FREQ_FILE:
359 strlcpy(parameter, "STATS_FREQ_FILE",
363 case STATS_LEAP_FILE:
364 strlcpy(parameter, "STATS_LEAP_FILE",
369 strlcpy(parameter, "STATS_STATSDIR",
374 strlcpy(parameter, "STATS_PID_FILE",
379 strlcpy(parameter, "UNKNOWN",
385 "ExpandEnvironmentStrings(%s) failed: %m\n",
392 #endif /* SYS_WINNT */
397 * Open and read frequency file.
399 case STATS_FREQ_FILE:
400 if (!value || (len = strlen(value)) == 0)
403 stats_drift_file = erealloc(stats_drift_file, len + 1);
404 stats_temp_file = erealloc(stats_temp_file,
405 len + sizeof(".TEMP"));
406 memcpy(stats_drift_file, value, (size_t)(len+1));
407 memcpy(stats_temp_file, value, (size_t)len);
408 memcpy(stats_temp_file + len, temp_ext, sizeof(temp_ext));
411 * Open drift file and read frequency. If the file is
412 * missing or contains errors, tell the loop to reset.
414 if ((fp = fopen(stats_drift_file, "r")) == NULL)
417 if (fscanf(fp, "%lf", &old_drift) != 1) {
419 "format error frequency file %s",
426 loop_config(LOOP_FREQ, old_drift);
427 prev_drift_comp = drift_comp;
431 * Specify statistics directory.
435 /* - 1 since value may be missing the DIR_SEP. */
436 if (strlen(value) >= sizeof(statsdir) - 1) {
438 "statsdir too long (>%d, sigh)",
439 (int)sizeof(statsdir) - 2);
444 /* Add a DIR_SEP unless we already have one. */
445 value_l = strlen(value);
449 add_dir_sep = (DIR_SEP !=
453 snprintf(statsdir, sizeof(statsdir),
454 "%s%c", value, DIR_SEP);
456 snprintf(statsdir, sizeof(statsdir),
466 if ((fp = fopen(value, "w")) == NULL) {
467 msyslog(LOG_ERR, "pid file %s: %m",
471 fprintf(fp, "%d", (int)getpid());
476 * Read leapseconds file.
478 * Note: Currently a leap file without SHA1 signature is
479 * accepted, but if there is a signature line, the signature
480 * must be valid or the file is rejected.
482 case STATS_LEAP_FILE:
483 if (!value || (len = strlen(value)) == 0)
486 leapfile_name = erealloc(leapfile_name, len + 1);
487 memcpy(leapfile_name, value, len + 1);
488 chck_leaphash = optflag;
490 if (leapsec_load_file(
491 leapfile_name, &leapfile_stat,
492 TRUE, TRUE, chck_leaphash))
494 leap_signature_t lsig;
498 leapsec_getsig(&lsig);
499 mprintf_event(EVNT_TAI, NULL,
503 leapsec_expired(now.l_ui, NULL)
506 fstostr(lsig.etime));
508 have_leapfile = TRUE;
510 /* force an immediate daily expiration check of
511 * the leap seconds table
513 check_leap_expiration(TRUE, now.l_ui, &ttnow);
525 * record_peer_stats - write peer statistics to file
529 * time (s past UTC midnight)
541 double offset, /* offset */
542 double delay, /* delay */
543 double dispersion, /* dispersion */
544 double jitter /* jitter */
554 filegen_setup(&peerstats, now.l_ui);
555 day = now.l_ui / 86400 + MJD_1900;
557 if (peerstats.fp != NULL) {
558 fprintf(peerstats.fp,
559 "%lu %s %s %x %.9f %.9f %.9f %.9f\n", day,
560 ulfptoa(&now, 3), stoa(addr), status, offset,
561 delay, dispersion, jitter);
562 fflush(peerstats.fp);
568 * record_loop_stats - write loop filter statistics to file
572 * time (s past midnight)
577 * time constant (log2)
581 double offset, /* offset */
582 double freq, /* frequency (PPM) */
583 double jitter, /* jitter */
584 double wander, /* wander (PPM) */
595 filegen_setup(&loopstats, now.l_ui);
596 day = now.l_ui / 86400 + MJD_1900;
598 if (loopstats.fp != NULL) {
599 fprintf(loopstats.fp, "%lu %s %.9f %.3f %.9f %.6f %d\n",
600 day, ulfptoa(&now, 3), offset, freq * 1e6, jitter,
601 wander * 1e6, spoll);
602 fflush(loopstats.fp);
608 * record_clock_stats - write clock statistics to file
612 * time (s past midnight)
619 const char *text /* timecode string */
629 filegen_setup(&clockstats, now.l_ui);
630 day = now.l_ui / 86400 + MJD_1900;
632 if (clockstats.fp != NULL) {
633 fprintf(clockstats.fp, "%lu %s %s %s\n", day,
634 ulfptoa(&now, 3), stoa(addr), text);
635 fflush(clockstats.fp);
641 * mprintf_clock_stats - write clock statistics to file with
642 * msnprintf-style formatting.
656 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
659 record_clock_stats(addr, msg);
665 * record_raw_stats - write raw timestamps to file
669 * time (s past midnight)
672 * t1 t2 t3 t4 timestamps
673 * leap, version, mode, stratum, ppoll, precision, root delay, root dispersion, REFID
674 * length and hex dump of any EFs and any legacy MAC.
680 l_fp *t1, /* originate timestamp */
681 l_fp *t2, /* receive timestamp */
682 l_fp *t3, /* transmit timestamp */
683 l_fp *t4, /* destination timestamp */
690 double root_delay, /* seconds */
691 double root_dispersion,/* seconds */
704 filegen_setup(&rawstats, now.l_ui);
705 day = now.l_ui / 86400 + MJD_1900;
707 if (rawstats.fp != NULL) {
708 fprintf(rawstats.fp, "%lu %s %s %s %s %s %s %s %d %d %d %d %d %d %.6f %.6f %s",
709 day, ulfptoa(&now, 3),
710 srcadr ? stoa(srcadr) : "-",
711 dstadr ? stoa(dstadr) : "-",
712 ulfptoa(t1, 9), ulfptoa(t2, 9),
713 ulfptoa(t3, 9), ulfptoa(t4, 9),
714 leap, version, mode, stratum, ppoll, precision,
715 root_delay, root_dispersion, refid_str(refid, stratum));
719 fprintf(rawstats.fp, " %d: ", len);
720 for (i = 0; i < len; ++i) {
721 fprintf(rawstats.fp, "%02x", extra[i]);
724 fprintf(rawstats.fp, "\n");
731 * record_sys_stats - write system statistics to file
735 * time (s past midnight)
738 * packets for this host
742 * bad length or format
749 record_sys_stats(void)
758 filegen_setup(&sysstats, now.l_ui);
759 day = now.l_ui / 86400 + MJD_1900;
761 if (sysstats.fp != NULL) {
763 "%lu %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
764 day, ulfptoa(&now, 3), current_time - sys_stattime,
765 sys_received, sys_processed, sys_newversion,
766 sys_oldversion, sys_restricted, sys_badlength,
767 sys_badauth, sys_declined, sys_limitrejected,
776 * record_proto_stats - write system statistics to file
780 * time (s past midnight)
785 char *str /* text string */
795 filegen_setup(&protostats, now.l_ui);
796 day = now.l_ui / 86400 + MJD_1900;
798 if (protostats.fp != NULL) {
799 fprintf(protostats.fp, "%lu %s %s\n", day,
800 ulfptoa(&now, 3), str);
801 fflush(protostats.fp);
808 * record_crypto_stats - write crypto statistics to file
812 * time (s past midnight)
819 const char *text /* text message */
829 filegen_setup(&cryptostats, now.l_ui);
830 day = now.l_ui / 86400 + MJD_1900;
832 if (cryptostats.fp != NULL) {
834 fprintf(cryptostats.fp, "%lu %s 0.0.0.0 %s\n",
835 day, ulfptoa(&now, 3), text);
837 fprintf(cryptostats.fp, "%lu %s %s %s\n",
838 day, ulfptoa(&now, 3), stoa(addr), text);
839 fflush(cryptostats.fp);
847 * record_timing_stats - write timing statistics to file
851 * time (s past midnight)
856 const char *text /* text message */
859 static unsigned int flshcnt;
867 filegen_setup(&timingstats, now.l_ui);
868 day = now.l_ui / 86400 + MJD_1900;
870 if (timingstats.fp != NULL) {
871 fprintf(timingstats.fp, "%lu %s %s\n", day, lfptoa(&now,
873 if (++flshcnt % 100 == 0)
874 fflush(timingstats.fp);
881 * check_leap_file - See if the leapseconds file has been updated.
885 * Note: This loads a new leapfile on the fly. Currently a leap file
886 * without SHA1 signature is accepted, but if there is a signature line,
887 * the signature must be valid or the file is rejected.
893 const time_t *systime
896 /* just do nothing if there is no leap file */
897 if ( ! (leapfile_name && *leapfile_name))
900 /* try to load leapfile, force it if no leapfile loaded yet */
901 if (leapsec_load_file(
902 leapfile_name, &leapfile_stat,
903 !have_leapfile, is_daily_check, chck_leaphash))
904 have_leapfile = TRUE;
905 else if (!have_leapfile)
908 check_leap_expiration(is_daily_check, ntptime, systime);
912 * check expiration of a loaded leap table
915 check_leap_expiration(
918 const time_t *systime
921 static const char * const logPrefix = "leapsecond file";
924 /* test the expiration of the leap data and log with proper
925 * level and frequency (once/hour or once/day, depending on the
928 rc = leapsec_daystolive(ntptime, systime);
931 "%s ('%s'): will expire in less than one day",
932 logPrefix, leapfile_name);
933 } else if (is_daily_check && rc < 28) {
936 "%s ('%s'): expired %d day%s ago",
937 logPrefix, leapfile_name, -rc, (rc == -1 ? "" : "s"));
940 "%s ('%s'): will expire in less than %d days",
941 logPrefix, leapfile_name, 1+rc);
947 * getauthkeys - read the authentication keys from the specified file
956 len = strlen(keyfile);
961 key_file_name = erealloc(key_file_name, len + 1);
962 memcpy(key_file_name, keyfile, len + 1);
964 key_file_name = erealloc(key_file_name, _MAX_PATH);
965 if (len + 1 > _MAX_PATH)
967 if (!ExpandEnvironmentStrings(keyfile, key_file_name,
970 "ExpandEnvironmentStrings(KEY_FILE) failed: %m");
971 strlcpy(key_file_name, keyfile, _MAX_PATH);
973 key_file_name = erealloc(key_file_name,
974 1 + strlen(key_file_name));
975 #endif /* SYS_WINNT */
977 authreadkeys(key_file_name);
982 * rereadkeys - read the authentication key file over again.
987 if (NULL != key_file_name)
988 authreadkeys(key_file_name);
994 * ntp_exit - document explicitly that ntpd has exited
999 msyslog(LOG_ERR, "EXITING with return code %d", retval);
1005 * fstostr - prettyprint NTP seconds
1015 if (ntpcal_ntp_to_date(&tm, (u_int32)ntp_stamp, NULL) < 0)
1016 snprintf(buf, LIB_BUFLENGTH, "ntpcal_ntp_to_date: %ld: range error",
1019 snprintf(buf, LIB_BUFLENGTH, "%04d%02d%02d%02d%02d",
1020 tm.year, tm.month, tm.monthday,
1021 tm.hour, tm.minute);
1027 * ntpd_time_stepped is called back by step_systime(), allowing ntpd
1028 * to do any one-time processing necessitated by the step.
1031 ntpd_time_stepped(void)
1033 u_int saved_mon_enabled;
1036 * flush the monitor MRU list which contains l_fp timestamps
1037 * which should not be compared across the step.
1039 if (MON_OFF != mon_enabled) {
1040 saved_mon_enabled = mon_enabled;
1042 mon_start(saved_mon_enabled);
1045 /* inform interpolating Windows code to allow time to go back */