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 char *stats_drift_file; /* frequency file name */
62 static char *stats_temp_file; /* temp frequency file name */
63 static double wander_resid; /* last frequency update */
64 double wander_threshold = 1e-7; /* initial frequency threshold */
67 * Statistics file stuff
71 # define NTP_VAR "/var/NTP/" /* NOTE the trailing '/' */
73 # define NTP_VAR "c:\\var\\ntp\\" /* NOTE the trailing '\\' */
74 # endif /* SYS_WINNT */
78 char statsdir[MAXFILENAME] = NTP_VAR;
79 static FILEGEN peerstats;
80 static FILEGEN loopstats;
81 static FILEGEN clockstats;
82 static FILEGEN rawstats;
83 static FILEGEN sysstats;
84 static FILEGEN protostats;
85 static FILEGEN cryptostats;
86 static FILEGEN timingstats;
89 * This controls whether stats are written to the fileset. Provided
90 * so that ntpdc can turn off stats when the file system fills up.
95 * Last frequency written to file.
97 static double prev_drift_comp; /* last frequency update */
100 * Function prototypes
102 static void record_sys_stats(void);
103 void ntpd_time_stepped(void);
104 static void check_leap_expiration(int, uint32_t, const time_t*);
110 void uninit_util(void);
114 * uninit_util - free memory allocated by init_util
120 #if defined(_MSC_VER) && defined (_DEBUG)
123 if (stats_drift_file) {
124 free(stats_drift_file);
125 free(stats_temp_file);
126 stats_drift_file = NULL;
127 stats_temp_file = NULL;
131 key_file_name = NULL;
133 filegen_unregister("peerstats");
134 filegen_unregister("loopstats");
135 filegen_unregister("clockstats");
136 filegen_unregister("rawstats");
137 filegen_unregister("sysstats");
138 filegen_unregister("protostats");
140 filegen_unregister("cryptostats");
143 filegen_unregister("timingstats");
144 #endif /* DEBUG_TIMING */
146 #if defined(_MSC_VER) && defined (_DEBUG)
154 * init_util - initialize the util module of ntpd
159 filegen_register(statsdir, "peerstats", &peerstats);
160 filegen_register(statsdir, "loopstats", &loopstats);
161 filegen_register(statsdir, "clockstats", &clockstats);
162 filegen_register(statsdir, "rawstats", &rawstats);
163 filegen_register(statsdir, "sysstats", &sysstats);
164 filegen_register(statsdir, "protostats", &protostats);
165 filegen_register(statsdir, "cryptostats", &cryptostats);
166 filegen_register(statsdir, "timingstats", &timingstats);
168 * register with libntp ntp_set_tod() to call us back
169 * when time is stepped.
171 step_callback = &ntpd_time_stepped;
173 atexit(&uninit_util);
179 * hourly_stats - print some interesting stats
196 * Sometimes having a Sun can be a drag.
198 * The kernel variable dosynctodr controls whether the system's
199 * soft clock is kept in sync with the battery clock. If it
200 * is zero, then the soft clock is not synced, and the battery
201 * clock is simply left to rot. That means that when the system
202 * reboots, the battery clock (which has probably gone wacky)
203 * sets the soft clock. That means ntpd starts off with a very
204 * confused idea of what time it is. It then takes a large
205 * amount of time to figure out just how wacky the battery clock
206 * has made things drift, etc, etc. The solution is to make the
207 * battery clock sync up to system time. The way to do THAT is
208 * to simply set the time of day to the current time of day, but
209 * as quickly as possible. This may, or may not be a sensible
212 * CAVEAT: settimeofday() steps the sun clock by about 800 us,
213 * so setting DOSYNCTODR seems a bad idea in the
214 * case of us resolution
219 * (prr) getpriority returns -1 on error, but -1 is also a valid
220 * return value (!), so instead we have to zero errno before the
221 * call and check it for non-zero afterwards.
225 o_prio = getpriority(PRIO_PROCESS,0); /* Save setting */
228 * (prr) if getpriority succeeded, call setpriority to raise
229 * scheduling priority as high as possible. If that succeeds
230 * as well, set the prio_set flag so we remember to reset
231 * priority to its previous value below. Note that on Solaris
232 * 2.6 (and beyond?), both getpriority and setpriority will fail
233 * with ESRCH, because sched_setscheduler (called from main) put
234 * us in the real-time scheduling class which setpriority
235 * doesn't know about. Being in the real-time class is better
236 * than anything setpriority can do, anyhow, so this error is
239 if ((errno == 0) && (setpriority(PRIO_PROCESS,0,-20) == 0))
240 prio_set = 1; /* overdrive */
243 (void) getclock(TIMEOFDAY, &ts);
244 tv.tv_sec = ts.tv_sec;
245 tv.tv_usec = ts.tv_nsec / 1000;
246 #else /* not HAVE_GETCLOCK */
247 GETTIMEOFDAY(&tv,(struct timezone *)NULL);
248 #endif /* not HAVE_GETCLOCK */
249 if (ntp_set_tod(&tv,(struct timezone *)NULL) != 0)
250 msyslog(LOG_ERR, "can't sync battery time: %m");
253 setpriority(PRIO_PROCESS, 0, o_prio); /* downshift */
255 #endif /* DOSYNCTODR */
257 if (stats_drift_file != 0) {
260 * When the frequency file is written, initialize the
261 * prev_drift_comp and wander_resid. Thereafter,
262 * reduce the wander_resid by half each hour. When
263 * the difference between the prev_drift_comp and
264 * drift_comp is less than the wander_resid, update
265 * the frequncy file. This minimizes the file writes to
266 * nonvolaile storage.
270 printf("write_stats: frequency %.6lf thresh %.6lf, freq %.6lf\n",
271 (prev_drift_comp - drift_comp) * 1e6, wander_resid *
272 1e6, drift_comp * 1e6);
274 if (fabs(prev_drift_comp - drift_comp) < wander_resid) {
278 prev_drift_comp = drift_comp;
279 wander_resid = wander_threshold;
280 if ((fp = fopen(stats_temp_file, "w")) == NULL) {
281 msyslog(LOG_ERR, "frequency file %s: %m",
285 fprintf(fp, "%.3f\n", drift_comp * 1e6);
289 if (_unlink(stats_drift_file)) /* rename semantics differ under NT */
291 "Unable to remove prior drift file %s, %m",
293 #endif /* SYS_WINNT */
296 if (rename(stats_temp_file, stats_drift_file))
298 "Unable to rename temp drift file %s to %s, %m",
299 stats_temp_file, stats_drift_file);
301 /* we have no rename NFS of ftp in use */
302 if ((fp = fopen(stats_drift_file, "w")) ==
305 "frequency file %s: %m",
314 $DESCRIPTOR(oldvers,";-1");
315 struct dsc$descriptor driftdsc = {
316 strlen(stats_drift_file), 0, 0,
318 while(lib$delete_file(&oldvers,
327 * stats_config - configure the stats operation
332 const char *invalue /* only one type so far */
342 const char temp_ext[] = ".TEMP";
344 const char temp_ext[] = "-TEMP";
348 * Expand environment strings under Windows NT, since the
349 * command interpreter doesn't do this, the program must.
352 char newvalue[MAX_PATH], parameter[MAX_PATH];
354 if (!ExpandEnvironmentStrings(invalue, newvalue, MAX_PATH)) {
356 case STATS_FREQ_FILE:
357 strlcpy(parameter, "STATS_FREQ_FILE",
361 case STATS_LEAP_FILE:
362 strlcpy(parameter, "STATS_LEAP_FILE",
367 strlcpy(parameter, "STATS_STATSDIR",
372 strlcpy(parameter, "STATS_PID_FILE",
377 strlcpy(parameter, "UNKNOWN",
383 "ExpandEnvironmentStrings(%s) failed: %m\n",
390 #endif /* SYS_WINNT */
395 * Open and read frequency file.
397 case STATS_FREQ_FILE:
398 if (!value || (len = strlen(value)) == 0)
401 stats_drift_file = erealloc(stats_drift_file, len + 1);
402 stats_temp_file = erealloc(stats_temp_file,
403 len + sizeof(".TEMP"));
404 memcpy(stats_drift_file, value, (size_t)(len+1));
405 memcpy(stats_temp_file, value, (size_t)len);
406 memcpy(stats_temp_file + len, temp_ext, sizeof(temp_ext));
409 * Open drift file and read frequency. If the file is
410 * missing or contains errors, tell the loop to reset.
412 if ((fp = fopen(stats_drift_file, "r")) == NULL)
415 if (fscanf(fp, "%lf", &old_drift) != 1) {
417 "format error frequency file %s",
424 loop_config(LOOP_FREQ, old_drift);
425 prev_drift_comp = drift_comp;
429 * Specify statistics directory.
433 /* - 1 since value may be missing the DIR_SEP. */
434 if (strlen(value) >= sizeof(statsdir) - 1) {
436 "statsdir too long (>%d, sigh)",
437 (int)sizeof(statsdir) - 2);
442 /* Add a DIR_SEP unless we already have one. */
443 value_l = strlen(value);
447 add_dir_sep = (DIR_SEP !=
451 snprintf(statsdir, sizeof(statsdir),
452 "%s%c", value, DIR_SEP);
454 snprintf(statsdir, sizeof(statsdir),
464 if ((fp = fopen(value, "w")) == NULL) {
465 msyslog(LOG_ERR, "pid file %s: %m",
469 fprintf(fp, "%d", (int)getpid());
474 * Read leapseconds file.
476 * Note: Currently a leap file without SHA1 signature is
477 * accepted, but if there is a signature line, the signature
478 * must be valid or the file is rejected.
480 case STATS_LEAP_FILE:
481 if (!value || (len = strlen(value)) == 0)
484 leapfile_name = erealloc(leapfile_name, len + 1);
485 memcpy(leapfile_name, value, len + 1);
487 if (leapsec_load_file(
488 leapfile_name, &leapfile_stat, TRUE, TRUE))
490 leap_signature_t lsig;
494 leapsec_getsig(&lsig);
495 mprintf_event(EVNT_TAI, NULL,
499 leapsec_expired(now.l_ui, NULL)
502 fstostr(lsig.etime));
504 have_leapfile = TRUE;
506 /* force an immediate daily expiration check of
507 * the leap seconds table
509 check_leap_expiration(TRUE, now.l_ui, &ttnow);
521 * record_peer_stats - write peer statistics to file
525 * time (s past UTC midnight)
537 double offset, /* offset */
538 double delay, /* delay */
539 double dispersion, /* dispersion */
540 double jitter /* jitter */
550 filegen_setup(&peerstats, now.l_ui);
551 day = now.l_ui / 86400 + MJD_1900;
553 if (peerstats.fp != NULL) {
554 fprintf(peerstats.fp,
555 "%lu %s %s %x %.9f %.9f %.9f %.9f\n", day,
556 ulfptoa(&now, 3), stoa(addr), status, offset,
557 delay, dispersion, jitter);
558 fflush(peerstats.fp);
564 * record_loop_stats - write loop filter statistics to file
568 * time (s past midnight)
573 * time constant (log2)
577 double offset, /* offset */
578 double freq, /* frequency (PPM) */
579 double jitter, /* jitter */
580 double wander, /* wander (PPM) */
591 filegen_setup(&loopstats, now.l_ui);
592 day = now.l_ui / 86400 + MJD_1900;
594 if (loopstats.fp != NULL) {
595 fprintf(loopstats.fp, "%lu %s %.9f %.3f %.9f %.6f %d\n",
596 day, ulfptoa(&now, 3), offset, freq * 1e6, jitter,
597 wander * 1e6, spoll);
598 fflush(loopstats.fp);
604 * record_clock_stats - write clock statistics to file
608 * time (s past midnight)
615 const char *text /* timecode string */
625 filegen_setup(&clockstats, now.l_ui);
626 day = now.l_ui / 86400 + MJD_1900;
628 if (clockstats.fp != NULL) {
629 fprintf(clockstats.fp, "%lu %s %s %s\n", day,
630 ulfptoa(&now, 3), stoa(addr), text);
631 fflush(clockstats.fp);
637 * mprintf_clock_stats - write clock statistics to file with
638 * msnprintf-style formatting.
652 rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
655 record_clock_stats(addr, msg);
661 * record_raw_stats - write raw timestamps to file
665 * time (s past midnight)
668 * t1 t2 t3 t4 timestamps
674 l_fp *t1, /* originate timestamp */
675 l_fp *t2, /* receive timestamp */
676 l_fp *t3, /* transmit timestamp */
677 l_fp *t4, /* destination timestamp */
684 double root_delay, /* seconds */
685 double root_dispersion,/* seconds */
696 filegen_setup(&rawstats, now.l_ui);
697 day = now.l_ui / 86400 + MJD_1900;
699 if (rawstats.fp != NULL) {
700 fprintf(rawstats.fp, "%lu %s %s %s %s %s %s %s %d %d %d %d %d %d %.6f %.6f %s\n",
701 day, ulfptoa(&now, 3),
702 stoa(srcadr), dstadr ? stoa(dstadr) : "-",
703 ulfptoa(t1, 9), ulfptoa(t2, 9),
704 ulfptoa(t3, 9), ulfptoa(t4, 9),
705 leap, version, mode, stratum, ppoll, precision,
706 root_delay, root_dispersion, refid_str(refid, stratum));
713 * record_sys_stats - write system statistics to file
717 * time (s past midnight)
720 * packets for this host
724 * bad length or format
731 record_sys_stats(void)
740 filegen_setup(&sysstats, now.l_ui);
741 day = now.l_ui / 86400 + MJD_1900;
743 if (sysstats.fp != NULL) {
745 "%lu %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
746 day, ulfptoa(&now, 3), current_time - sys_stattime,
747 sys_received, sys_processed, sys_newversion,
748 sys_oldversion, sys_restricted, sys_badlength,
749 sys_badauth, sys_declined, sys_limitrejected,
758 * record_proto_stats - write system statistics to file
762 * time (s past midnight)
767 char *str /* text string */
777 filegen_setup(&protostats, now.l_ui);
778 day = now.l_ui / 86400 + MJD_1900;
780 if (protostats.fp != NULL) {
781 fprintf(protostats.fp, "%lu %s %s\n", day,
782 ulfptoa(&now, 3), str);
783 fflush(protostats.fp);
790 * record_crypto_stats - write crypto statistics to file
794 * time (s past midnight)
801 const char *text /* text message */
811 filegen_setup(&cryptostats, now.l_ui);
812 day = now.l_ui / 86400 + MJD_1900;
814 if (cryptostats.fp != NULL) {
816 fprintf(cryptostats.fp, "%lu %s 0.0.0.0 %s\n",
817 day, ulfptoa(&now, 3), text);
819 fprintf(cryptostats.fp, "%lu %s %s %s\n",
820 day, ulfptoa(&now, 3), stoa(addr), text);
821 fflush(cryptostats.fp);
829 * record_timing_stats - write timing statistics to file
833 * time (s past midnight)
838 const char *text /* text message */
841 static unsigned int flshcnt;
849 filegen_setup(&timingstats, now.l_ui);
850 day = now.l_ui / 86400 + MJD_1900;
852 if (timingstats.fp != NULL) {
853 fprintf(timingstats.fp, "%lu %s %s\n", day, lfptoa(&now,
855 if (++flshcnt % 100 == 0)
856 fflush(timingstats.fp);
863 * check_leap_file - See if the leapseconds file has been updated.
867 * Note: This loads a new leapfile on the fly. Currently a leap file
868 * without SHA1 signature is accepted, but if there is a signature line,
869 * the signature must be valid or the file is rejected.
875 const time_t *systime
878 /* just do nothing if there is no leap file */
879 if ( ! (leapfile_name && *leapfile_name))
882 /* try to load leapfile, force it if no leapfile loaded yet */
883 if (leapsec_load_file(
884 leapfile_name, &leapfile_stat,
885 !have_leapfile, is_daily_check))
886 have_leapfile = TRUE;
887 else if (!have_leapfile)
890 check_leap_expiration(is_daily_check, ntptime, systime);
894 * check expiration of a loaded leap table
897 check_leap_expiration(
900 const time_t *systime
903 static const char * const logPrefix = "leapsecond file";
906 /* test the expiration of the leap data and log with proper
907 * level and frequency (once/hour or once/day, depending on the
910 rc = leapsec_daystolive(ntptime, systime);
913 "%s ('%s'): will expire in less than one day",
914 logPrefix, leapfile_name);
915 } else if (is_daily_check && rc < 28) {
918 "%s ('%s'): expired less than %d day%s ago",
919 logPrefix, leapfile_name, -rc, (rc == -1 ? "" : "s"));
922 "%s ('%s'): will expire in less than %d days",
923 logPrefix, leapfile_name, 1+rc);
929 * getauthkeys - read the authentication keys from the specified file
938 len = strlen(keyfile);
943 key_file_name = erealloc(key_file_name, len + 1);
944 memcpy(key_file_name, keyfile, len + 1);
946 key_file_name = erealloc(key_file_name, _MAX_PATH);
947 if (len + 1 > _MAX_PATH)
949 if (!ExpandEnvironmentStrings(keyfile, key_file_name,
952 "ExpandEnvironmentStrings(KEY_FILE) failed: %m");
953 strlcpy(key_file_name, keyfile, _MAX_PATH);
955 key_file_name = erealloc(key_file_name,
956 1 + strlen(key_file_name));
957 #endif /* SYS_WINNT */
959 authreadkeys(key_file_name);
964 * rereadkeys - read the authentication key file over again.
969 if (NULL != key_file_name)
970 authreadkeys(key_file_name);
976 * ntp_exit - document explicitly that ntpd has exited
981 msyslog(LOG_ERR, "EXITING with return code %d", retval);
987 * fstostr - prettyprint NTP seconds
997 if (ntpcal_ntp_to_date(&tm, (u_int32)ntp_stamp, NULL) < 0)
998 snprintf(buf, LIB_BUFLENGTH, "ntpcal_ntp_to_date: %ld: range error",
1001 snprintf(buf, LIB_BUFLENGTH, "%04d%02d%02d%02d%02d",
1002 tm.year, tm.month, tm.monthday,
1003 tm.hour, tm.minute);
1009 * ntpd_time_stepped is called back by step_systime(), allowing ntpd
1010 * to do any one-time processing necessitated by the step.
1013 ntpd_time_stepped(void)
1015 u_int saved_mon_enabled;
1018 * flush the monitor MRU list which contains l_fp timestamps
1019 * which should not be compared across the step.
1021 if (MON_OFF != mon_enabled) {
1022 saved_mon_enabled = mon_enabled;
1024 mon_start(saved_mon_enabled);
1027 /* inform interpolating Windows code to allow time to go back */