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