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