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