xref: /netbsd-src/external/bsd/ntp/dist/ntpd/ntp_util.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
1 /*	$NetBSD: ntp_util.c,v 1.8 2016/01/08 21:35:39 christos Exp $	*/
2 
3 /*
4  * ntp_util.c - stuff I didn't have any other place for
5  */
6 #ifdef HAVE_CONFIG_H
7 # include <config.h>
8 #endif
9 
10 #include "ntpd.h"
11 #include "ntp_unixtime.h"
12 #include "ntp_filegen.h"
13 #include "ntp_if.h"
14 #include "ntp_stdlib.h"
15 #include "ntp_assert.h"
16 #include "ntp_calendar.h"
17 #include "ntp_leapsec.h"
18 #include "lib_strbuf.h"
19 
20 #include <stdio.h>
21 #include <ctype.h>
22 #include <sys/types.h>
23 #ifdef HAVE_SYS_IOCTL_H
24 # include <sys/ioctl.h>
25 #endif
26 #ifdef HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29 #include <sys/stat.h>
30 
31 #ifdef HAVE_IEEEFP_H
32 # include <ieeefp.h>
33 #endif
34 #ifdef HAVE_MATH_H
35 # include <math.h>
36 #endif
37 
38 #if defined(VMS)
39 # include <descrip.h>
40 #endif /* VMS */
41 
42 /*
43  * Defines used by the leapseconds stuff
44  */
45 #define	MAX_TAI	100			/* max TAI offset (s) */
46 #define	L_DAY	86400UL			/* seconds per day */
47 #define	L_YEAR	(L_DAY * 365)		/* days per year */
48 #define	L_LYEAR	(L_YEAR + L_DAY)	/* days per leap year */
49 #define	L_4YEAR	(L_LYEAR + 3 * L_YEAR)	/* days per leap cycle */
50 #define	L_CENT	(L_4YEAR * 25)		/* days per century */
51 
52 /*
53  * This contains odds and ends, including the hourly stats, various
54  * configuration items, leapseconds stuff, etc.
55  */
56 /*
57  * File names
58  */
59 static	char *key_file_name;		/* keys file name */
60 static char	  *leapfile_name;		/* leapseconds file name */
61 static struct stat leapfile_stat;	/* leapseconds file stat() buffer */
62 static int /*BOOL*/have_leapfile = FALSE;
63 char	*stats_drift_file;		/* frequency file name */
64 static	char *stats_temp_file;		/* temp frequency file name */
65 static double wander_resid;		/* last frequency update */
66 double	wander_threshold = 1e-7;	/* initial frequency threshold */
67 
68 /*
69  * Statistics file stuff
70  */
71 #ifndef NTP_VAR
72 # ifndef SYS_WINNT
73 #  define NTP_VAR "/var/NTP/"		/* NOTE the trailing '/' */
74 # else
75 #  define NTP_VAR "c:\\var\\ntp\\"	/* NOTE the trailing '\\' */
76 # endif /* SYS_WINNT */
77 #endif
78 
79 
80 char statsdir[MAXFILENAME] = NTP_VAR;
81 static FILEGEN peerstats;
82 static FILEGEN loopstats;
83 static FILEGEN clockstats;
84 static FILEGEN rawstats;
85 static FILEGEN sysstats;
86 static FILEGEN protostats;
87 static FILEGEN cryptostats;
88 static FILEGEN timingstats;
89 
90 /*
91  * This controls whether stats are written to the fileset. Provided
92  * so that ntpdc can turn off stats when the file system fills up.
93  */
94 int stats_control;
95 
96 /*
97  * Last frequency written to file.
98  */
99 static double prev_drift_comp;		/* last frequency update */
100 
101 /*
102  * Function prototypes
103  */
104 static	void	record_sys_stats(void);
105 	void	ntpd_time_stepped(void);
106 static  void	check_leap_expiration(int, uint32_t, const time_t*);
107 
108 /*
109  * Prototypes
110  */
111 #ifdef DEBUG
112 void	uninit_util(void);
113 #endif
114 
115 /*
116  * uninit_util - free memory allocated by init_util
117  */
118 #ifdef DEBUG
119 void
120 uninit_util(void)
121 {
122 #if defined(_MSC_VER) && defined (_DEBUG)
123 	_CrtCheckMemory();
124 #endif
125 	if (stats_drift_file) {
126 		free(stats_drift_file);
127 		free(stats_temp_file);
128 		stats_drift_file = NULL;
129 		stats_temp_file = NULL;
130 	}
131 	if (key_file_name) {
132 		free(key_file_name);
133 		key_file_name = NULL;
134 	}
135 	filegen_unregister("peerstats");
136 	filegen_unregister("loopstats");
137 	filegen_unregister("clockstats");
138 	filegen_unregister("rawstats");
139 	filegen_unregister("sysstats");
140 	filegen_unregister("protostats");
141 #ifdef AUTOKEY
142 	filegen_unregister("cryptostats");
143 #endif	/* AUTOKEY */
144 #ifdef DEBUG_TIMING
145 	filegen_unregister("timingstats");
146 #endif	/* DEBUG_TIMING */
147 
148 #if defined(_MSC_VER) && defined (_DEBUG)
149 	_CrtCheckMemory();
150 #endif
151 }
152 #endif /* DEBUG */
153 
154 
155 /*
156  * init_util - initialize the util module of ntpd
157  */
158 void
159 init_util(void)
160 {
161 	filegen_register(statsdir, "peerstats",	  &peerstats);
162 	filegen_register(statsdir, "loopstats",	  &loopstats);
163 	filegen_register(statsdir, "clockstats",  &clockstats);
164 	filegen_register(statsdir, "rawstats",	  &rawstats);
165 	filegen_register(statsdir, "sysstats",	  &sysstats);
166 	filegen_register(statsdir, "protostats",  &protostats);
167 	filegen_register(statsdir, "cryptostats", &cryptostats);
168 	filegen_register(statsdir, "timingstats", &timingstats);
169 	/*
170 	 * register with libntp ntp_set_tod() to call us back
171 	 * when time is stepped.
172 	 */
173 	step_callback = &ntpd_time_stepped;
174 #ifdef DEBUG
175 	atexit(&uninit_util);
176 #endif /* DEBUG */
177 }
178 
179 
180 /*
181  * hourly_stats - print some interesting stats
182  */
183 void
184 write_stats(void)
185 {
186 	FILE	*fp;
187 #ifdef DOSYNCTODR
188 	struct timeval tv;
189 #if !defined(VMS)
190 	int	prio_set;
191 #endif
192 #ifdef HAVE_GETCLOCK
193 	struct timespec ts;
194 #endif
195 	int	o_prio;
196 
197 	/*
198 	 * Sometimes having a Sun can be a drag.
199 	 *
200 	 * The kernel variable dosynctodr controls whether the system's
201 	 * soft clock is kept in sync with the battery clock. If it
202 	 * is zero, then the soft clock is not synced, and the battery
203 	 * clock is simply left to rot. That means that when the system
204 	 * reboots, the battery clock (which has probably gone wacky)
205 	 * sets the soft clock. That means ntpd starts off with a very
206 	 * confused idea of what time it is. It then takes a large
207 	 * amount of time to figure out just how wacky the battery clock
208 	 * has made things drift, etc, etc. The solution is to make the
209 	 * battery clock sync up to system time. The way to do THAT is
210 	 * to simply set the time of day to the current time of day, but
211 	 * as quickly as possible. This may, or may not be a sensible
212 	 * thing to do.
213 	 *
214 	 * CAVEAT: settimeofday() steps the sun clock by about 800 us,
215 	 *	   so setting DOSYNCTODR seems a bad idea in the
216 	 *	   case of us resolution
217 	 */
218 
219 #if !defined(VMS)
220 	/*
221 	 * (prr) getpriority returns -1 on error, but -1 is also a valid
222 	 * return value (!), so instead we have to zero errno before the
223 	 * call and check it for non-zero afterwards.
224 	 */
225 	errno = 0;
226 	prio_set = 0;
227 	o_prio = getpriority(PRIO_PROCESS,0); /* Save setting */
228 
229 	/*
230 	 * (prr) if getpriority succeeded, call setpriority to raise
231 	 * scheduling priority as high as possible.  If that succeeds
232 	 * as well, set the prio_set flag so we remember to reset
233 	 * priority to its previous value below.  Note that on Solaris
234 	 * 2.6 (and beyond?), both getpriority and setpriority will fail
235 	 * with ESRCH, because sched_setscheduler (called from main) put
236 	 * us in the real-time scheduling class which setpriority
237 	 * doesn't know about. Being in the real-time class is better
238 	 * than anything setpriority can do, anyhow, so this error is
239 	 * silently ignored.
240 	 */
241 	if ((errno == 0) && (setpriority(PRIO_PROCESS,0,-20) == 0))
242 		prio_set = 1;	/* overdrive */
243 #endif /* VMS */
244 #ifdef HAVE_GETCLOCK
245 	(void) getclock(TIMEOFDAY, &ts);
246 	tv.tv_sec = ts.tv_sec;
247 	tv.tv_usec = ts.tv_nsec / 1000;
248 #else /*  not HAVE_GETCLOCK */
249 	GETTIMEOFDAY(&tv,(struct timezone *)NULL);
250 #endif /* not HAVE_GETCLOCK */
251 	if (ntp_set_tod(&tv,(struct timezone *)NULL) != 0)
252 		msyslog(LOG_ERR, "can't sync battery time: %m");
253 #if !defined(VMS)
254 	if (prio_set)
255 		setpriority(PRIO_PROCESS, 0, o_prio); /* downshift */
256 #endif /* VMS */
257 #endif /* DOSYNCTODR */
258 	record_sys_stats();
259 	if (stats_drift_file != 0) {
260 
261 		/*
262 		 * When the frequency file is written, initialize the
263 		 * prev_drift_comp and wander_resid. Thereafter,
264 		 * reduce the wander_resid by half each hour. When
265 		 * the difference between the prev_drift_comp and
266 		 * drift_comp is less than the wander_resid, update
267 		 * the frequncy file. This minimizes the file writes to
268 		 * nonvolaile storage.
269 		 */
270 #ifdef DEBUG
271 		if (debug)
272 			printf("write_stats: frequency %.6lf thresh %.6lf, freq %.6lf\n",
273 			    (prev_drift_comp - drift_comp) * 1e6, wander_resid *
274 			    1e6, drift_comp * 1e6);
275 #endif
276 		if (fabs(prev_drift_comp - drift_comp) < wander_resid) {
277 			wander_resid *= 0.5;
278 			return;
279 		}
280 		prev_drift_comp = drift_comp;
281 		wander_resid = wander_threshold;
282 		if ((fp = fopen(stats_temp_file, "w")) == NULL) {
283 			msyslog(LOG_ERR, "frequency file %s: %m",
284 			    stats_temp_file);
285 			return;
286 		}
287 		fprintf(fp, "%.3f\n", drift_comp * 1e6);
288 		(void)fclose(fp);
289 		/* atomic */
290 #ifdef SYS_WINNT
291 		if (_unlink(stats_drift_file)) /* rename semantics differ under NT */
292 			msyslog(LOG_WARNING,
293 				"Unable to remove prior drift file %s, %m",
294 				stats_drift_file);
295 #endif /* SYS_WINNT */
296 
297 #ifndef NO_RENAME
298 		if (rename(stats_temp_file, stats_drift_file))
299 			msyslog(LOG_WARNING,
300 				"Unable to rename temp drift file %s to %s, %m",
301 				stats_temp_file, stats_drift_file);
302 #else
303 		/* we have no rename NFS of ftp in use */
304 		if ((fp = fopen(stats_drift_file, "w")) ==
305 		    NULL) {
306 			msyslog(LOG_ERR,
307 			    "frequency file %s: %m",
308 			    stats_drift_file);
309 			return;
310 		}
311 #endif
312 
313 #if defined(VMS)
314 		/* PURGE */
315 		{
316 			$DESCRIPTOR(oldvers,";-1");
317 			struct dsc$descriptor driftdsc = {
318 				strlen(stats_drift_file), 0, 0,
319 				    stats_drift_file };
320 			while(lib$delete_file(&oldvers,
321 			    &driftdsc) & 1);
322 		}
323 #endif
324 	}
325 }
326 
327 
328 /*
329  * stats_config - configure the stats operation
330  */
331 void
332 stats_config(
333 	int item,
334 	const char *invalue	/* only one type so far */
335 	)
336 {
337 	FILE	*fp;
338 	const char *value;
339 	size_t	len;
340 	double	old_drift;
341 	l_fp	now;
342 	time_t  ttnow;
343 #ifndef VMS
344 	const char temp_ext[] = ".TEMP";
345 #else
346 	const char temp_ext[] = "-TEMP";
347 #endif
348 
349 	/*
350 	 * Expand environment strings under Windows NT, since the
351 	 * command interpreter doesn't do this, the program must.
352 	 */
353 #ifdef SYS_WINNT
354 	char newvalue[MAX_PATH], parameter[MAX_PATH];
355 
356 	if (!ExpandEnvironmentStrings(invalue, newvalue, MAX_PATH)) {
357 		switch (item) {
358 		case STATS_FREQ_FILE:
359 			strlcpy(parameter, "STATS_FREQ_FILE",
360 				sizeof(parameter));
361 			break;
362 
363 		case STATS_LEAP_FILE:
364 			strlcpy(parameter, "STATS_LEAP_FILE",
365 				sizeof(parameter));
366 			break;
367 
368 		case STATS_STATSDIR:
369 			strlcpy(parameter, "STATS_STATSDIR",
370 				sizeof(parameter));
371 			break;
372 
373 		case STATS_PID_FILE:
374 			strlcpy(parameter, "STATS_PID_FILE",
375 				sizeof(parameter));
376 			break;
377 
378 		default:
379 			strlcpy(parameter, "UNKNOWN",
380 				sizeof(parameter));
381 			break;
382 		}
383 		value = invalue;
384 		msyslog(LOG_ERR,
385 			"ExpandEnvironmentStrings(%s) failed: %m\n",
386 			parameter);
387 	} else {
388 		value = newvalue;
389 	}
390 #else
391 	value = invalue;
392 #endif /* SYS_WINNT */
393 
394 	switch (item) {
395 
396 	/*
397 	 * Open and read frequency file.
398 	 */
399 	case STATS_FREQ_FILE:
400 		if (!value || (len = strlen(value)) == 0)
401 			break;
402 
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));
409 
410 		/*
411 		 * Open drift file and read frequency. If the file is
412 		 * missing or contains errors, tell the loop to reset.
413 		 */
414 		if ((fp = fopen(stats_drift_file, "r")) == NULL)
415 			break;
416 
417 		if (fscanf(fp, "%lf", &old_drift) != 1) {
418 			msyslog(LOG_ERR,
419 				"format error frequency file %s",
420 				stats_drift_file);
421 			fclose(fp);
422 			break;
423 
424 		}
425 		fclose(fp);
426 		loop_config(LOOP_FREQ, old_drift);
427 		prev_drift_comp = drift_comp;
428 		break;
429 
430 	/*
431 	 * Specify statistics directory.
432 	 */
433 	case STATS_STATSDIR:
434 
435 		/* - 1 since value may be missing the DIR_SEP. */
436 		if (strlen(value) >= sizeof(statsdir) - 1) {
437 			msyslog(LOG_ERR,
438 			    "statsdir too long (>%d, sigh)",
439 			    (int)sizeof(statsdir) - 2);
440 		} else {
441 			int add_dir_sep;
442 			size_t value_l;
443 
444 			/* Add a DIR_SEP unless we already have one. */
445 			value_l = strlen(value);
446 			if (0 == value_l)
447 				add_dir_sep = FALSE;
448 			else
449 				add_dir_sep = (DIR_SEP !=
450 				    value[value_l - 1]);
451 
452 			if (add_dir_sep)
453 				snprintf(statsdir, sizeof(statsdir),
454 				    "%s%c", value, DIR_SEP);
455 			else
456 				snprintf(statsdir, sizeof(statsdir),
457 				    "%s", value);
458 			filegen_statsdir();
459 		}
460 		break;
461 
462 	/*
463 	 * Open pid file.
464 	 */
465 	case STATS_PID_FILE:
466 		if ((fp = fopen(value, "w")) == NULL) {
467 			msyslog(LOG_ERR, "pid file %s: %m",
468 			    value);
469 			break;
470 		}
471 		fprintf(fp, "%d", (int)getpid());
472 		fclose(fp);
473 		break;
474 
475 	/*
476 	 * Read leapseconds file.
477 	 *
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.
481 	 */
482 	case STATS_LEAP_FILE:
483 		if (!value || (len = strlen(value)) == 0)
484 			break;
485 
486 		leapfile_name = erealloc(leapfile_name, len + 1);
487 		memcpy(leapfile_name, value, len + 1);
488 
489 		if (leapsec_load_file(
490 			    leapfile_name, &leapfile_stat, TRUE, TRUE))
491 		{
492 			leap_signature_t lsig;
493 
494 			get_systime(&now);
495 			time(&ttnow);
496 			leapsec_getsig(&lsig);
497 			mprintf_event(EVNT_TAI, NULL,
498 				      "%d leap %s %s %s",
499 				      lsig.taiof,
500 				      fstostr(lsig.ttime),
501 				      leapsec_expired(now.l_ui, NULL)
502 					  ? "expired"
503 					  : "expires",
504 				      fstostr(lsig.etime));
505 
506 			have_leapfile = TRUE;
507 
508 			/* force an immediate daily expiration check of
509 			 * the leap seconds table
510 			 */
511 			check_leap_expiration(TRUE, now.l_ui, &ttnow);
512 		}
513 		break;
514 
515 	default:
516 		/* oh well */
517 		break;
518 	}
519 }
520 
521 
522 /*
523  * record_peer_stats - write peer statistics to file
524  *
525  * file format:
526  * day (MJD)
527  * time (s past UTC midnight)
528  * IP address
529  * status word (hex)
530  * offset
531  * delay
532  * dispersion
533  * jitter
534 */
535 void
536 record_peer_stats(
537 	sockaddr_u *addr,
538 	int	status,
539 	double	offset,		/* offset */
540 	double	delay,		/* delay */
541 	double	dispersion,	/* dispersion */
542 	double	jitter		/* jitter */
543 	)
544 {
545 	l_fp	now;
546 	u_long	day;
547 
548 	if (!stats_control)
549 		return;
550 
551 	get_systime(&now);
552 	filegen_setup(&peerstats, now.l_ui);
553 	day = now.l_ui / 86400 + MJD_1900;
554 	now.l_ui %= 86400;
555 	if (peerstats.fp != NULL) {
556 		fprintf(peerstats.fp,
557 		    "%lu %s %s %x %.9f %.9f %.9f %.9f\n", day,
558 		    ulfptoa(&now, 3), stoa(addr), status, offset,
559 		    delay, dispersion, jitter);
560 		fflush(peerstats.fp);
561 	}
562 }
563 
564 
565 /*
566  * record_loop_stats - write loop filter statistics to file
567  *
568  * file format:
569  * day (MJD)
570  * time (s past midnight)
571  * offset
572  * frequency (PPM)
573  * jitter
574  * wnder (PPM)
575  * time constant (log2)
576  */
577 void
578 record_loop_stats(
579 	double	offset,		/* offset */
580 	double	freq,		/* frequency (PPM) */
581 	double	jitter,		/* jitter */
582 	double	wander,		/* wander (PPM) */
583 	int spoll
584 	)
585 {
586 	l_fp	now;
587 	u_long	day;
588 
589 	if (!stats_control)
590 		return;
591 
592 	get_systime(&now);
593 	filegen_setup(&loopstats, now.l_ui);
594 	day = now.l_ui / 86400 + MJD_1900;
595 	now.l_ui %= 86400;
596 	if (loopstats.fp != NULL) {
597 		fprintf(loopstats.fp, "%lu %s %.9f %.3f %.9f %.6f %d\n",
598 		    day, ulfptoa(&now, 3), offset, freq * 1e6, jitter,
599 		    wander * 1e6, spoll);
600 		fflush(loopstats.fp);
601 	}
602 }
603 
604 
605 /*
606  * record_clock_stats - write clock statistics to file
607  *
608  * file format:
609  * day (MJD)
610  * time (s past midnight)
611  * IP address
612  * text message
613  */
614 void
615 record_clock_stats(
616 	sockaddr_u *addr,
617 	const char *text	/* timecode string */
618 	)
619 {
620 	l_fp	now;
621 	u_long	day;
622 
623 	if (!stats_control)
624 		return;
625 
626 	get_systime(&now);
627 	filegen_setup(&clockstats, now.l_ui);
628 	day = now.l_ui / 86400 + MJD_1900;
629 	now.l_ui %= 86400;
630 	if (clockstats.fp != NULL) {
631 		fprintf(clockstats.fp, "%lu %s %s %s\n", day,
632 		    ulfptoa(&now, 3), stoa(addr), text);
633 		fflush(clockstats.fp);
634 	}
635 }
636 
637 
638 /*
639  * mprintf_clock_stats - write clock statistics to file with
640  *			msnprintf-style formatting.
641  */
642 int
643 mprintf_clock_stats(
644 	sockaddr_u *addr,
645 	const char *fmt,
646 	...
647 	)
648 {
649 	va_list	ap;
650 	int	rc;
651 	char	msg[512];
652 
653 	va_start(ap, fmt);
654 	rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
655 	va_end(ap);
656 	if (stats_control)
657 		record_clock_stats(addr, msg);
658 
659 	return rc;
660 }
661 
662 /*
663  * record_raw_stats - write raw timestamps to file
664  *
665  * file format
666  * day (MJD)
667  * time (s past midnight)
668  * peer ip address
669  * IP address
670  * t1 t2 t3 t4 timestamps
671  */
672 void
673 record_raw_stats(
674 	sockaddr_u *srcadr,
675 	sockaddr_u *dstadr,
676 	l_fp	*t1,		/* originate timestamp */
677 	l_fp	*t2,		/* receive timestamp */
678 	l_fp	*t3,		/* transmit timestamp */
679 	l_fp	*t4,		/* destination timestamp */
680 	int	leap,
681 	int	version,
682 	int	mode,
683 	int	stratum,
684 	int	ppoll,
685 	int	precision,
686 	double	root_delay,	/* seconds */
687 	double	root_dispersion,/* seconds */
688 	u_int32	refid
689 	)
690 {
691 	l_fp	now;
692 	u_long	day;
693 
694 	if (!stats_control)
695 		return;
696 
697 	get_systime(&now);
698 	filegen_setup(&rawstats, now.l_ui);
699 	day = now.l_ui / 86400 + MJD_1900;
700 	now.l_ui %= 86400;
701 	if (rawstats.fp != NULL) {
702 		fprintf(rawstats.fp, "%lu %s %s %s %s %s %s %s %d %d %d %d %d %d %.6f %.6f %s\n",
703 		    day, ulfptoa(&now, 3),
704 		    stoa(srcadr), dstadr ?  stoa(dstadr) : "-",
705 		    ulfptoa(t1, 9), ulfptoa(t2, 9),
706 		    ulfptoa(t3, 9), ulfptoa(t4, 9),
707 		    leap, version, mode, stratum, ppoll, precision,
708 		    root_delay, root_dispersion, refid_str(refid, stratum));
709 		fflush(rawstats.fp);
710 	}
711 }
712 
713 
714 /*
715  * record_sys_stats - write system statistics to file
716  *
717  * file format
718  * day (MJD)
719  * time (s past midnight)
720  * time since reset
721  * packets recieved
722  * packets for this host
723  * current version
724  * old version
725  * access denied
726  * bad length or format
727  * bad authentication
728  * declined
729  * rate exceeded
730  * KoD sent
731  */
732 void
733 record_sys_stats(void)
734 {
735 	l_fp	now;
736 	u_long	day;
737 
738 	if (!stats_control)
739 		return;
740 
741 	get_systime(&now);
742 	filegen_setup(&sysstats, now.l_ui);
743 	day = now.l_ui / 86400 + MJD_1900;
744 	now.l_ui %= 86400;
745 	if (sysstats.fp != NULL) {
746 		fprintf(sysstats.fp,
747 		    "%lu %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
748 		    day, ulfptoa(&now, 3), current_time - sys_stattime,
749 		    sys_received, sys_processed, sys_newversion,
750 		    sys_oldversion, sys_restricted, sys_badlength,
751 		    sys_badauth, sys_declined, sys_limitrejected,
752 		    sys_kodsent);
753 		fflush(sysstats.fp);
754 		proto_clr_stats();
755 	}
756 }
757 
758 
759 /*
760  * record_proto_stats - write system statistics to file
761  *
762  * file format
763  * day (MJD)
764  * time (s past midnight)
765  * text message
766  */
767 void
768 record_proto_stats(
769 	char	*str		/* text string */
770 	)
771 {
772 	l_fp	now;
773 	u_long	day;
774 
775 	if (!stats_control)
776 		return;
777 
778 	get_systime(&now);
779 	filegen_setup(&protostats, now.l_ui);
780 	day = now.l_ui / 86400 + MJD_1900;
781 	now.l_ui %= 86400;
782 	if (protostats.fp != NULL) {
783 		fprintf(protostats.fp, "%lu %s %s\n", day,
784 		    ulfptoa(&now, 3), str);
785 		fflush(protostats.fp);
786 	}
787 }
788 
789 
790 #ifdef AUTOKEY
791 /*
792  * record_crypto_stats - write crypto statistics to file
793  *
794  * file format:
795  * day (mjd)
796  * time (s past midnight)
797  * peer ip address
798  * text message
799  */
800 void
801 record_crypto_stats(
802 	sockaddr_u *addr,
803 	const char *text	/* text message */
804 	)
805 {
806 	l_fp	now;
807 	u_long	day;
808 
809 	if (!stats_control)
810 		return;
811 
812 	get_systime(&now);
813 	filegen_setup(&cryptostats, now.l_ui);
814 	day = now.l_ui / 86400 + MJD_1900;
815 	now.l_ui %= 86400;
816 	if (cryptostats.fp != NULL) {
817 		if (addr == NULL)
818 			fprintf(cryptostats.fp, "%lu %s 0.0.0.0 %s\n",
819 			    day, ulfptoa(&now, 3), text);
820 		else
821 			fprintf(cryptostats.fp, "%lu %s %s %s\n",
822 			    day, ulfptoa(&now, 3), stoa(addr), text);
823 		fflush(cryptostats.fp);
824 	}
825 }
826 #endif	/* AUTOKEY */
827 
828 
829 #ifdef DEBUG_TIMING
830 /*
831  * record_timing_stats - write timing statistics to file
832  *
833  * file format:
834  * day (mjd)
835  * time (s past midnight)
836  * text message
837  */
838 void
839 record_timing_stats(
840 	const char *text	/* text message */
841 	)
842 {
843 	static unsigned int flshcnt;
844 	l_fp	now;
845 	u_long	day;
846 
847 	if (!stats_control)
848 		return;
849 
850 	get_systime(&now);
851 	filegen_setup(&timingstats, now.l_ui);
852 	day = now.l_ui / 86400 + MJD_1900;
853 	now.l_ui %= 86400;
854 	if (timingstats.fp != NULL) {
855 		fprintf(timingstats.fp, "%lu %s %s\n", day, lfptoa(&now,
856 		    3), text);
857 		if (++flshcnt % 100 == 0)
858 			fflush(timingstats.fp);
859 	}
860 }
861 #endif
862 
863 
864 /*
865  * check_leap_file - See if the leapseconds file has been updated.
866  *
867  * Returns: n/a
868  *
869  * Note: This loads a new leapfile on the fly. Currently a leap file
870  * without SHA1 signature is accepted, but if there is a signature line,
871  * the signature must be valid or the file is rejected.
872  */
873 void
874 check_leap_file(
875 	int           is_daily_check,
876 	uint32_t      ntptime       ,
877 	const time_t *systime
878 	)
879 {
880 	/* just do nothing if there is no leap file */
881 	if ( ! (leapfile_name && *leapfile_name))
882 		return;
883 
884 	/* try to load leapfile, force it if no leapfile loaded yet */
885 	if (leapsec_load_file(
886 		    leapfile_name, &leapfile_stat,
887 		    !have_leapfile, is_daily_check))
888 		have_leapfile = TRUE;
889 	else if (!have_leapfile)
890 		return;
891 
892 	check_leap_expiration(is_daily_check, ntptime, systime);
893 }
894 
895 /*
896  * check expiration of a loaded leap table
897  */
898 static void
899 check_leap_expiration(
900 	int           is_daily_check,
901 	uint32_t      ntptime       ,
902 	const time_t *systime
903 	)
904 {
905 	static const char * const logPrefix = "leapsecond file";
906 	int  rc;
907 
908 	/* test the expiration of the leap data and log with proper
909 	 * level and frequency (once/hour or once/day, depending on the
910 	 * state.
911 	 */
912 	rc = leapsec_daystolive(ntptime, systime);
913 	if (rc == 0) {
914 		msyslog(LOG_WARNING,
915 			"%s ('%s'): will expire in less than one day",
916 			logPrefix, leapfile_name);
917 	} else if (is_daily_check && rc < 28) {
918 		if (rc < 0)
919 			msyslog(LOG_ERR,
920 				"%s ('%s'): expired less than %d day%s ago",
921 				logPrefix, leapfile_name, -rc, (rc == -1 ? "" : "s"));
922 		else
923 			msyslog(LOG_WARNING,
924 				"%s ('%s'): will expire in less than %d days",
925 				logPrefix, leapfile_name, 1+rc);
926 	}
927 }
928 
929 
930 /*
931  * getauthkeys - read the authentication keys from the specified file
932  */
933 void
934 getauthkeys(
935 	const char *keyfile
936 	)
937 {
938 	size_t len;
939 
940 	len = strlen(keyfile);
941 	if (!len)
942 		return;
943 
944 #ifndef SYS_WINNT
945 	key_file_name = erealloc(key_file_name, len + 1);
946 	memcpy(key_file_name, keyfile, len + 1);
947 #else
948 	key_file_name = erealloc(key_file_name, _MAX_PATH);
949 	if (len + 1 > _MAX_PATH)
950 		return;
951 	if (!ExpandEnvironmentStrings(keyfile, key_file_name,
952 				      _MAX_PATH)) {
953 		msyslog(LOG_ERR,
954 			"ExpandEnvironmentStrings(KEY_FILE) failed: %m");
955 		strlcpy(key_file_name, keyfile, _MAX_PATH);
956 	}
957 	key_file_name = erealloc(key_file_name,
958 				 1 + strlen(key_file_name));
959 #endif /* SYS_WINNT */
960 
961 	authreadkeys(key_file_name);
962 }
963 
964 
965 /*
966  * rereadkeys - read the authentication key file over again.
967  */
968 void
969 rereadkeys(void)
970 {
971 	if (NULL != key_file_name)
972 		authreadkeys(key_file_name);
973 }
974 
975 
976 #if notyet
977 /*
978  * ntp_exit - document explicitly that ntpd has exited
979  */
980 void
981 ntp_exit(int retval)
982 {
983 	msyslog(LOG_ERR, "EXITING with return code %d", retval);
984 	exit(retval);
985 }
986 #endif
987 
988 /*
989  * fstostr - prettyprint NTP seconds
990  */
991 char * fstostr(
992 	time_t	ntp_stamp
993 	)
994 {
995 	char *		buf;
996 	struct calendar tm;
997 
998 	LIB_GETBUF(buf);
999 	if (ntpcal_ntp_to_date(&tm, (u_int32)ntp_stamp, NULL) < 0)
1000 		snprintf(buf, LIB_BUFLENGTH, "ntpcal_ntp_to_date: %ld: range error",
1001 			 (long)ntp_stamp);
1002 	else
1003 		snprintf(buf, LIB_BUFLENGTH, "%04d%02d%02d%02d%02d",
1004 			 tm.year, tm.month, tm.monthday,
1005 			 tm.hour, tm.minute);
1006 	return buf;
1007 }
1008 
1009 
1010 /*
1011  * ntpd_time_stepped is called back by step_systime(), allowing ntpd
1012  * to do any one-time processing necessitated by the step.
1013  */
1014 void
1015 ntpd_time_stepped(void)
1016 {
1017 	u_int saved_mon_enabled;
1018 
1019 	/*
1020 	 * flush the monitor MRU list which contains l_fp timestamps
1021 	 * which should not be compared across the step.
1022 	 */
1023 	if (MON_OFF != mon_enabled) {
1024 		saved_mon_enabled = mon_enabled;
1025 		mon_stop(MON_OFF);
1026 		mon_start(saved_mon_enabled);
1027 	}
1028 
1029 	/* inform interpolating Windows code to allow time to go back */
1030 #ifdef SYS_WINNT
1031 	win_time_stepped();
1032 #endif
1033 }
1034