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