xref: /freebsd/contrib/ntp/parseutil/dcfd.c (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
1 /*
2  * /src/NTP/REPOSITORY/ntp4-dev/parseutil/dcfd.c,v 4.18 2005/10/07 22:08:18 kardel RELEASE_20051008_A
3  *
4  * dcfd.c,v 4.18 2005/10/07 22:08:18 kardel RELEASE_20051008_A
5  *
6  * DCF77 100/200ms pulse synchronisation daemon program (via 50Baud serial line)
7  *
8  * Features:
9  *  DCF77 decoding
10  *  simple NTP loopfilter logic for local clock
11  *  interactive display for debugging
12  *
13  * Lacks:
14  *  Leap second handling (at that level you should switch to NTP Version 4 - really!)
15  *
16  * Copyright (c) 1995-2015 by Frank Kardel <kardel <AT> ntp.org>
17  * Copyright (c) 1989-1994 by Frank Kardel, Friedrich-Alexander Universitaet Erlangen-Nuernberg, Germany
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  * 3. Neither the name of the author nor the names of its contributors
28  *    may be used to endorse or promote products derived from this software
29  *    without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  *
43  */
44 
45 #ifdef HAVE_CONFIG_H
46 # include <config.h>
47 #endif
48 
49 #include <sys/ioctl.h>
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <fcntl.h>
53 #include <sys/types.h>
54 #include <sys/time.h>
55 #include <signal.h>
56 #include <syslog.h>
57 #include <time.h>
58 
59 /*
60  * NTP compilation environment
61  */
62 #include "ntp_stdlib.h"
63 #include "ntpd.h"   /* indirectly include ntp.h to get YEAR_PIVOT   Y2KFixes */
64 
65 /*
66  * select which terminal handling to use (currently only SysV variants)
67  */
68 #if defined(HAVE_TERMIOS_H) || defined(STREAM)
69 #include <termios.h>
70 #define TTY_GETATTR(_FD_, _ARG_) tcgetattr((_FD_), (_ARG_))
71 #define TTY_SETATTR(_FD_, _ARG_) tcsetattr((_FD_), TCSANOW, (_ARG_))
72 #else  /* not HAVE_TERMIOS_H || STREAM */
73 # if defined(HAVE_TERMIO_H) || defined(HAVE_SYSV_TTYS)
74 #  include <termio.h>
75 #  define TTY_GETATTR(_FD_, _ARG_) ioctl((_FD_), TCGETA, (_ARG_))
76 #  define TTY_SETATTR(_FD_, _ARG_) ioctl((_FD_), TCSETAW, (_ARG_))
77 # endif/* HAVE_TERMIO_H || HAVE_SYSV_TTYS */
78 #endif /* not HAVE_TERMIOS_H || STREAM */
79 
80 
81 #ifndef TTY_GETATTR
82 #include "Bletch: MUST DEFINE ONE OF 'HAVE_TERMIOS_H' or 'HAVE_TERMIO_H'"
83 #endif
84 
85 #ifndef days_per_year
86 #define days_per_year(_x_) (((_x_) % 4) ? 365 : (((_x_) % 400) ? 365 : 366))
87 #endif
88 
89 #define timernormalize(_a_) \
90 	if ((_a_)->tv_usec >= 1000000) \
91 	{ \
92 		(_a_)->tv_sec  += (_a_)->tv_usec / 1000000; \
93 		(_a_)->tv_usec  = (_a_)->tv_usec % 1000000; \
94 	} \
95 	if ((_a_)->tv_usec < 0) \
96 	{ \
97 		(_a_)->tv_sec  -= 1 + (-(_a_)->tv_usec / 1000000); \
98 		(_a_)->tv_usec = 999999 - (-(_a_)->tv_usec - 1); \
99 	}
100 
101 #ifdef timeradd
102 #undef timeradd
103 #endif
104 #define timeradd(_a_, _b_) \
105 	(_a_)->tv_sec  += (_b_)->tv_sec; \
106 	(_a_)->tv_usec += (_b_)->tv_usec; \
107 	timernormalize((_a_))
108 
109 #ifdef timersub
110 #undef timersub
111 #endif
112 #define timersub(_a_, _b_) \
113 	(_a_)->tv_sec  -= (_b_)->tv_sec; \
114 	(_a_)->tv_usec -= (_b_)->tv_usec; \
115 	timernormalize((_a_))
116 
117 /*
118  * debug macros
119  */
120 #define PRINTF if (interactive) printf
121 #define LPRINTF if (interactive && loop_filter_debug) printf
122 
123 #ifdef DEBUG
124 #define DPRINTF(_x_) LPRINTF _x_
125 #else
126 #define DPRINTF(_x_)
127 #endif
128 
129 #ifdef DECL_ERRNO
130      extern int errno;
131 #endif
132 
133 static char *revision = "4.18";
134 
135 /*
136  * display received data (avoids also detaching from tty)
137  */
138 static int interactive = 0;
139 
140 /*
141  * display loopfilter (clock control) variables
142  */
143 static int loop_filter_debug = 0;
144 
145 /*
146  * do not set/adjust system time
147  */
148 static int no_set = 0;
149 
150 /*
151  * time that passes between start of DCF impulse and time stamping (fine
152  * adjustment) in microseconds (receiver/OS dependent)
153  */
154 #define DEFAULT_DELAY	230000	/* rough estimate */
155 
156 /*
157  * The two states we can be in - eithe we receive nothing
158  * usable or we have the correct time
159  */
160 #define NO_SYNC		0x01
161 #define SYNC		0x02
162 
163 static int    sync_state = NO_SYNC;
164 static time_t last_sync;
165 
166 static unsigned long ticks = 0;
167 
168 static char pat[] = "-\\|/";
169 
170 #define LINES		(24-2)	/* error lines after which the two headlines are repeated */
171 
172 #define MAX_UNSYNC	(10*60)	/* allow synchronisation loss for 10 minutes */
173 #define NOTICE_INTERVAL (20*60)	/* mention missing synchronisation every 20 minutes */
174 
175 /*
176  * clock adjustment PLL - see NTP protocol spec (RFC1305) for details
177  */
178 
179 #define USECSCALE	10
180 #define TIMECONSTANT	2
181 #define ADJINTERVAL	0
182 #define FREQ_WEIGHT	18
183 #define PHASE_WEIGHT	7
184 #define MAX_DRIFT	0x3FFFFFFF
185 
186 #define R_SHIFT(_X_, _Y_) (((_X_) < 0) ? -(-(_X_) >> (_Y_)) : ((_X_) >> (_Y_)))
187 
188 static long max_adj_offset_usec = 128000;
189 
190 static long clock_adjust = 0;	/* current adjustment value (usec * 2^USECSCALE) */
191 static long accum_drift   = 0;	/* accumulated drift value  (usec / ADJINTERVAL) */
192 static long adjustments  = 0;
193 static char skip_adjust  = 1;	/* discard first adjustment (bad samples) */
194 
195 /*
196  * DCF77 state flags
197  */
198 #define DCFB_ANNOUNCE		0x0001 /* switch time zone warning (DST switch) */
199 #define DCFB_DST		0x0002 /* DST in effect */
200 #define DCFB_LEAP		0x0004 /* LEAP warning (1 hour prior to occurrence) */
201 #define DCFB_CALLBIT		0x0008 /* "call bit" used to signalize irregularities in the control facilities */
202 
203 struct clocktime		/* clock time broken up from time code */
204 {
205 	long wday;		/* Day of week: 1: Monday - 7: Sunday */
206 	long day;
207 	long month;
208 	long year;
209 	long hour;
210 	long minute;
211 	long second;
212 	long usecond;
213 	long utcoffset;	/* in minutes */
214 	long flags;		/* current clock status  (DCF77 state flags) */
215 };
216 
217 typedef struct clocktime clocktime_t;
218 
219 /*
220  * (usually) quick constant multiplications
221  */
222 #ifndef TIMES10
223 #define TIMES10(_X_) (((_X_) << 3) + ((_X_) << 1))	/* *8 + *2 */
224 #endif
225 #ifndef TIMES24
226 #define TIMES24(_X_) (((_X_) << 4) + ((_X_) << 3))      /* *16 + *8 */
227 #endif
228 #ifndef TIMES60
229 #define TIMES60(_X_) ((((_X_) << 4)  - (_X_)) << 2)     /* *(16 - 1) *4 */
230 #endif
231 
232 /*
233  * generic l_abs() function
234  */
235 #define l_abs(_x_)     (((_x_) < 0) ? -(_x_) : (_x_))
236 
237 /*
238  * conversion related return/error codes
239  */
240 #define CVT_MASK	0x0000000F /* conversion exit code */
241 #define   CVT_NONE	0x00000001 /* format not applicable */
242 #define   CVT_FAIL	0x00000002 /* conversion failed - error code returned */
243 #define   CVT_OK	0x00000004 /* conversion succeeded */
244 #define CVT_BADFMT	0x00000010 /* general format error - (unparsable) */
245 #define CVT_BADDATE	0x00000020 /* invalid date */
246 #define CVT_BADTIME	0x00000040 /* invalid time */
247 
248 /*
249  * DCF77 raw time code
250  *
251  * From "Zur Zeit", Physikalisch-Technische Bundesanstalt (PTB), Braunschweig
252  * und Berlin, Maerz 1989
253  *
254  * Timecode transmission:
255  * AM:
256  *	time marks are send every second except for the second before the
257  *	next minute mark
258  *	time marks consist of a reduction of transmitter power to 25%
259  *	of the nominal level
260  *	the falling edge is the time indication (on time)
261  *	time marks of a 100ms duration constitute a logical 0
262  *	time marks of a 200ms duration constitute a logical 1
263  * FM:
264  *	see the spec. (basically a (non-)inverted psuedo random phase shift)
265  *
266  * Encoding:
267  * Second	Contents
268  * 0  - 10	AM: free, FM: 0
269  * 11 - 14	free
270  * 15		R     - "call bit" used to signalize irregularities in the control facilities
271  *		        (until 2003 indicated transmission via alternate antenna)
272  * 16		A1    - expect zone change (1 hour before)
273  * 17 - 18	Z1,Z2 - time zone
274  *		 0  0 illegal
275  *		 0  1 MEZ  (MET)
276  *		 1  0 MESZ (MED, MET DST)
277  *		 1  1 illegal
278  * 19		A2    - expect leap insertion/deletion (1 hour before)
279  * 20		S     - start of time code (1)
280  * 21 - 24	M1    - BCD (lsb first) Minutes
281  * 25 - 27	M10   - BCD (lsb first) 10 Minutes
282  * 28		P1    - Minute Parity (even)
283  * 29 - 32	H1    - BCD (lsb first) Hours
284  * 33 - 34      H10   - BCD (lsb first) 10 Hours
285  * 35		P2    - Hour Parity (even)
286  * 36 - 39	D1    - BCD (lsb first) Days
287  * 40 - 41	D10   - BCD (lsb first) 10 Days
288  * 42 - 44	DW    - BCD (lsb first) day of week (1: Monday -> 7: Sunday)
289  * 45 - 49	MO    - BCD (lsb first) Month
290  * 50           MO0   - 10 Months
291  * 51 - 53	Y1    - BCD (lsb first) Years
292  * 54 - 57	Y10   - BCD (lsb first) 10 Years
293  * 58 		P3    - Date Parity (even)
294  * 59		      - usually missing (minute indication), except for leap insertion
295  */
296 
297 /*-----------------------------------------------------------------------
298  * conversion table to map DCF77 bit stream into data fields.
299  * Encoding:
300  *   Each field of the DCF77 code is described with two adjacent entries in
301  *   this table. The first entry specifies the offset into the DCF77 data stream
302  *   while the length is given as the difference between the start index and
303  *   the start index of the following field.
304  */
305 static struct rawdcfcode
306 {
307 	char offset;			/* start bit */
308 } rawdcfcode[] =
309 {
310 	{  0 }, { 15 }, { 16 }, { 17 }, { 19 }, { 20 }, { 21 }, { 25 }, { 28 }, { 29 },
311 	{ 33 }, { 35 }, { 36 }, { 40 }, { 42 }, { 45 }, { 49 }, { 50 }, { 54 }, { 58 }, { 59 }
312 };
313 
314 /*-----------------------------------------------------------------------
315  * symbolic names for the fields of DCF77 describes in "rawdcfcode".
316  * see comment above for the structure of the DCF77 data
317  */
318 #define DCF_M	0
319 #define DCF_R	1
320 #define DCF_A1	2
321 #define DCF_Z	3
322 #define DCF_A2	4
323 #define DCF_S	5
324 #define DCF_M1	6
325 #define DCF_M10	7
326 #define DCF_P1	8
327 #define DCF_H1	9
328 #define DCF_H10	10
329 #define DCF_P2	11
330 #define DCF_D1	12
331 #define DCF_D10	13
332 #define DCF_DW	14
333 #define DCF_MO	15
334 #define DCF_MO0	16
335 #define DCF_Y1	17
336 #define DCF_Y10	18
337 #define DCF_P3	19
338 
339 /*-----------------------------------------------------------------------
340  * parity field table (same encoding as rawdcfcode)
341  * This table describes the sections of the DCF77 code that are
342  * parity protected
343  */
344 static struct partab
345 {
346 	char offset;			/* start bit of parity field */
347 } partab[] =
348 {
349 	{ 21 }, { 29 }, { 36 }, { 59 }
350 };
351 
352 /*-----------------------------------------------------------------------
353  * offsets for parity field descriptions
354  */
355 #define DCF_P_P1	0
356 #define DCF_P_P2	1
357 #define DCF_P_P3	2
358 
359 /*-----------------------------------------------------------------------
360  * legal values for time zone information
361  */
362 #define DCF_Z_MET 0x2
363 #define DCF_Z_MED 0x1
364 
365 /*-----------------------------------------------------------------------
366  * symbolic representation if the DCF77 data stream
367  */
368 static struct dcfparam
369 {
370 	unsigned char onebits[60];
371 	unsigned char zerobits[60];
372 } dcfparam =
373 {
374 	"###############RADMLS1248124P124812P1248121241248112481248P", /* 'ONE' representation */
375 	"--------------------s-------p------p----------------------p"  /* 'ZERO' representation */
376 };
377 
378 /*-----------------------------------------------------------------------
379  * extract a bitfield from DCF77 datastream
380  * All numeric fields are LSB first.
381  * buf holds a pointer to a DCF77 data buffer in symbolic
382  *     representation
383  * idx holds the index to the field description in rawdcfcode
384  */
385 static unsigned long
386 ext_bf(
387 	register unsigned char *buf,
388 	register int   idx
389 	)
390 {
391 	register unsigned long sum = 0;
392 	register int i, first;
393 
394 	first = rawdcfcode[idx].offset;
395 
396 	for (i = rawdcfcode[idx+1].offset - 1; i >= first; i--)
397 	{
398 		sum <<= 1;
399 		sum |= (buf[i] != dcfparam.zerobits[i]);
400 	}
401 	return sum;
402 }
403 
404 /*-----------------------------------------------------------------------
405  * check even parity integrity for a bitfield
406  *
407  * buf holds a pointer to a DCF77 data buffer in symbolic
408  *     representation
409  * idx holds the index to the field description in partab
410  */
411 static unsigned
412 pcheck(
413 	register unsigned char *buf,
414 	register int   idx
415 	)
416 {
417 	register int i,last;
418 	register unsigned psum = 1;
419 
420 	last = partab[idx+1].offset;
421 
422 	for (i = partab[idx].offset; i < last; i++)
423 	    psum ^= (buf[i] != dcfparam.zerobits[i]);
424 
425 	return psum;
426 }
427 
428 /*-----------------------------------------------------------------------
429  * convert a DCF77 data buffer into wall clock time + flags
430  *
431  * buffer holds a pointer to a DCF77 data buffer in symbolic
432  *        representation
433  * size   describes the length of DCF77 information in bits (represented
434  *        as chars in symbolic notation
435  * clock  points to a wall clock time description of the DCF77 data (result)
436  */
437 static unsigned long
438 convert_rawdcf(
439 	       unsigned char   *buffer,
440 	       int              size,
441 	       clocktime_t     *clock_time
442 	       )
443 {
444 	if (size < 57)
445 	{
446 		PRINTF("%-30s", "*** INCOMPLETE");
447 		return CVT_NONE;
448 	}
449 
450 	/*
451 	 * check Start and Parity bits
452 	 */
453 	if ((ext_bf(buffer, DCF_S) == 1) &&
454 	    pcheck(buffer, DCF_P_P1) &&
455 	    pcheck(buffer, DCF_P_P2) &&
456 	    pcheck(buffer, DCF_P_P3))
457 	{
458 		/*
459 		 * buffer OK - extract all fields and build wall clock time from them
460 		 */
461 
462 		clock_time->flags  = 0;
463 		clock_time->usecond= 0;
464 		clock_time->second = 0;
465 		clock_time->minute = ext_bf(buffer, DCF_M10);
466 		clock_time->minute = TIMES10(clock_time->minute) + ext_bf(buffer, DCF_M1);
467 		clock_time->hour   = ext_bf(buffer, DCF_H10);
468 		clock_time->hour   = TIMES10(clock_time->hour)   + ext_bf(buffer, DCF_H1);
469 		clock_time->day    = ext_bf(buffer, DCF_D10);
470 		clock_time->day    = TIMES10(clock_time->day)    + ext_bf(buffer, DCF_D1);
471 		clock_time->month  = ext_bf(buffer, DCF_MO0);
472 		clock_time->month  = TIMES10(clock_time->month)  + ext_bf(buffer, DCF_MO);
473 		clock_time->year   = ext_bf(buffer, DCF_Y10);
474 		clock_time->year   = TIMES10(clock_time->year)   + ext_bf(buffer, DCF_Y1);
475 		clock_time->wday   = ext_bf(buffer, DCF_DW);
476 
477 		/*
478 		 * determine offset to UTC by examining the time zone
479 		 */
480 		switch (ext_bf(buffer, DCF_Z))
481 		{
482 		    case DCF_Z_MET:
483 			clock_time->utcoffset = -60;
484 			break;
485 
486 		    case DCF_Z_MED:
487 			clock_time->flags     |= DCFB_DST;
488 			clock_time->utcoffset  = -120;
489 			break;
490 
491 		    default:
492 			PRINTF("%-30s", "*** BAD TIME ZONE");
493 			return CVT_FAIL|CVT_BADFMT;
494 		}
495 
496 		/*
497 		 * extract various warnings from DCF77
498 		 */
499 		if (ext_bf(buffer, DCF_A1))
500 		    clock_time->flags |= DCFB_ANNOUNCE;
501 
502 		if (ext_bf(buffer, DCF_A2))
503 		    clock_time->flags |= DCFB_LEAP;
504 
505 		if (ext_bf(buffer, DCF_R))
506 		    clock_time->flags |= DCFB_CALLBIT;
507 
508 		return CVT_OK;
509 	}
510 	else
511 	{
512 		/*
513 		 * bad format - not for us
514 		 */
515 		PRINTF("%-30s", "*** BAD FORMAT (invalid/parity)");
516 		return CVT_FAIL|CVT_BADFMT;
517 	}
518 }
519 
520 /*-----------------------------------------------------------------------
521  * raw dcf input routine - fix up 50 baud
522  * characters for 1/0 decision
523  */
524 static unsigned long
525 cvt_rawdcf(
526 	   unsigned char   *buffer,
527 	   int              size,
528 	   clocktime_t     *clock_time
529 	   )
530 {
531 	register unsigned char *s = buffer;
532 	register unsigned char *e = buffer + size;
533 	register unsigned char *b = dcfparam.onebits;
534 	register unsigned char *c = dcfparam.zerobits;
535 	register unsigned rtc = CVT_NONE;
536 	register unsigned int i, lowmax, highmax, cutoff, span;
537 #define BITS 9
538 	unsigned char     histbuf[BITS];
539 	/*
540 	 * the input buffer contains characters with runs of consecutive
541 	 * bits set. These set bits are an indication of the DCF77 pulse
542 	 * length. We assume that we receive the pulse at 50 Baud. Thus
543 	 * a 100ms pulse would generate a 4 bit train (20ms per bit and
544 	 * start bit)
545 	 * a 200ms pulse would create all zeroes (and probably a frame error)
546 	 *
547 	 * The basic idea is that on corret reception we must have two
548 	 * maxima in the pulse length distribution histogram. (one for
549 	 * the zero representing pulses and one for the one representing
550 	 * pulses)
551 	 * There will always be ones in the datastream, thus we have to see
552 	 * two maxima.
553 	 * The best point to cut for a 1/0 decision is the minimum between those
554 	 * between the maxima. The following code tries to find this cutoff point.
555 	 */
556 
557 	/*
558 	 * clear histogram buffer
559 	 */
560 	for (i = 0; i < BITS; i++)
561 	{
562 		histbuf[i] = 0;
563 	}
564 
565 	cutoff = 0;
566 	lowmax = 0;
567 
568 	/*
569 	 * convert sequences of set bits into bits counts updating
570 	 * the histogram alongway
571 	 */
572 	while (s < e)
573 	{
574 		register unsigned int ch = *s ^ 0xFF;
575 		/*
576 		 * check integrity and update histogramm
577 		 */
578 		if (!((ch+1) & ch) || !*s)
579 		{
580 			/*
581 			 * character ok
582 			 */
583 			for (i = 0; ch; i++)
584 			{
585 				ch >>= 1;
586 			}
587 
588 			*s = i;
589 			histbuf[i]++;
590 			cutoff += i;
591 			lowmax++;
592 		}
593 		else
594 		{
595 			/*
596 			 * invalid character (no consecutive bit sequence)
597 			 */
598 			DPRINTF(("parse: cvt_rawdcf: character check for 0x%x@%ld FAILED\n",
599 				 (u_int)*s, (long)(s - buffer)));
600 			*s = (unsigned char)~0;
601 			rtc = CVT_FAIL|CVT_BADFMT;
602 		}
603 		s++;
604 	}
605 
606 	/*
607 	 * first cutoff estimate (average bit count - must be between both
608 	 * maxima)
609 	 */
610 	if (lowmax)
611 	{
612 		cutoff /= lowmax;
613 	}
614 	else
615 	{
616 		cutoff = 4;	/* doesn't really matter - it'll fail anyway, but gives error output */
617 	}
618 
619 	DPRINTF(("parse: cvt_rawdcf: average bit count: %d\n", cutoff));
620 
621 	lowmax = 0;  /* weighted sum */
622 	highmax = 0; /* bitcount */
623 
624 	/*
625 	 * collect weighted sum of lower bits (left of initial guess)
626 	 */
627 	DPRINTF(("parse: cvt_rawdcf: histogram:"));
628 	for (i = 0; i <= cutoff; i++)
629 	{
630 		lowmax  += histbuf[i] * i;
631 		highmax += histbuf[i];
632 		DPRINTF((" %d", histbuf[i]));
633 	}
634 	DPRINTF((" <M>"));
635 
636 	/*
637 	 * round up
638 	 */
639 	lowmax += highmax / 2;
640 
641 	/*
642 	 * calculate lower bit maximum (weighted sum / bit count)
643 	 *
644 	 * avoid divide by zero
645 	 */
646 	if (highmax)
647 	{
648 		lowmax /= highmax;
649 	}
650 	else
651 	{
652 		lowmax = 0;
653 	}
654 
655 	highmax = 0; /* weighted sum of upper bits counts */
656 	cutoff = 0;  /* bitcount */
657 
658 	/*
659 	 * collect weighted sum of lower bits (right of initial guess)
660 	 */
661 	for (; i < BITS; i++)
662 	{
663 		highmax+=histbuf[i] * i;
664 		cutoff +=histbuf[i];
665 		DPRINTF((" %d", histbuf[i]));
666 	}
667 	DPRINTF(("\n"));
668 
669 	/*
670 	 * determine upper maximum (weighted sum / bit count)
671 	 */
672 	if (cutoff)
673 	{
674 		highmax /= cutoff;
675 	}
676 	else
677 	{
678 		highmax = BITS-1;
679 	}
680 
681 	/*
682 	 * following now holds:
683 	 * lowmax <= cutoff(initial guess) <= highmax
684 	 * best cutoff is the minimum nearest to higher bits
685 	 */
686 
687 	/*
688 	 * find the minimum between lowmax and highmax (detecting
689 	 * possibly a minimum span)
690 	 */
691 	span = cutoff = lowmax;
692 	for (i = lowmax; i <= highmax; i++)
693 	{
694 		if (histbuf[cutoff] > histbuf[i])
695 		{
696 			/*
697 			 * got a new minimum move beginning of minimum (cutoff) and
698 			 * end of minimum (span) there
699 			 */
700 			cutoff = span = i;
701 		}
702 		else
703 		    if (histbuf[cutoff] == histbuf[i])
704 		    {
705 			    /*
706 			     * minimum not better yet - but it spans more than
707 			     * one bit value - follow it
708 			     */
709 			    span = i;
710 		    }
711 	}
712 
713 	/*
714 	 * cutoff point for 1/0 decision is the middle of the minimum section
715 	 * in the histogram
716 	 */
717 	cutoff = (cutoff + span) / 2;
718 
719 	DPRINTF(("parse: cvt_rawdcf: lower maximum %d, higher maximum %d, cutoff %d\n", lowmax, highmax, cutoff));
720 
721 	/*
722 	 * convert the bit counts to symbolic 1/0 information for data conversion
723 	 */
724 	s = buffer;
725 	while ((s < e) && *c && *b)
726 	{
727 		if (*s == (unsigned char)~0)
728 		{
729 			/*
730 			 * invalid character
731 			 */
732 			*s = '?';
733 		}
734 		else
735 		{
736 			/*
737 			 * symbolic 1/0 representation
738 			 */
739 			*s = (*s >= cutoff) ? *b : *c;
740 		}
741 		s++;
742 		b++;
743 		c++;
744 	}
745 
746 	/*
747 	 * if everything went well so far return the result of the symbolic
748 	 * conversion routine else just the accumulated errors
749 	 */
750 	if (rtc != CVT_NONE)
751 	{
752 		PRINTF("%-30s", "*** BAD DATA");
753 	}
754 
755 	return (rtc == CVT_NONE) ? convert_rawdcf(buffer, size, clock_time) : rtc;
756 }
757 
758 /*-----------------------------------------------------------------------
759  * convert a wall clock time description of DCF77 to a Unix time (seconds
760  * since 1.1. 1970 UTC)
761  */
762 static time_t
763 dcf_to_unixtime(
764 		clocktime_t   *clock_time,
765 		unsigned *cvtrtc
766 		)
767 {
768 #define SETRTC(_X_)	{ if (cvtrtc) *cvtrtc = (_X_); }
769 	static int days_of_month[] =
770 	{
771 		0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
772 	};
773 	register int i;
774 	time_t t;
775 
776 	/*
777 	 * map 2 digit years to 19xx (DCF77 is a 20th century item)
778 	 */
779 	if ( clock_time->year < YEAR_PIVOT ) 	/* in case of	   Y2KFixes [ */
780 		clock_time->year += 100;	/* *year%100, make tm_year */
781 						/* *(do we need this?) */
782 	if ( clock_time->year < YEAR_BREAK )	/* (failsafe if) */
783 	    clock_time->year += 1900;				/* Y2KFixes ] */
784 
785 	/*
786 	 * must have been a really bad year code - drop it
787 	 */
788 	if (clock_time->year < (YEAR_PIVOT + 1900) )		/* Y2KFixes */
789 	{
790 		SETRTC(CVT_FAIL|CVT_BADDATE);
791 		return -1;
792 	}
793 	/*
794 	 * sorry, slow section here - but it's not time critical anyway
795 	 */
796 
797 	/*
798 	 * calculate days since 1970 (watching leap years)
799 	 */
800 	t = julian0( clock_time->year ) - julian0( 1970 );
801 
802   				/* month */
803 	if (clock_time->month <= 0 || clock_time->month > 12)
804 	{
805 		SETRTC(CVT_FAIL|CVT_BADDATE);
806 		return -1;		/* bad month */
807 	}
808 				/* adjust current leap year */
809 #if 0
810 	if (clock_time->month < 3 && days_per_year(clock_time->year) == 366)
811 	    t--;
812 #endif
813 
814 	/*
815 	 * collect days from months excluding the current one
816 	 */
817 	for (i = 1; i < clock_time->month; i++)
818 	{
819 		t += days_of_month[i];
820 	}
821 				/* day */
822 	if (clock_time->day < 1 || ((clock_time->month == 2 && days_per_year(clock_time->year) == 366) ?
823 			       clock_time->day > 29 : clock_time->day > days_of_month[clock_time->month]))
824 	{
825 		SETRTC(CVT_FAIL|CVT_BADDATE);
826 		return -1;		/* bad day */
827 	}
828 
829 	/*
830 	 * collect days from date excluding the current one
831 	 */
832 	t += clock_time->day - 1;
833 
834 				/* hour */
835 	if (clock_time->hour < 0 || clock_time->hour >= 24)
836 	{
837 		SETRTC(CVT_FAIL|CVT_BADTIME);
838 		return -1;		/* bad hour */
839 	}
840 
841 	/*
842 	 * calculate hours from 1. 1. 1970
843 	 */
844 	t = TIMES24(t) + clock_time->hour;
845 
846   				/* min */
847 	if (clock_time->minute < 0 || clock_time->minute > 59)
848 	{
849 		SETRTC(CVT_FAIL|CVT_BADTIME);
850 		return -1;		/* bad min */
851 	}
852 
853 	/*
854 	 * calculate minutes from 1. 1. 1970
855 	 */
856 	t = TIMES60(t) + clock_time->minute;
857 				/* sec */
858 
859 	/*
860 	 * calculate UTC in minutes
861 	 */
862 	t += clock_time->utcoffset;
863 
864 	if (clock_time->second < 0 || clock_time->second > 60)	/* allow for LEAPs */
865 	{
866 		SETRTC(CVT_FAIL|CVT_BADTIME);
867 		return -1;		/* bad sec */
868 	}
869 
870 	/*
871 	 * calculate UTC in seconds - phew !
872 	 */
873 	t  = TIMES60(t) + clock_time->second;
874 				/* done */
875 	return t;
876 }
877 
878 /*-----------------------------------------------------------------------
879  * cheap half baked 1/0 decision - for interactive operation only
880  */
881 static char
882 type(
883      unsigned int c
884      )
885 {
886 	c ^= 0xFF;
887 	return (c > 0xF);
888 }
889 
890 /*-----------------------------------------------------------------------
891  * week day representation
892  */
893 static const char *wday[8] =
894 {
895 	"??",
896 	"Mo",
897 	"Tu",
898 	"We",
899 	"Th",
900 	"Fr",
901 	"Sa",
902 	"Su"
903 };
904 
905 /*-----------------------------------------------------------------------
906  * generate a string representation for a timeval
907  */
908 static char *
909 pr_timeval(
910 	struct timeval *val
911 	)
912 {
913 	static char buf[20];
914 
915 	if (val->tv_sec == 0)
916 		snprintf(buf, sizeof(buf), "%c0.%06ld",
917 			 (val->tv_usec < 0) ? '-' : '+',
918 			 (long int)l_abs(val->tv_usec));
919 	else
920 		snprintf(buf, sizeof(buf), "%ld.%06ld",
921 			 (long int)val->tv_sec,
922 			 (long int)l_abs(val->tv_usec));
923 	return buf;
924 }
925 
926 /*-----------------------------------------------------------------------
927  * correct the current time by an offset by setting the time rigorously
928  */
929 static void
930 set_time(
931 	 struct timeval *offset
932 	 )
933 {
934 	struct timeval the_time;
935 
936 	if (no_set)
937 	    return;
938 
939 	LPRINTF("set_time: %s ", pr_timeval(offset));
940 	syslog(LOG_NOTICE, "setting time (offset %s)", pr_timeval(offset));
941 
942 	if (gettimeofday(&the_time, 0L) == -1)
943 	{
944 		perror("gettimeofday()");
945 	}
946 	else
947 	{
948 		timeradd(&the_time, offset);
949 		if (settimeofday(&the_time, 0L) == -1)
950 		{
951 			perror("settimeofday()");
952 		}
953 	}
954 }
955 
956 /*-----------------------------------------------------------------------
957  * slew the time by a given offset
958  */
959 static void
960 adj_time(
961 	 long offset
962 	 )
963 {
964 	struct timeval time_offset;
965 
966 	if (no_set)
967 	    return;
968 
969 	time_offset.tv_sec  = offset / 1000000;
970 	time_offset.tv_usec = offset % 1000000;
971 
972 	LPRINTF("adj_time: %ld us ", (long int)offset);
973 	if (adjtime(&time_offset, 0L) == -1)
974 	    perror("adjtime()");
975 }
976 
977 /*-----------------------------------------------------------------------
978  * read in a possibly previously written drift value
979  */
980 static void
981 read_drift(
982 	   const char *drift_file
983 	   )
984 {
985 	FILE *df;
986 
987 	df = fopen(drift_file, "r");
988 	if (df != NULL)
989 	{
990 		int idrift = 0, fdrift = 0;
991 
992 		if (2 != fscanf(df, "%4d.%03d", &idrift, &fdrift))
993 			LPRINTF("read_drift: trouble reading drift file");
994 		fclose(df);
995 		LPRINTF("read_drift: %d.%03d ppm ", idrift, fdrift);
996 
997 		accum_drift = idrift << USECSCALE;
998 		fdrift     = (fdrift << USECSCALE) / 1000;
999 		accum_drift += fdrift & (1<<USECSCALE);
1000 		LPRINTF("read_drift: drift_comp %ld ", (long int)accum_drift);
1001 	}
1002 }
1003 
1004 /*-----------------------------------------------------------------------
1005  * write out the current drift value
1006  */
1007 static void
1008 update_drift(
1009 	     const char *drift_file,
1010 	     long offset,
1011 	     time_t reftime
1012 	     )
1013 {
1014 	FILE *df;
1015 
1016 	df = fopen(drift_file, "w");
1017 	if (df != NULL)
1018 	{
1019 		int idrift = R_SHIFT(accum_drift, USECSCALE);
1020 		int fdrift = accum_drift & ((1<<USECSCALE)-1);
1021 
1022 		LPRINTF("update_drift: drift_comp %ld ", (long int)accum_drift);
1023 		fdrift = (fdrift * 1000) / (1<<USECSCALE);
1024 		fprintf(df, "%4d.%03d %c%ld.%06ld %.24s\n", idrift, fdrift,
1025 			(offset < 0) ? '-' : '+', (long int)(l_abs(offset) / 1000000),
1026 			(long int)(l_abs(offset) % 1000000), asctime(localtime(&reftime)));
1027 		fclose(df);
1028 		LPRINTF("update_drift: %d.%03d ppm ", idrift, fdrift);
1029 	}
1030 }
1031 
1032 /*-----------------------------------------------------------------------
1033  * process adjustments derived from the DCF77 observation
1034  * (controls clock PLL)
1035  */
1036 static void
1037 adjust_clock(
1038 	     struct timeval *offset,
1039 	     const char *drift_file,
1040 	     time_t reftime
1041 	     )
1042 {
1043 	struct timeval toffset;
1044 	register long usecoffset;
1045 	int tmp;
1046 
1047 	if (no_set)
1048 	    return;
1049 
1050 	if (skip_adjust)
1051 	{
1052 		skip_adjust = 0;
1053 		return;
1054 	}
1055 
1056 	toffset = *offset;
1057 	toffset.tv_sec  = l_abs(toffset.tv_sec);
1058 	toffset.tv_usec = l_abs(toffset.tv_usec);
1059 	if (toffset.tv_sec ||
1060 	    (!toffset.tv_sec && toffset.tv_usec > max_adj_offset_usec))
1061 	{
1062 		/*
1063 		 * hopeless - set the clock - and clear the timing
1064 		 */
1065 		set_time(offset);
1066 		clock_adjust = 0;
1067 		skip_adjust  = 1;
1068 		return;
1069 	}
1070 
1071 	usecoffset   = offset->tv_sec * 1000000 + offset->tv_usec;
1072 
1073 	clock_adjust = R_SHIFT(usecoffset, TIMECONSTANT);	/* adjustment to make for next period */
1074 
1075 	tmp = 0;
1076 	while (adjustments > (1 << tmp))
1077 	    tmp++;
1078 	adjustments = 0;
1079 	if (tmp > FREQ_WEIGHT)
1080 	    tmp = FREQ_WEIGHT;
1081 
1082 	accum_drift  += R_SHIFT(usecoffset << USECSCALE, TIMECONSTANT+TIMECONSTANT+FREQ_WEIGHT-tmp);
1083 
1084 	if (accum_drift > MAX_DRIFT)		/* clamp into interval */
1085 	    accum_drift = MAX_DRIFT;
1086 	else
1087 	    if (accum_drift < -MAX_DRIFT)
1088 		accum_drift = -MAX_DRIFT;
1089 
1090 	update_drift(drift_file, usecoffset, reftime);
1091 	LPRINTF("clock_adjust: %s, clock_adjust %ld, drift_comp %ld(%ld) ",
1092 		pr_timeval(offset),(long int) R_SHIFT(clock_adjust, USECSCALE),
1093 		(long int)R_SHIFT(accum_drift, USECSCALE), (long int)accum_drift);
1094 }
1095 
1096 /*-----------------------------------------------------------------------
1097  * adjust the clock by a small mount to simulate frequency correction
1098  */
1099 static void
1100 periodic_adjust(
1101 		void
1102 		)
1103 {
1104 	register long adjustment;
1105 
1106 	adjustments++;
1107 
1108 	adjustment = R_SHIFT(clock_adjust, PHASE_WEIGHT);
1109 
1110 	clock_adjust -= adjustment;
1111 
1112 	adjustment += R_SHIFT(accum_drift, USECSCALE+ADJINTERVAL);
1113 
1114 	adj_time(adjustment);
1115 }
1116 
1117 /*-----------------------------------------------------------------------
1118  * control synchronisation status (warnings) and do periodic adjusts
1119  * (frequency control simulation)
1120  */
1121 static void
1122 tick(
1123      int signum
1124      )
1125 {
1126 	static unsigned long last_notice = 0;
1127 
1128 #if !defined(HAVE_SIGACTION) && !defined(HAVE_SIGVEC)
1129 	(void)signal(SIGALRM, tick);
1130 #endif
1131 
1132 	periodic_adjust();
1133 
1134 	ticks += 1<<ADJINTERVAL;
1135 
1136 	if ((ticks - last_sync) > MAX_UNSYNC)
1137 	{
1138 		/*
1139 		 * not getting time for a while
1140 		 */
1141 		if (sync_state == SYNC)
1142 		{
1143 			/*
1144 			 * completely lost information
1145 			 */
1146 			sync_state = NO_SYNC;
1147 			syslog(LOG_INFO, "DCF77 reception lost (timeout)");
1148 			last_notice = ticks;
1149 		}
1150 		else
1151 		    /*
1152 		     * in NO_SYNC state - look whether its time to speak up again
1153 		     */
1154 		    if ((ticks - last_notice) > NOTICE_INTERVAL)
1155 		    {
1156 			    syslog(LOG_NOTICE, "still not synchronized to DCF77 - check receiver/signal");
1157 			    last_notice = ticks;
1158 		    }
1159 	}
1160 
1161 #ifndef ITIMER_REAL
1162 	(void) alarm(1<<ADJINTERVAL);
1163 #endif
1164 }
1165 
1166 /*-----------------------------------------------------------------------
1167  * break association from terminal to avoid catching terminal
1168  * or process group related signals (-> daemon operation)
1169  */
1170 static void
1171 detach(
1172        void
1173        )
1174 {
1175 #   ifdef HAVE_DAEMON
1176 	if (daemon(0, 0)) {
1177 		fprintf(stderr, "'daemon()' fails: %d(%s)\n",
1178 			errno, strerror(errno));
1179 	}
1180 #   else /* not HAVE_DAEMON */
1181 	if (fork())
1182 	    exit(0);
1183 
1184 	{
1185 		u_long s;
1186 		int max_fd;
1187 
1188 #if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
1189 		max_fd = sysconf(_SC_OPEN_MAX);
1190 #else /* HAVE_SYSCONF && _SC_OPEN_MAX */
1191 		max_fd = getdtablesize();
1192 #endif /* HAVE_SYSCONF && _SC_OPEN_MAX */
1193 		for (s = 0; s < max_fd; s++)
1194 		    (void) close((int)s);
1195 		(void) open("/", 0);
1196 		(void) dup2(0, 1);
1197 		(void) dup2(0, 2);
1198 #ifdef SYS_DOMAINOS
1199 		{
1200 			uid_$t puid;
1201 			status_$t st;
1202 
1203 			proc2_$who_am_i(&puid);
1204 			proc2_$make_server(&puid, &st);
1205 		}
1206 #endif /* SYS_DOMAINOS */
1207 #if defined(HAVE_SETPGID) || defined(HAVE_SETSID)
1208 # ifdef HAVE_SETSID
1209 		if (setsid() == (pid_t)-1)
1210 		    syslog(LOG_ERR, "dcfd: setsid(): %m");
1211 # else
1212 		if (setpgid(0, 0) == -1)
1213 		    syslog(LOG_ERR, "dcfd: setpgid(): %m");
1214 # endif
1215 #else /* HAVE_SETPGID || HAVE_SETSID */
1216 		{
1217 			int fid;
1218 
1219 			fid = open("/dev/tty", 2);
1220 			if (fid >= 0)
1221 			{
1222 				(void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0);
1223 				(void) close(fid);
1224 			}
1225 # ifdef HAVE_SETPGRP_0
1226 			(void) setpgrp();
1227 # else /* HAVE_SETPGRP_0 */
1228 			(void) setpgrp(0, getpid());
1229 # endif /* HAVE_SETPGRP_0 */
1230 		}
1231 #endif /* HAVE_SETPGID || HAVE_SETSID */
1232 	}
1233 #endif /* not HAVE_DAEMON */
1234 }
1235 
1236 /*-----------------------------------------------------------------------
1237  * list possible arguments and options
1238  */
1239 static void
1240 usage(
1241       char *program
1242       )
1243 {
1244   fprintf(stderr, "usage: %s [-n] [-f] [-l] [-t] [-i] [-o] [-d <drift_file>] [-D <input delay>] <device>\n", program);
1245 	fprintf(stderr, "\t-n              do not change time\n");
1246 	fprintf(stderr, "\t-i              interactive\n");
1247 	fprintf(stderr, "\t-t              trace (print all datagrams)\n");
1248 	fprintf(stderr, "\t-f              print all databits (includes PTB private data)\n");
1249 	fprintf(stderr, "\t-l              print loop filter debug information\n");
1250 	fprintf(stderr, "\t-o              print offet average for current minute\n");
1251 	fprintf(stderr, "\t-Y              make internal Y2K checks then exit\n");	/* Y2KFixes */
1252 	fprintf(stderr, "\t-d <drift_file> specify alternate drift file\n");
1253 	fprintf(stderr, "\t-D <input delay>specify delay from input edge to processing in micro seconds\n");
1254 }
1255 
1256 /*-----------------------------------------------------------------------
1257  * check_y2k() - internal check of Y2K logic
1258  *	(a lot of this logic lifted from ../ntpd/check_y2k.c)
1259  */
1260 static int
1261 check_y2k( void )
1262 {
1263     int  year;			/* current working year */
1264     int  year0 = 1900;		/* sarting year for NTP time */
1265     int  yearend;		/* ending year we test for NTP time.
1266 				    * 32-bit systems: through 2036, the
1267 				      **year in which NTP time overflows.
1268 				    * 64-bit systems: a reasonable upper
1269 				      **limit (well, maybe somewhat beyond
1270 				      **reasonable, but well before the
1271 				      **max time, by which time the earth
1272 				      **will be dead.) */
1273     time_t Time;
1274     struct tm LocalTime;
1275 
1276     int Fatals, Warnings;
1277 #define Error(year) if ( (year)>=2036 && LocalTime.tm_year < 110 ) \
1278 	Warnings++; else Fatals++
1279 
1280     Fatals = Warnings = 0;
1281 
1282     Time = time( (time_t *)NULL );
1283     LocalTime = *localtime( &Time );
1284 
1285     year = ( sizeof( u_long ) > 4 ) 	/* save max span using year as temp */
1286 		? ( 400 * 3 ) 		/* three greater gregorian cycles */
1287 		: ((int)(0x7FFFFFFF / 365.242 / 24/60/60)* 2 ); /*32-bit limit*/
1288 			/* NOTE: will automacially expand test years on
1289 			 * 64 bit machines.... this may cause some of the
1290 			 * existing ntp logic to fail for years beyond
1291 			 * 2036 (the current 32-bit limit). If all checks
1292 			 * fail ONLY beyond year 2036 you may ignore such
1293 			 * errors, at least for a decade or so. */
1294     yearend = year0 + year;
1295 
1296     year = 1900+YEAR_PIVOT;
1297     printf( "  starting year %04d\n", (int) year );
1298     printf( "  ending year   %04d\n", (int) yearend );
1299 
1300     for ( ; year < yearend; year++ )
1301     {
1302 	clocktime_t  ct;
1303 	time_t	     Observed;
1304 	time_t	     Expected;
1305 	unsigned     Flag;
1306 	unsigned long t;
1307 
1308 	ct.day = 1;
1309 	ct.month = 1;
1310 	ct.year = year;
1311 	ct.hour = ct.minute = ct.second = ct.usecond = 0;
1312 	ct.utcoffset = 0;
1313 	ct.flags = 0;
1314 
1315 	Flag = 0;
1316  	Observed = dcf_to_unixtime( &ct, &Flag );
1317 		/* seems to be a clone of parse_to_unixtime() with
1318 		 * *a minor difference to arg2 type */
1319 	if ( ct.year != year )
1320 	{
1321 	    fprintf( stdout,
1322 	       "%04d: dcf_to_unixtime(,%d) CORRUPTED ct.year: was %d\n",
1323 	       (int)year, (int)Flag, (int)ct.year );
1324 	    Error(year);
1325 	    break;
1326 	}
1327 	t = julian0(year) - julian0(1970);	/* Julian day from 1970 */
1328 	Expected = t * 24 * 60 * 60;
1329 	if ( Observed != Expected  ||  Flag )
1330 	{   /* time difference */
1331 	    fprintf( stdout,
1332 	       "%04d: dcf_to_unixtime(,%d) FAILURE: was=%lu s/b=%lu  (%ld)\n",
1333 	       year, (int)Flag,
1334 	       (unsigned long)Observed, (unsigned long)Expected,
1335 	       ((long)Observed - (long)Expected) );
1336 	    Error(year);
1337 	    break;
1338 	}
1339 
1340     }
1341 
1342     return ( Fatals );
1343 }
1344 
1345 /*--------------------------------------------------
1346  * rawdcf_init - set up modem lines for RAWDCF receivers
1347  */
1348 #if defined(TIOCMSET) && (defined(TIOCM_DTR) || defined(CIOCM_DTR))
1349 static void
1350 rawdcf_init(
1351 	int fd
1352 	)
1353 {
1354 	/*
1355 	 * You can use the RS232 to supply the power for a DCF77 receiver.
1356 	 * Here a voltage between the DTR and the RTS line is used. Unfortunately
1357 	 * the name has changed from CIOCM_DTR to TIOCM_DTR recently.
1358 	 */
1359 
1360 #ifdef TIOCM_DTR
1361 	int sl232 = TIOCM_DTR;	/* turn on DTR for power supply */
1362 #else
1363 	int sl232 = CIOCM_DTR;	/* turn on DTR for power supply */
1364 #endif
1365 
1366 	if (ioctl(fd, TIOCMSET, (caddr_t)&sl232) == -1)
1367 	{
1368 		syslog(LOG_NOTICE, "rawdcf_init: WARNING: ioctl(fd, TIOCMSET, [C|T]IOCM_DTR): %m");
1369 	}
1370 }
1371 #else
1372 static void
1373 rawdcf_init(
1374 	    int fd
1375 	)
1376 {
1377 	syslog(LOG_NOTICE, "rawdcf_init: WARNING: OS interface incapable of setting DTR to power DCF modules");
1378 }
1379 #endif  /* DTR initialisation type */
1380 
1381 /*-----------------------------------------------------------------------
1382  * main loop - argument interpreter / setup / main loop
1383  */
1384 int
1385 main(
1386      int argc,
1387      char **argv
1388      )
1389 {
1390 	unsigned char c;
1391 	char **a = argv;
1392 	int  ac = argc;
1393 	char *file = NULL;
1394 	const char *drift_file = "/etc/dcfd.drift";
1395 	int fd;
1396 	int offset = 15;
1397 	int offsets = 0;
1398 	int delay = DEFAULT_DELAY;	/* average delay from input edge to time stamping */
1399 	int trace = 0;
1400 	int errs = 0;
1401 
1402 	/*
1403 	 * process arguments
1404 	 */
1405 	while (--ac)
1406 	{
1407 		char *arg = *++a;
1408 		if (*arg == '-')
1409 		    while ((c = *++arg))
1410 			switch (c)
1411 			{
1412 			    case 't':
1413 				trace = 1;
1414 				interactive = 1;
1415 				break;
1416 
1417 			    case 'f':
1418 				offset = 0;
1419 				interactive = 1;
1420 				break;
1421 
1422 			    case 'l':
1423 				loop_filter_debug = 1;
1424 				offsets = 1;
1425 				interactive = 1;
1426 				break;
1427 
1428 			    case 'n':
1429 				no_set = 1;
1430 				break;
1431 
1432 			    case 'o':
1433 				offsets = 1;
1434 				interactive = 1;
1435 				break;
1436 
1437 			    case 'i':
1438 				interactive = 1;
1439 				break;
1440 
1441 			    case 'D':
1442 				if (ac > 1)
1443 				{
1444 					delay = atoi(*++a);
1445 					ac--;
1446 				}
1447 				else
1448 				{
1449 					fprintf(stderr, "%s: -D requires integer argument\n", argv[0]);
1450 					errs=1;
1451 				}
1452 				break;
1453 
1454 			    case 'd':
1455 				if (ac > 1)
1456 				{
1457 					drift_file = *++a;
1458 					ac--;
1459 				}
1460 				else
1461 				{
1462 					fprintf(stderr, "%s: -d requires file name argument\n", argv[0]);
1463 					errs=1;
1464 				}
1465 				break;
1466 
1467 			    case 'Y':
1468 				errs=check_y2k();
1469 				exit( errs ? 1 : 0 );
1470 
1471 			    default:
1472 				fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
1473 				errs=1;
1474 				break;
1475 			}
1476 		else
1477 		    if (file == NULL)
1478 			file = arg;
1479 		    else
1480 		    {
1481 			    fprintf(stderr, "%s: device specified twice\n", argv[0]);
1482 			    errs=1;
1483 		    }
1484 	}
1485 
1486 	if (errs)
1487 	{
1488 		usage(argv[0]);
1489 		exit(1);
1490 	}
1491 	else
1492 	    if (file == NULL)
1493 	    {
1494 		    fprintf(stderr, "%s: device not specified\n", argv[0]);
1495 		    usage(argv[0]);
1496 		    exit(1);
1497 	    }
1498 
1499 	errs = LINES+1;
1500 
1501 	/*
1502 	 * get access to DCF77 tty port
1503 	 */
1504 	fd = open(file, O_RDONLY);
1505 	if (fd == -1)
1506 	{
1507 		perror(file);
1508 		exit(1);
1509 	}
1510 	else
1511 	{
1512 		int i, rrc;
1513 		struct timeval t, tt, tlast;
1514 		struct timeval timeout;
1515 		struct timeval phase;
1516 		struct timeval time_offset;
1517 		char pbuf[61];		/* printable version */
1518 		char buf[61];		/* raw data */
1519 		clocktime_t clock_time;	/* wall clock time */
1520 		time_t utc_time = 0;
1521 		time_t last_utc_time = 0;
1522 		long usecerror = 0;
1523 		long lasterror = 0;
1524 #if defined(HAVE_TERMIOS_H) || defined(STREAM)
1525 		struct termios term;
1526 #else  /* not HAVE_TERMIOS_H || STREAM */
1527 # if defined(HAVE_TERMIO_H) || defined(HAVE_SYSV_TTYS)
1528 		struct termio term;
1529 # endif/* HAVE_TERMIO_H || HAVE_SYSV_TTYS */
1530 #endif /* not HAVE_TERMIOS_H || STREAM */
1531 		unsigned int rtc = CVT_NONE;
1532 
1533 		rawdcf_init(fd);
1534 
1535 		timeout.tv_sec  = 1;
1536 		timeout.tv_usec = 500000;
1537 
1538 		phase.tv_sec    = 0;
1539 		phase.tv_usec   = delay;
1540 
1541 		/*
1542 		 * setup TTY (50 Baud, Read, 8Bit, No Hangup, 1 character IO)
1543 		 */
1544 		if (TTY_GETATTR(fd,  &term) == -1)
1545 		{
1546 			perror("tcgetattr");
1547 			exit(1);
1548 		}
1549 
1550 		memset(term.c_cc, 0, sizeof(term.c_cc));
1551 		term.c_cc[VMIN] = 1;
1552 #ifdef NO_PARENB_IGNPAR
1553 		term.c_cflag = CS8|CREAD|CLOCAL;
1554 #else
1555 		term.c_cflag = CS8|CREAD|CLOCAL|PARENB;
1556 #endif
1557 		term.c_iflag = IGNPAR;
1558 		term.c_oflag = 0;
1559 		term.c_lflag = 0;
1560 
1561 		cfsetispeed(&term, B50);
1562 		cfsetospeed(&term, B50);
1563 
1564 		if (TTY_SETATTR(fd, &term) == -1)
1565 		{
1566 			perror("tcsetattr");
1567 			exit(1);
1568 		}
1569 
1570 		/*
1571 		 * lose terminal if in daemon operation
1572 		 */
1573 		if (!interactive)
1574 		    detach();
1575 
1576 		/*
1577 		 * get syslog() initialized
1578 		 */
1579 #ifdef LOG_DAEMON
1580 		openlog("dcfd", LOG_PID, LOG_DAEMON);
1581 #else
1582 		openlog("dcfd", LOG_PID);
1583 #endif
1584 
1585 		/*
1586 		 * setup periodic operations (state control / frequency control)
1587 		 */
1588 #ifdef HAVE_SIGACTION
1589 		{
1590 			struct sigaction act;
1591 
1592 # ifdef HAVE_SA_SIGACTION_IN_STRUCT_SIGACTION
1593 			act.sa_sigaction = (void (*) (int, siginfo_t *, void *))0;
1594 # endif /* HAVE_SA_SIGACTION_IN_STRUCT_SIGACTION */
1595 			act.sa_handler   = tick;
1596 			sigemptyset(&act.sa_mask);
1597 			act.sa_flags     = 0;
1598 
1599 			if (sigaction(SIGALRM, &act, (struct sigaction *)0) == -1)
1600 			{
1601 				syslog(LOG_ERR, "sigaction(SIGALRM): %m");
1602 				exit(1);
1603 			}
1604 		}
1605 #else
1606 #ifdef HAVE_SIGVEC
1607 		{
1608 			struct sigvec vec;
1609 
1610 			vec.sv_handler   = tick;
1611 			vec.sv_mask      = 0;
1612 			vec.sv_flags     = 0;
1613 
1614 			if (sigvec(SIGALRM, &vec, (struct sigvec *)0) == -1)
1615 			{
1616 				syslog(LOG_ERR, "sigvec(SIGALRM): %m");
1617 				exit(1);
1618 			}
1619 		}
1620 #else
1621 		(void) signal(SIGALRM, tick);
1622 #endif
1623 #endif
1624 
1625 #ifdef ITIMER_REAL
1626 		{
1627 			struct itimerval it;
1628 
1629 			it.it_interval.tv_sec  = 1<<ADJINTERVAL;
1630 			it.it_interval.tv_usec = 0;
1631 			it.it_value.tv_sec     = 1<<ADJINTERVAL;
1632 			it.it_value.tv_usec    = 0;
1633 
1634 			if (setitimer(ITIMER_REAL, &it, (struct itimerval *)0) == -1)
1635 			{
1636 				syslog(LOG_ERR, "setitimer: %m");
1637 				exit(1);
1638 			}
1639 		}
1640 #else
1641 		(void) alarm(1<<ADJINTERVAL);
1642 #endif
1643 
1644 		PRINTF("  DCF77 monitor %s - Copyright (C) 1993-2005 by Frank Kardel\n\n", revision);
1645 
1646 		pbuf[60] = '\0';
1647 		for ( i = 0; i < 60; i++)
1648 		    pbuf[i] = '.';
1649 
1650 		read_drift(drift_file);
1651 
1652 		/*
1653 		 * what time is it now (for interval measurement)
1654 		 */
1655 		gettimeofday(&tlast, 0L);
1656 		i = 0;
1657 		/*
1658 		 * loop until input trouble ...
1659 		 */
1660 		do
1661 		{
1662 			/*
1663 			 * get an impulse
1664 			 */
1665 			while ((rrc = read(fd, &c, 1)) == 1)
1666 			{
1667 				gettimeofday(&t, 0L);
1668 				tt = t;
1669 				timersub(&t, &tlast);
1670 
1671 				if (errs > LINES)
1672 				{
1673 					PRINTF("  %s", &"PTB private....RADMLSMin....PHour..PMDay..DayMonthYear....P\n"[offset]);
1674 					PRINTF("  %s", &"---------------RADMLS1248124P124812P1248121241248112481248P\n"[offset]);
1675 					errs = 0;
1676 				}
1677 
1678 				/*
1679 				 * timeout -> possible minute mark -> interpretation
1680 				 */
1681 				if (timercmp(&t, &timeout, >))
1682 				{
1683 					PRINTF("%c %.*s ", pat[i % (sizeof(pat)-1)], 59 - offset, &pbuf[offset]);
1684 
1685 					if ((rtc = cvt_rawdcf((unsigned char *)buf, i, &clock_time)) != CVT_OK)
1686 					{
1687 						/*
1688 						 * this data was bad - well - forget synchronisation for now
1689 						 */
1690 						PRINTF("\n");
1691 						if (sync_state == SYNC)
1692 						{
1693 							sync_state = NO_SYNC;
1694 							syslog(LOG_INFO, "DCF77 reception lost (bad data)");
1695 						}
1696 						errs++;
1697 					}
1698 					else
1699 					    if (trace)
1700 					    {
1701 						    PRINTF("\r  %.*s ", 59 - offset, &buf[offset]);
1702 					    }
1703 
1704 
1705 					buf[0] = c;
1706 
1707 					/*
1708 					 * collect first character
1709 					 */
1710 					if (((c^0xFF)+1) & (c^0xFF))
1711 					    pbuf[0] = '?';
1712 					else
1713 					    pbuf[0] = type(c) ? '#' : '-';
1714 
1715 					for ( i = 1; i < 60; i++)
1716 					    pbuf[i] = '.';
1717 
1718 					i = 0;
1719 				}
1720 				else
1721 				{
1722 					/*
1723 					 * collect character
1724 					 */
1725 					buf[i] = c;
1726 
1727 					/*
1728 					 * initial guess (usually correct)
1729 					 */
1730 					if (((c^0xFF)+1) & (c^0xFF))
1731 					    pbuf[i] = '?';
1732 					else
1733 					    pbuf[i] = type(c) ? '#' : '-';
1734 
1735 					PRINTF("%c %.*s ", pat[i % (sizeof(pat)-1)], 59 - offset, &pbuf[offset]);
1736 				}
1737 
1738 				if (i == 0 && rtc == CVT_OK)
1739 				{
1740 					/*
1741 					 * we got a good time code here - try to convert it to
1742 					 * UTC
1743 					 */
1744 					if ((utc_time = dcf_to_unixtime(&clock_time, &rtc)) == -1)
1745 					{
1746 						PRINTF("*** BAD CONVERSION\n");
1747 					}
1748 
1749 					if (utc_time != (last_utc_time + 60))
1750 					{
1751 						/*
1752 						 * well, two successive sucessful telegrams are not 60 seconds
1753 						 * apart
1754 						 */
1755 						PRINTF("*** NO MINUTE INC\n");
1756 						if (sync_state == SYNC)
1757 						{
1758 							sync_state = NO_SYNC;
1759 							syslog(LOG_INFO, "DCF77 reception lost (data mismatch)");
1760 						}
1761 						errs++;
1762 						rtc = CVT_FAIL|CVT_BADTIME|CVT_BADDATE;
1763 					}
1764 					else
1765 					    usecerror = 0;
1766 
1767 					last_utc_time = utc_time;
1768 				}
1769 
1770 				if (rtc == CVT_OK)
1771 				{
1772 					if (i == 0)
1773 					{
1774 						/*
1775 						 * valid time code - determine offset and
1776 						 * note regained reception
1777 						 */
1778 						last_sync = ticks;
1779 						if (sync_state == NO_SYNC)
1780 						{
1781 							syslog(LOG_INFO, "receiving DCF77");
1782 						}
1783 						else
1784 						{
1785 							/*
1786 							 * we had at least one minute SYNC - thus
1787 							 * last error is valid
1788 							 */
1789 							time_offset.tv_sec  = lasterror / 1000000;
1790 							time_offset.tv_usec = lasterror % 1000000;
1791 							adjust_clock(&time_offset, drift_file, utc_time);
1792 						}
1793 						sync_state = SYNC;
1794 					}
1795 
1796 					time_offset.tv_sec  = utc_time + i;
1797 					time_offset.tv_usec = 0;
1798 
1799 					timeradd(&time_offset, &phase);
1800 
1801 					usecerror += (time_offset.tv_sec - tt.tv_sec) * 1000000 + time_offset.tv_usec
1802 						-tt.tv_usec;
1803 
1804 					/*
1805 					 * output interpreted DCF77 data
1806 					 */
1807 					PRINTF(offsets ? "%s, %2ld:%02ld:%02d, %ld.%02ld.%02ld, <%s%s%s%s> (%c%ld.%06lds)" :
1808 					       "%s, %2ld:%02ld:%02d, %ld.%02ld.%02ld, <%s%s%s%s>",
1809 					       wday[clock_time.wday],
1810 					       clock_time.hour, clock_time.minute, i, clock_time.day, clock_time.month,
1811 					       clock_time.year,
1812 					       (clock_time.flags & DCFB_CALLBIT) ? "R" : "_",
1813 					       (clock_time.flags & DCFB_ANNOUNCE) ? "A" : "_",
1814 					       (clock_time.flags & DCFB_DST) ? "D" : "_",
1815 					       (clock_time.flags & DCFB_LEAP) ? "L" : "_",
1816 					       (lasterror < 0) ? '-' : '+', l_abs(lasterror) / 1000000, l_abs(lasterror) % 1000000
1817 					       );
1818 
1819 					if (trace && (i == 0))
1820 					{
1821 						PRINTF("\n");
1822 						errs++;
1823 					}
1824 					lasterror = usecerror / (i+1);
1825 				}
1826 				else
1827 				{
1828 					lasterror = 0; /* we cannot calculate phase errors on bad reception */
1829 				}
1830 
1831 				PRINTF("\r");
1832 
1833 				if (i < 60)
1834 				{
1835 					i++;
1836 				}
1837 
1838 				tlast = tt;
1839 
1840 				if (interactive)
1841 				    fflush(stdout);
1842 			}
1843 		} while ((rrc == -1) && (errno == EINTR));
1844 
1845 		/*
1846 		 * lost IO - sorry guys
1847 		 */
1848 		syslog(LOG_ERR, "TERMINATING - cannot read from device %s (%m)", file);
1849 
1850 		(void)close(fd);
1851 	}
1852 
1853 	closelog();
1854 
1855 	return 0;
1856 }
1857 
1858 /*
1859  * History:
1860  *
1861  * dcfd.c,v
1862  * Revision 4.18  2005/10/07 22:08:18  kardel
1863  * make dcfd.c compile on NetBSD 3.99.9 again (configure/sigvec compatibility fix)
1864  *
1865  * Revision 4.17.2.1  2005/10/03 19:15:16  kardel
1866  * work around configure not detecting a missing sigvec compatibility
1867  * interface on NetBSD 3.99.9 and above
1868  *
1869  * Revision 4.17  2005/08/10 10:09:44  kardel
1870  * output revision information
1871  *
1872  * Revision 4.16  2005/08/10 06:33:25  kardel
1873  * cleanup warnings
1874  *
1875  * Revision 4.15  2005/08/10 06:28:45  kardel
1876  * fix setting of baud rate
1877  *
1878  * Revision 4.14  2005/04/16 17:32:10  kardel
1879  * update copyright
1880  *
1881  * Revision 4.13  2004/11/14 15:29:41  kardel
1882  * support PPSAPI, upgrade Copyright to Berkeley style
1883  *
1884  */
1885