adjkerntz.c revision 253749
1/*
2 * Copyright (C) 1993-1998 by Andrey A. Chernov, Moscow, Russia.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#if 0
28#ifndef lint
29static const char copyright[] =
30"@(#)Copyright (C) 1993-1996 by Andrey A. Chernov, Moscow, Russia.\n\
31 All rights reserved.\n";
32#endif /* not lint */
33#endif
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/sbin/adjkerntz/adjkerntz.c 253749 2013-07-28 18:35:43Z avg $");
36
37/*
38 * Andrey A. Chernov   <ache@astral.msk.su>    Dec 20 1993
39 *
40 * Fix kernel time value if machine run wall CMOS clock
41 * (and /etc/wall_cmos_clock file present)
42 * using zoneinfo rules or direct TZ environment variable set.
43 * Use Joerg Wunsch idea for seconds accurate offset calculation
44 * with Garrett Wollman and Bruce Evans fixes.
45 *
46 */
47#include <stdio.h>
48#include <signal.h>
49#include <stdlib.h>
50#include <unistd.h>
51#include <syslog.h>
52#include <sys/time.h>
53#include <sys/param.h>
54#include <sys/sysctl.h>
55
56#include "pathnames.h"
57
58/*#define DEBUG*/
59
60#define True (1)
61#define False (0)
62#define Unknown (-1)
63
64#define REPORT_PERIOD (30*60)
65
66static void fake(int);
67static void usage(void);
68
69static void
70fake(int unused __unused)
71{
72
73	/* Do nothing. */
74}
75
76int
77main(int argc, char *argv[])
78{
79	struct tm local;
80	struct timeval tv, *stv;
81	struct timezone tz, *stz;
82	int kern_offset, wall_clock, disrtcset;
83	size_t len;
84	/* Avoid time_t here, can be unsigned long or worse */
85	long offset, localsec, diff;
86	time_t initial_sec, final_sec;
87	int ch;
88	int initial_isdst = -1, final_isdst;
89	int need_restore = False, sleep_mode = False, looping,
90	    init = Unknown;
91	sigset_t mask, emask;
92
93	while ((ch = getopt(argc, argv, "ais")) != -1)
94		switch((char)ch) {
95		case 'i':               /* initial call, save offset */
96			if (init != Unknown)
97				usage();
98			init = True;
99			break;
100		case 'a':               /* adjustment call, use saved offset */
101			if (init != Unknown)
102				usage();
103			init = False;
104			break;
105		case 's':
106			sleep_mode = True;
107			break;
108		default:
109			usage();
110		}
111	if (init == Unknown)
112		usage();
113
114	if (access(_PATH_CLOCK, F_OK) != 0)
115		return 0;
116
117	if (init)
118		sleep_mode = True;
119
120	sigemptyset(&mask);
121	sigemptyset(&emask);
122	sigaddset(&mask, SIGTERM);
123
124	openlog("adjkerntz", LOG_PID|LOG_PERROR, LOG_DAEMON);
125
126	(void) signal(SIGHUP, SIG_IGN);
127
128	if (init && daemon(0,
129#ifdef DEBUG
130	    1
131#else
132	    0
133#endif
134	    )) {
135		syslog(LOG_ERR, "daemon: %m");
136		return 1;
137	}
138
139again:
140	(void) sigprocmask(SIG_BLOCK, &mask, NULL);
141	(void) signal(SIGTERM, fake);
142
143	diff = 0;
144	stv = NULL;
145	stz = NULL;
146	looping = False;
147
148	wall_clock = (access(_PATH_CLOCK, F_OK) == 0);
149	if (init && !sleep_mode) {
150		init = False;
151		if (!wall_clock)
152			return 0;
153	}
154
155	tzset();
156
157	len = sizeof(kern_offset);
158	if (sysctlbyname("machdep.adjkerntz", &kern_offset, &len, NULL, 0) == -1) {
159		syslog(LOG_ERR, "sysctl(\"machdep.adjkerntz\"): %m");
160		return 1;
161	}
162
163/****** Critical section, do all things as fast as possible ******/
164
165	/* get local CMOS clock and possible kernel offset */
166	if (gettimeofday(&tv, &tz)) {
167		syslog(LOG_ERR, "gettimeofday: %m");
168		return 1;
169	}
170
171	/* get the actual local timezone difference */
172	initial_sec = tv.tv_sec;
173
174recalculate:
175	local = *localtime(&initial_sec);
176	if (diff == 0)
177		initial_isdst = local.tm_isdst;
178	local.tm_isdst = initial_isdst;
179
180	/* calculate local CMOS diff from GMT */
181
182	localsec = mktime(&local);
183	if (localsec == -1) {
184		/*
185		 * XXX user can only control local time, and it is
186		 * unacceptable to fail here for init.  2:30 am in the
187		 * middle of the nonexistent hour means 3:30 am.
188		 */
189		if (!sleep_mode) {
190			syslog(LOG_WARNING,
191			"Warning: nonexistent local time, try to run later.");
192			syslog(LOG_WARNING, "Giving up.");
193			return 1;
194		}
195		syslog(LOG_WARNING,
196			"Warning: nonexistent local time.");
197		syslog(LOG_WARNING, "Will retry after %d minutes.",
198			REPORT_PERIOD / 60);
199		(void) signal(SIGTERM, SIG_DFL);
200		(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
201		(void) sleep(REPORT_PERIOD);
202		goto again;
203	}
204	offset = -local.tm_gmtoff;
205#ifdef DEBUG
206	fprintf(stderr, "Initial offset: %ld secs\n", offset);
207#endif
208
209	/* correct the kerneltime for this diffs */
210	/* subtract kernel offset, if present, old offset too */
211
212	diff = offset - tz.tz_minuteswest * 60 - kern_offset;
213
214	if (diff != 0) {
215#ifdef DEBUG
216		fprintf(stderr, "Initial diff: %ld secs\n", diff);
217#endif
218		/* Yet one step for final time */
219
220		final_sec = initial_sec + diff;
221
222		/* get the actual local timezone difference */
223		local = *localtime(&final_sec);
224		final_isdst = diff < 0 ? initial_isdst : local.tm_isdst;
225		if (diff > 0 && initial_isdst != final_isdst) {
226			if (looping)
227				goto bad_final;
228			looping = True;
229			initial_isdst = final_isdst;
230			goto recalculate;
231		}
232		local.tm_isdst =  final_isdst;
233
234		localsec = mktime(&local);
235		if (localsec == -1) {
236		bad_final:
237			/*
238			 * XXX as above.  The user has even less control,
239			 * but perhaps we never get here.
240			 */
241			if (!sleep_mode) {
242				syslog(LOG_WARNING,
243					"Warning: nonexistent final local time, try to run later.");
244				syslog(LOG_WARNING, "Giving up.");
245				return 1;
246			}
247			syslog(LOG_WARNING,
248				"Warning: nonexistent final local time.");
249			syslog(LOG_WARNING, "Will retry after %d minutes.",
250				REPORT_PERIOD / 60);
251			(void) signal(SIGTERM, SIG_DFL);
252			(void) sigprocmask(SIG_UNBLOCK, &mask, NULL);
253			(void) sleep(REPORT_PERIOD);
254			goto again;
255		}
256		offset = -local.tm_gmtoff;
257#ifdef DEBUG
258		fprintf(stderr, "Final offset: %ld secs\n", offset);
259#endif
260
261		/* correct the kerneltime for this diffs */
262		/* subtract kernel offset, if present, old offset too */
263
264		diff = offset - tz.tz_minuteswest * 60 - kern_offset;
265
266		if (diff != 0) {
267#ifdef DEBUG
268			fprintf(stderr, "Final diff: %ld secs\n", diff);
269#endif
270			/*
271			 * stv is abused as a flag.  The important value
272			 * is in `diff'.
273			 */
274			stv = &tv;
275		}
276	}
277
278	if (tz.tz_dsttime != 0 || tz.tz_minuteswest != 0) {
279		tz.tz_dsttime = tz.tz_minuteswest = 0;  /* zone info is garbage */
280		stz = &tz;
281	}
282	if (!wall_clock && stz == NULL)
283		stv = NULL;
284
285	/* if init or UTC clock and offset/date will be changed, */
286	/* disable RTC modification for a while.                      */
287
288	if (   (init && stv != NULL)
289	    || ((init || !wall_clock) && kern_offset != offset)
290	   ) {
291		len = sizeof(disrtcset);
292		if (sysctlbyname("machdep.disable_rtc_set", &disrtcset, &len, NULL, 0) == -1) {
293			syslog(LOG_ERR, "sysctl(get: \"machdep.disable_rtc_set\"): %m");
294			return 1;
295		}
296		if (disrtcset == 0) {
297			disrtcset = 1;
298			need_restore = True;
299			if (sysctlbyname("machdep.disable_rtc_set", NULL, NULL, &disrtcset, len) == -1) {
300				syslog(LOG_ERR, "sysctl(set: \"machdep.disable_rtc_set\"): %m");
301				return 1;
302			}
303		}
304	}
305
306	if (   (init && (stv != NULL || stz != NULL))
307	    || (stz != NULL && stv == NULL)
308	   ) {
309		if (stv != NULL) {
310			/*
311			 * Get the time again, as close as possible to
312			 * adjusting it, to minimise drift.
313			 * XXX we'd better not fail between here and
314			 * restoring disrtcset, since we don't clean up
315			 * anything.
316			 */
317			(void)gettimeofday(&tv, NULL);
318			tv.tv_sec += diff;
319			stv = &tv;
320		}
321		if (settimeofday(stv, stz)) {
322			syslog(LOG_ERR, "settimeofday: %m");
323			return 1;
324		}
325	}
326
327	/* setting machdep.adjkerntz have a side effect: resettodr(), which */
328	/* can be disabled by machdep.disable_rtc_set, so if init or UTC clock    */
329	/* -- don't write RTC, else write RTC.                          */
330
331	if (kern_offset != offset) {
332		kern_offset = offset;
333		len = sizeof(kern_offset);
334		if (sysctlbyname("machdep.adjkerntz", NULL, NULL, &kern_offset, len) == -1) {
335			syslog(LOG_ERR, "sysctl(set: \"machdep.adjkerntz\"): %m");
336			return 1;
337		}
338	}
339
340	len = sizeof(wall_clock);
341	if (sysctlbyname("machdep.wall_cmos_clock",  NULL, NULL, &wall_clock, len) == -1) {
342		syslog(LOG_ERR, "sysctl(set: \"machdep.wall_cmos_clock\"): %m");
343		return 1;
344	}
345
346	if (need_restore) {
347		need_restore = False;
348		disrtcset = 0;
349		len = sizeof(disrtcset);
350		if (sysctlbyname("machdep.disable_rtc_set", NULL, NULL, &disrtcset, len) == -1) {
351			syslog(LOG_ERR, "sysctl(set: \"machdep.disable_rtc_set\"): %m");
352			return 1;
353		}
354	}
355
356/****** End of critical section ******/
357
358	if (init && wall_clock) {
359		sleep_mode = False;
360		/* wait for signals and acts like -a */
361		(void) sigsuspend(&emask);
362		goto again;
363	}
364
365	return 0;
366}
367
368static void
369usage(void)
370{
371	fprintf(stderr, "%s\n%s\n%s\n%s\n",
372		"usage: adjkerntz -i",
373		"\t\t(initial call from /etc/rc)",
374		"       adjkerntz -a [-s]",
375		"\t\t(adjustment call, -s for sleep/retry mode)");
376	exit(2);
377}
378