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