xref: /freebsd/contrib/ntp/ntpd/refclock_acts.c (revision daf1cffce2e07931f27c6c6998652e90df6ba87e)
1 /*
2  * refclock_acts - clock driver for the NIST/PTB Automated Computer Time
3  *	Service aka Amalgamated Containerized Trash Service (ACTS)
4  */
5 
6 #ifdef HAVE_CONFIG_H
7 #include <config.h>
8 #endif
9 
10 #if defined(REFCLOCK) && (defined(CLOCK_ACTS) || defined(CLOCK_PTBACTS))
11 
12 #include <stdio.h>
13 #include <ctype.h>
14 #include <sys/time.h>
15 #ifdef HAVE_SYS_IOCTL_H
16 # include <sys/ioctl.h>
17 #endif /* HAVE_SYS_IOCTL_H */
18 
19 #include "ntpd.h"
20 #include "ntp_io.h"
21 #include "ntp_unixtime.h"
22 #include "ntp_refclock.h"
23 #include "ntp_stdlib.h"
24 #include "ntp_control.h"
25 
26 /* MUST BE AFTER LAST #include <config.h> !!! */
27 
28 #if defined(CLOCK_ACTS) && defined(CLOCK_PTBACTS)
29 # if defined(KEEPPTBACTS)
30 #   undef CLOCK_ACTS
31 # else /* not KEEPPTBACTS */
32 #   undef CLOCK_PTBACTS
33 # endif /* not KEEPPTBACTS */
34 #endif /* CLOCK_ACTS && CLOCK_PTBACTS */
35 
36 /*
37  * This driver supports the NIST Automated Computer Time Service (ACTS).
38  * It periodically dials a prespecified telephone number, receives the
39  * NIST timecode data and calculates the local clock correction. It is
40  * designed primarily for use as a backup when neither a radio clock nor
41  * connectivity to Internet time servers is available. For the best
42  * accuracy, the individual telephone line/modem delay needs to be
43  * calibrated using outside sources.
44  *
45  * The ACTS is located at NIST Boulder, CO, telephone 303 494 4774. A
46  * toll call from a residence telephone in Newark, DE, costs between 14
47  * and 27 cents, depending on time of day, and from a campus telephone
48  * between 3 and 4 cents, although it is not clear what carrier and time
49  * of day discounts apply in this case. The modem dial string will
50  * differ depending on local telephone configuration, etc., and is
51  * specified by the phone command in the configuration file. The
52  * argument to this command is an AT command for a Hayes compatible
53  * modem.
54  *
55  * The accuracy produced by this driver should be in the range of a
56  * millisecond or two, but may need correction due to the delay
57  * characteristics of the individual modem involved. For undetermined
58  * reasons, some modems work with the ACTS echo-delay measurement scheme
59  * and some don't. This driver tries to do the best it can with what it
60  * gets. Initial experiments with a Practical Peripherals 9600SA modem
61  * here in Delaware suggest an accuracy of a millisecond or two can be
62  * achieved without the scheme by using a fudge time1 value of 65.0 ms.
63  * In either case, the dispersion for a single call involving ten
64  * samples is about 1.3 ms.
65  *
66  * The driver can operate in either of three modes, as determined by
67  * the mode parameter in the server configuration command. In mode 0
68  * (automatic) the driver operates continuously at intervals depending
69  * on the prediction error, as measured by the driver, usually in the
70  * order of several hours. In mode 1 (backup) the driver is enabled in
71  * automatic mode only when no other source of synchronization is
72  * available and when more than MAXOUTAGE (3600 s) have elapsed since
73  * last synchronized by other sources. In mode 2 (manual) the driver
74  * operates only when enabled using a fudge flags switch, as described
75  * below.
76  *
77  * For reliable call management, this driver requires a 1200-bps modem
78  * with a Hayes-compatible command set and control over the modem data
79  * terminal ready (DTR) control line. Present restrictions require the
80  * use of a POSIX-compatible programming interface, although other
81  * interfaces may work as well. The modem setup string is hard-coded in
82  * the driver and may require changes for nonstandard modems or special
83  * circumstances.
84  *
85  * Further information can be found in the README.refclock file in the
86  * ntp - Version 3 distribution.
87  *
88  * Fudge Factors
89  *
90  * Ordinarily, the propagation time correction is computed automatically
91  * by ACTS and the driver. When this is not possible or erratic due to
92  * individual modem characteristics, the fudge flag2 switch should be
93  * set to disable the ACTS echo-delay scheme. In any case, the fudge
94  * time1 parameter can be used to adjust the propagation delay as
95  * required.
96  *
97  * The ACTS call interval is determined in one of three ways. In manual
98  * mode a call is initiated by setting fudge flag1 using ntpdc, either
99  * manually or via a cron job. In AUTO mode this flag is set by the peer
100  * timer, which is controlled by the sys_poll variable in response to
101  * measured errors. In backup mode the driver is ordinarily asleep, but
102  * awakes (in auto mode) if all other synchronization sources are lost.
103  * In either auto or backup modes, the call interval increases as long
104  * as the measured errors do not exceed the value of the fudge time2
105  * parameter.
106  *
107  * When the fudge flag1 is set, the ACTS calling program is activated.
108  * This program dials each number listed in the phones command of the
109  * configuration file in turn. If a call attempt fails, the next number
110  * in the list is dialed. The fudge flag1 and counter are reset and the
111  * calling program terminated if (a) a valid clock update has been
112  * determined, (b) no more numbers remain in the list, (c) a device
113  * fault or timeout occurs or (d) fudge flag1 is reset manually using
114  * ntpdc.
115  *
116  * In automatic and backup modes, the driver determines the call
117  * interval using a procedure depending on the measured prediction
118  * error and the fudge time2 parameter. If the error exceeds time2 for a
119  * number of times depending on the current interval, the interval is
120  * decreased, but not less than about 1000 s. If the error is less than
121  * time2 for some number of times, the interval is increased, but not
122  * more than about 18 h. With the default value of zero for fudge time2,
123  * the interval will increase from 1000 s to the 4000-8000-s range, in
124  * which the expected accuracy should be in the 1-2-ms range. Setting
125  * fudge time2 to a large value, like 0.1 s, may result in errors of
126  * that order, but increase the call interval to the maximum. The exact
127  * value for each configuration will depend on the modem and operating
128  * system involved, so some experimentation may be necessary.
129  */
130 
131 /*
132  * DESCRIPTION OF THE AUTOMATED COMPUTER TELEPHONE SERVICE (ACTS)
133  * (reformatted from ACTS on-line computer help information)
134  *
135  * The following is transmitted (at 1200 baud) following completion of
136  * the telephone connection.
137  *
138  * National Institute of Standards and Technology
139  * Telephone Time Service, Generator 3B
140  * Enter question mark "?" for HELP
141  *                         D  L D
142  *  MJD  YR MO DA H  M  S  ST S UT1 msADV        <OTM>
143  * 47999 90-04-18 21:39:15 50 0 +.1 045.0 UTC(NIST) *
144  * 47999 90-04-18 21:39:16 50 0 +.1 045.0 UTC(NIST) *
145  * 47999 90-04-18 21:39:17 50 0 +.1 045.0 UTC(NIST) *
146  * 47999 90-04-18 21:39:18 50 0 +.1 045.0 UTC(NIST) *
147  * 47999 90-04-18 21:39:19 50 0 +.1 037.6 UTC(NIST) #
148  * 47999 90-04-18 21:39:20 50 0 +.1 037.6 UTC(NIST) #
149  * etc..etc...etc.......
150  *
151  * UTC = Universal Time Coordinated, the official world time referred to
152  * the zero meridian.
153  *
154  * DST	Daylight savings time characters, valid for the continental
155  *	U.S., are set as follows:
156  *
157  *	00	We are on standard time (ST).
158  *	01-49	Now on DST, go to ST when your local time is 2:00 am and
159  *		the count is 01. The count is decremented daily at 00
160  *		(UTC).
161  *	50	We are on DST.
162  *	51-99	Now on ST, go to DST when your local time is 2:00 am and
163  *		the count is 51. The count is decremented daily at 00
164  *		(UTC).
165  *
166  *	The two DST characters provide up to 48 days advance notice of a
167  *	change in time. The count remains at 00 or 50 at other times.
168  *
169  * LS	Leap second flag is set to "1" to indicate that a leap second is
170  *	to be added as 23:59:60 (UTC) on the last day of the current UTC
171  *	month. The LS flag will be reset to "0" starting with 23:59:60
172  *	(UTC). The flag will remain on for the entire month before the
173  *	second is added. Leap seconds are added as needed at the end of
174  *	any month. Usually June and/or December are chosen.
175  *
176  *	The leap second flag will be set to a "2" to indicate that a
177  *	leap second is to be deleted at 23:59:58--00:00:00 on the last
178  *	day of the current month. (This latter provision is included per
179  *	international recommendation, however it is not likely to be
180  *	required in the near future.)
181  *
182  * DUT1	Approximate difference between earth rotation time (UT1) and
183  *	UTC, in steps of 0.1 second: DUT1 = UT1 - UTC.
184  *
185  * MJD	Modified Julian Date, often used to tag certain scientific data.
186  *
187  * The full time format is sent at 1200 baud, 8 bit, 1 stop, no parity.
188  * The format at 300 Baud is also 8 bit, 1 stop, no parity. At 300 Baud
189  * the MJD and DUT1 values are deleted and the time is transmitted only
190  * on even seconds.
191  *
192  * Maximum on line time will be 56 seconds. If all lines are busy at any
193  * time, the oldest call will be terminated if it has been on line more
194  * than 28 seconds, otherwise, the call that first reaches 28 seconds
195  * will be terminated.
196  *
197  * Current time is valid at the "on-time" marker (OTM), either "*" or
198  * "#". The nominal on-time marker (*) will be transmitted 45 ms early
199  * to account for the 8 ms required to send 1 character at 1200 Baud,
200  * plus an additional 7 ms for delay from NIST to the user, and
201  * approximately 30 ms "scrambler" delay inherent in 1200 Baud modems.
202  * If the caller echoes all characters, NIST will measure the round trip
203  * delay and advance the on-time marker so that the midpoint of the stop
204  * bit arrives at the user on time. The amount of msADV will reflect the
205  * actual required advance in milliseconds and the OTM will be a "#".
206  *
207  * (The NIST system requires 4 or 5 consecutive delay measurements which
208  * are consistent before switching from "*" to "#". If the user has a
209  * 1200 Baud modem with the same internal delay as that used by NIST,
210  * then the "#" OTM should arrive at the user within +-2 ms of the
211  * correct time.
212  *
213  * However, NIST has studied different brands of 1200 Baud modems and
214  * found internal delays from 24 ms to 40 ms and offsets of the "#" OTM
215  * of +-10 ms. For many computer users, +-10 ms accuracy should be more
216  * than adequate since many computer internal clocks can only be set
217  * with granularity of 20 to 50 ms. In any case, the repeatability of
218  * the offset for the "#" OTM should be within +-2 ms, if the dial-up
219  * path is reciprocal and the user doesn't change the brand or model of
220  * modem used.
221  *
222  * This should be true even if the dial-up path on one day is a land-
223  * line of less than 40 ms (one way) and on the next day is a satellite
224  * link of 260 to 300 ms. In the rare event that the path is one way by
225  * satellite and the other way by land line with a round trip
226  * measurement in the range of 90 to 260 ms, the OTM will remain a "*"
227  * indicating 45 ms advance.
228  *
229  * For user comments write:
230  * NIST-ACTS
231  * Time and Frequency Division
232  * Mail Stop 847
233  * 325 Broadway
234  * Boulder, CO 80303
235  *
236  * Software for setting (PC)DOS compatable machines is available on a
237  * 360-kbyte diskette for $35.00 from: NIST Office of Standard Reference
238  * Materials B311-Chemistry Bldg, NIST, Gaithersburg, MD, 20899, (301)
239  * 975-6776
240  *
241  * PTB timecode service (+49 531 512038)
242  * The Physikalisch-Technische Bundesanstalt (Germany)
243  * also supports a modem time service
244  * as the data formats are very similar this driver can also be compiled for
245  * utilizing the PTB time code service.
246  *
247  * Data format
248  * 0000000000111111111122222222223333333333444444444455555555556666666666777777777   7
249  * 0123456789012345678901234567890123456789012345678901234567890123456789012345678   9
250  * 1995-01-23 20:58:51 MEZ  10402303260219950123195849740+40000500              *
251  * A    B  C  D EF  G  H    IJ K  L M N O   P Q R S T    U V  W  XY             Z<CR><LF>
252  *
253  * A year
254  * B month
255  * C day
256  * D hour
257  * E : normally
258  *   A for DST to ST switch first hour
259  *   B for DST to ST switch second hour if not marked in H
260  * F minute
261  * G second
262  * H timezone
263  * I day of week
264  * J week of year
265  * K day of year
266  * L month for next ST/DST changes
267  * M day
268  * N hour
269  * O UTC year
270  * P UTC month
271  * Q UTC day
272  * R UTC hour
273  * S UTC minute
274  * T modified julian day (MJD)
275  * U DUT1
276  * V direction and month if leap second
277  * W signal delay (assumed/measured)
278  * X sequence number for additional text line in Y
279  * Y additional text
280  * Z on time marker (* - assumed delay / # measured delay)
281  * <CR>!<LF> ! is second change !
282  *
283  * This format is also used by the National Physical Laboratory (NPL)'s
284  * TRUETIME service in the UK.  In this case the timezone field is
285  * UTC+0 or UTC+1 for standard and daylight saving time.  The phone
286  * number for this service (a premium rate number) is 0891 516 333.
287  * It is not clear whether the echo check is implemented.
288  *
289  * For more detail, see http://www.npl.co.uk/npl/cetm/taf/truetime.html.
290  */
291 
292 /*
293  * Interface definitions
294  */
295 #define	SPEED232	B1200	/* uart speed (1200 cowardly baud) */
296 #define	PRECISION	(-10)	/* precision assumed (about 1 ms) */
297 #ifdef CLOCK_ACTS
298 # define REFID		"ACTS"	/* reference ID */
299 # define DESCRIPTION	"NIST Automated Computer Time Service" /* WRU */
300 # define LENCODE	50	/* length of valid timecode string */
301 # define DEVICE		"/dev/acts%d" /* device name and unit */
302 # define REF_ENTRY	refclock_acts
303 #else  /* not CLOCK_ACTS */
304 # define REFID		"TPTB"	/* reference ID */
305 # define DESCRIPTION	"PTB Automated Computer Time Service"
306 # define LENCODE	78	/* length of valid timecode string */
307 # define DEVICE		"/dev/ptb%d" /* device name and unit */
308 # define REF_ENTRY	refclock_ptb
309 #endif /* not CLOCK_ACTS */
310 #define MODE_AUTO	0	/* automatic mode */
311 #define MODE_BACKUP	1	/* backup mode */
312 #define MODE_MANUAL	2	/* manual mode */
313 
314 #define MSGCNT		10	/* we need this many ACTS messages */
315 #define SMAX		80	/* max token string length */
316 #define ACTS_MINPOLL	10	/* log2 min poll interval (1024 s) */
317 #define ACTS_MAXPOLL	18	/* log2 max poll interval (16384 s) */
318 #define MAXOUTAGE	3600	/* max before ACTS kicks in (s) */
319 
320 /*
321  * Modem control strings. These may have to be changed for some modems.
322  *
323  * AT	command prefix
324  * B1	initiate call negotiation using Bell 212A
325  * &C1	enable carrier detect
326  * &D2	hang up and return to command mode on DTR transition
327  * E0	modem command echo disabled
328  * l1	set modem speaker volume to low level
329  * M1	speaker enabled untill carrier detect
330  * Q0	return result codes
331  * V1	return result codes as English words
332  */
333 #define MODEM_SETUP	"ATB1&C1&D2E0L1M1Q0V1" /* modem setup */
334 #define MODEM_HANGUP	"ATH"	/* modem disconnect */
335 
336 /*
337  * Timeouts
338  */
339 #define IDLE		60	/* idle timeout (s) */
340 #define WAIT		2	/* wait timeout (s) */
341 #define ANSWER		30	/* answer timeout (s) */
342 #define CONNECT		10	/* connect timeout (s) */
343 #define TIMECODE	15	/* timecode timeout (s) */
344 
345 /*
346  * Tables to compute the ddd of year form icky dd/mm timecode. Viva la
347  * leap.
348  */
349 static int day1tab[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
350 static int day2tab[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
351 
352 /*
353  * Unit control structure
354  */
355 struct actsunit {
356 	int	pollcnt;	/* poll message counter */
357 	int	state;		/* the first one was Delaware */
358 	int	run;		/* call program run switch */
359 	int	msgcnt;		/* count of ACTS messages received */
360 	long	redial;		/* interval to next automatic call */
361 	double	msADV;		/* millisecond advance of last message */
362 };
363 
364 /*
365  * Function prototypes
366  */
367 static	int	acts_start	P((int, struct peer *));
368 static	void	acts_shutdown	P((int, struct peer *));
369 static	void	acts_receive	P((struct recvbuf *));
370 static	void	acts_poll	P((int, struct peer *));
371 static	void	acts_timeout	P((struct peer *));
372 static	void	acts_disc	P((struct peer *));
373 static	int	acts_write	P((struct peer *, const char *));
374 
375 /*
376  * Transfer vector (conditional structure name)
377  */
378 struct	refclock REF_ENTRY = {
379 	acts_start,		/* start up driver */
380 	acts_shutdown,		/* shut down driver */
381 	acts_poll,		/* transmit poll message */
382 	noentry,		/* not used (old acts_control) */
383 	noentry,		/* not used (old acts_init) */
384 	noentry,		/* not used (old acts_buginfo) */
385 	NOFLAGS			/* not used */
386 };
387 
388 
389 /*
390  * acts_start - open the devices and initialize data for processing
391  */
392 
393 static int
394 acts_start (
395 	int unit,
396 	struct peer *peer
397 	)
398 {
399 	register struct actsunit *up;
400 	struct refclockproc *pp;
401 	int fd;
402 	char device[20];
403 	int dtr = TIOCM_DTR;
404 
405 	/*
406 	 * Open serial port. Use ACTS line discipline, if available. It
407 	 * pumps a timestamp into the data stream at every on-time
408 	 * character '*' found. Note: the port must have modem control
409 	 * or deep pockets for the phone bill. HP-UX 9.03 users should
410 	 * have very deep pockets.
411 	 */
412 	(void)sprintf(device, DEVICE, unit);
413 	if (!(fd = refclock_open(device, SPEED232, LDISC_ACTS)))
414 	    return (0);
415 	if (ioctl(fd, TIOCMBIS, (char *)&dtr) < 0) {
416 		msyslog(LOG_ERR, "clock %s ACTS no modem control",
417 			ntoa(&peer->srcadr));
418 		return (0);
419 	}
420 
421 	/*
422 	 * Allocate and initialize unit structure
423 	 */
424 	if (!(up = (struct actsunit *)
425 	      emalloc(sizeof(struct actsunit)))) {
426 		(void) close(fd);
427 		return (0);
428 	}
429 	memset((char *)up, 0, sizeof(struct actsunit));
430 	pp = peer->procptr;
431 	pp->io.clock_recv = acts_receive;
432 	pp->io.srcclock = (caddr_t)peer;
433 	pp->io.datalen = 0;
434 	pp->io.fd = fd;
435 	if (!io_addclock(&pp->io)) {
436 		(void) close(fd);
437 		free(up);
438 		return (0);
439 	}
440 	pp->unitptr = (caddr_t)up;
441 
442 	/*
443 	 * Initialize miscellaneous variables
444 	 */
445 	peer->precision = PRECISION;
446 	pp->clockdesc = DESCRIPTION;
447 	memcpy((char *)&pp->refid, REFID, 4);
448 	peer->minpoll = ACTS_MINPOLL;
449 	peer->maxpoll = ACTS_MAXPOLL;
450 	peer->sstclktype = CTL_SST_TS_TELEPHONE;
451 
452 	/*
453 	 * Initialize modem and kill DTR. We skedaddle if this comes
454 	 * bum.
455 	 */
456 	if (!acts_write(peer, MODEM_SETUP)) {
457 		(void) close(fd);
458 		free(up);
459 		return (0);
460 	}
461 
462 	/*
463 	 * Set up the driver timeout
464 	 */
465 	peer->nextdate = current_time + WAIT;
466 	return (1);
467 }
468 
469 
470 /*
471  * acts_shutdown - shut down the clock
472  */
473 static void
474 acts_shutdown (
475 	int unit,
476 	struct peer *peer
477 	)
478 {
479 	register struct actsunit *up;
480 	struct refclockproc *pp;
481 
482 	pp = peer->procptr;
483 	up = (struct actsunit *)pp->unitptr;
484 	io_closeclock(&pp->io);
485 	free(up);
486 }
487 
488 
489 /*
490  * acts_receive - receive data from the serial interface
491  */
492 static void
493 acts_receive (
494 	struct recvbuf *rbufp
495 	)
496 {
497 	register struct actsunit *up;
498 	struct refclockproc *pp;
499 	struct peer *peer;
500 	char str[SMAX];
501 	int i;
502 	char hangup = '%';	/* ACTS hangup */
503 	int day;		/* day of the month */
504 	int month;		/* month of the year */
505 	u_long mjd;		/* Modified Julian Day */
506 	double dut1;		/* DUT adjustment */
507 	double msADV;		/* ACTS transmit advance (ms) */
508 	char flag;		/* calibration flag */
509 #ifndef CLOCK_PTBACTS
510 	char utc[10];		/* this is NIST and you're not */
511 	u_int dst;		/* daylight/standard time indicator */
512 	u_int leap;		/* leap-second indicator */
513 #else
514 	char leapdir;		/* leap direction */
515 	u_int leapmonth;	/* month of leap */
516 #endif
517 	/*
518 	 * Initialize pointers and read the timecode and timestamp. If
519 	 * the OK modem status code, leave it where folks can find it.
520 	 */
521 	peer = (struct peer *)rbufp->recv_srcclock;
522 	pp = peer->procptr;
523 	up = (struct actsunit *)pp->unitptr;
524 	pp->lencode = refclock_gtlin(rbufp, pp->a_lastcode, BMAX,
525 				     &pp->lastrec);
526 	if (pp->lencode == 0) {
527 		if (strcmp(pp->a_lastcode, "OK") == 0)
528 		    pp->lencode = 2;
529 		return;
530 	}
531 #ifdef DEBUG
532 	if (debug)
533 	    printf("acts: state %d timecode %d %*s\n", up->state,
534 		   pp->lencode, pp->lencode, pp->a_lastcode);
535 #endif
536 
537 	switch (up->state) {
538 
539 	    case 0:
540 
541 		/*
542 		 * State 0. We are not expecting anything. Probably
543 		 * modem disconnect noise. Go back to sleep.
544 		 */
545 		return;
546 
547 	    case 1:
548 
549 		/*
550 		 * State 1. We are waiting for the call to be answered.
551 		 * All we care about here is CONNECT as the first token
552 		 * in the string. If the modem signals BUSY, ERROR, NO
553 		 * ANSWER, NO CARRIER or NO DIALTONE, we immediately
554 		 * hang up the phone. If CONNECT doesn't happen after
555 		 * ANSWER seconds, hang up the phone. If everything is
556 		 * okay, start the connect timeout and slide into state
557 		 * 2.
558 		 */
559 		if( strcmp(pp->a_lastcode, " ") == 0) {
560 			acts_disc(peer);
561 			return;
562 		}
563 		if( strcmp(sys_phone[0],"DIRECT") != 0 ) {
564 			(void)strncpy(str, strtok(pp->a_lastcode, " "), SMAX);
565 			if (strcmp(str, "BUSY") == 0 || strcmp(str, "ERROR") ==
566 			    0 || strcmp(str, "NO") == 0) {
567 				NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
568 					msyslog(LOG_NOTICE,
569 						"clock %s ACTS modem status %s",
570 						ntoa(&peer->srcadr), pp->a_lastcode);
571 				acts_disc(peer);
572 			} else if (strcmp(str, "CONNECT") == 0) {
573 				peer->nextdate = current_time + CONNECT;
574 				up->msgcnt = 0;
575 				up->state++;
576 			}
577 		} else {
578 			(void) strncpy(str,"CONNECT",7);
579 			peer->nextdate = current_time + CONNECT;
580 			up->msgcnt = 0;
581 			up->state++;
582 		}
583 		return;
584 
585 	    case 2:
586 
587 		/*
588 		 * State 2. The call has been answered and we are
589 		 * waiting for the first ACTS message. If this doesn't
590 		 * happen within the timecode timeout, hang up the
591 		 * phone. We probably got a wrong number or ACTS is
592 		 * down.
593 		 */
594 		peer->nextdate = current_time + TIMECODE;
595 		up->state++;
596 	}
597 
598 	/*
599 	 * Real yucky things here. Ignore everything except timecode
600 	 * messages, as determined by the message length. We told the
601 	 * terminal routines to end the line with '*' and the line
602 	 * discipline to strike a timestamp on that character. However,
603 	 * when the ACTS echo-delay scheme works, the '*' eventually
604 	 * becomes a '#'. In this case the message is ended by the <CR>
605 	 * that comes about 200 ms after the '#' and the '#' cannot be
606 	 * echoed at the proper time. But, this may not be a lose, since
607 	 * we already have good data from prior messages and only need
608 	 * the millisecond advance calculated by ACTS. So, if the
609 	 * message is long enough and has an on-time character at the
610 	 * right place, we consider the message (but not neccesarily the
611 	 * timestmap) to be valid.
612 	 */
613 	if (pp->lencode != LENCODE)
614 	    return;
615 
616 #ifndef CLOCK_PTBACTS
617 	/*
618 	 * We apparently have a valid timecode message, so dismember it
619 	 * with sscan(). This routine does a good job in spotting syntax
620 	 * errors without becoming overly pedantic.
621 	 *
622 	 *                         D  L D
623 	 *  MJD  YR MO DA H  M  S  ST S UT1 msADV         OTM
624 	 * 47222 88-03-02 21:39:15 83 0 +.3 045.0 UTC(NBS) *
625 	 */
626 	if (sscanf(pp->a_lastcode,
627 		   "%5ld %2d-%2d-%2d %2d:%2d:%2d %2d %1d %3lf %5lf %s %c",
628 		   &mjd, &pp->year, &month, &day, &pp->hour, &pp->minute,
629 		   &pp->second, &dst, &leap, &dut1, &msADV, utc, &flag) != 13) {
630 		refclock_report(peer, CEVNT_BADREPLY);
631 		return;
632 	}
633 #else
634 	/*
635 	 * Data format
636 	 * 0000000000111111111122222222223333333333444444444455555555556666666666777777777   7
637 	 * 0123456789012345678901234567890123456789012345678901234567890123456789012345678   9
638 	 * 1995-01-23 20:58:51 MEZ  10402303260219950123195849740+40000500              *
639 	 */
640 	if (sscanf(pp->a_lastcode,
641 		   "%*4d-%*2d-%*2d %*2d:%*2d:%2d %*5c%*12c%4d%2d%2d%2d%2d%5ld%2lf%c%2d%3lf%*15c%c",
642 		   &pp->second, &pp->year, &month, &day, &pp->hour, &pp->minute, &mjd, &dut1, &leapdir, &leapmonth, &msADV, &flag) != 12) {
643 		refclock_report(peer, CEVNT_BADREPLY);
644 		return;
645 	}
646 #endif
647 	/*
648 	 * Some modems can't be trusted (the Practical Peripherals
649 	 * 9600SA comes to mind) and, even if they manage to unstick
650 	 * ACTS, the millisecond advance is wrong, so we use CLK_FLAG2
651 	 * to disable echoes, if neccessary.
652 	 */
653 	if ((flag == '*' || flag == '#') && !(pp->sloppyclockflag &
654 					      CLK_FLAG2))
655 	    (void)write(pp->io.fd, &flag, 1);
656 
657 	/*
658 	 * Yes, I know this code incorrectly thinks that 2000 is a leap
659 	 * year. The ACTS timecode format croaks then anyway. Life is
660 	 * short. Would only the timecode mavens resist the urge to
661 	 * express months of the year and days of the month in favor of
662 	 * days of the year.
663 	 *	NOTE: year 2000 IS a leap year!!!  ghealton	Y2KFixes
664 	 */
665 	if (month < 1 || month > 12 || day < 1) {
666 		refclock_report(peer, CEVNT_BADTIME);
667 		return;
668 	}
669 	if ( pp->year <= YEAR_PIVOT ) pp->year += 100;		/* Y2KFixes */
670 	if ( !isleap_tm(pp->year) ) {				/* Y2KFixes */
671 		if (day > day1tab[month - 1]) {
672 			refclock_report(peer, CEVNT_BADTIME);
673 			return;
674 		}
675 		for (i = 0; i < month - 1; i++)
676 		    day += day1tab[i];
677 	} else {
678 		if (day > day2tab[month - 1]) {
679 			refclock_report(peer, CEVNT_BADTIME);
680 			return;
681 		}
682 		for (i = 0; i < month - 1; i++)
683 		    day += day2tab[i];
684 	}
685 	pp->day = day;
686 
687 #ifndef CLOCK_PTBACTS
688 	if (leap == 1)
689 	    pp->leap = LEAP_ADDSECOND;
690 	else if (pp->leap == 2)
691 	    pp->leap = LEAP_DELSECOND;
692 #else
693 	if (leapmonth == month) {
694 		if (leapdir == '+')
695 		    pp->leap = LEAP_ADDSECOND;
696 		else if (leapdir == '-')
697 		    pp->leap = LEAP_DELSECOND;
698 	}
699 #endif
700 
701 	/*
702 	 * Colossal hack here. We process each sample in a trimmed-mean
703 	 * filter and determine the reference clock offset and
704 	 * dispersion. The fudge time1 value is added to each sample as
705 	 * received. If we collect MSGCNT samples before the '#' on-time
706 	 * character, we use the results of the filter as is. If the '#'
707 	 * is found before that, the adjusted msADV is used to correct
708 	 * the propagation delay.
709 	 */
710 	up->msgcnt++;
711 	if (flag == '#') {
712 		pp->offset += (msADV - up->msADV) * 1000 * 1e-6;
713 	} else {
714 		up->msADV = msADV;
715 		if (!refclock_process(pp)) {
716 			refclock_report(peer, CEVNT_BADTIME);
717 			return;
718 		} else if (up->msgcnt < MSGCNT)
719 		    return;
720 	}
721 
722 	/*
723 	 * We have a filtered sample offset ready for peer processing.
724 	 * We use lastrec as both the reference time and receive time in
725 	 * order to avoid being cute, like setting the reference time
726 	 * later than the receive time, which may cause a paranoid
727 	 * protocol module to chuck out the data. Finaly, we unhook the
728 	 * timeout, arm for the next call, fold the tent and go home.
729 	 * The little dance with the '%' character is an undocumented
730 	 * ACTS feature that hangs up the phone real quick without
731 	 * waiting for carrier loss or long-space disconnect, but we do
732 	 * these clumsy things anyway.
733 	 */
734 	record_clock_stats(&peer->srcadr, pp->a_lastcode);
735 	refclock_receive(peer);
736 	pp->sloppyclockflag &= ~CLK_FLAG1;
737 	up->pollcnt = 0;
738 	(void)write(pp->io.fd, &hangup, 1);
739 	up->state = 0;
740 	acts_disc(peer);
741 }
742 
743 
744 /*
745  * acts_poll - called by the transmit routine
746  */
747 static void
748 acts_poll (
749 	int unit,
750 	struct peer *peer
751 	)
752 {
753 	register struct actsunit *up;
754 	struct refclockproc *pp;
755 
756 	/*
757 	 * If the driver is running, we set the enable flag (fudge
758 	 * flag1), which causes the driver timeout routine to initiate a
759 	 * call to ACTS. If not, the enable flag can be set using
760 	 * ntpdc. If this is the sustem peer, then follow the system
761 	 * poll interval.
762 	 */
763 	pp = peer->procptr;
764 	up = (struct actsunit *)pp->unitptr;
765 
766 	if (up->run) {
767 		pp->sloppyclockflag |= CLK_FLAG1;
768 		if (peer == sys_peer)
769 		    peer->hpoll = sys_poll;
770 		else
771 		    peer->hpoll = peer->minpoll;
772 	}
773 	acts_timeout (peer);
774 	return;
775 }
776 
777 
778 /*
779  * acts_timeout - called by the timer interrupt
780  */
781 static void
782 acts_timeout (
783 	struct peer *peer
784 	)
785 {
786 	register struct actsunit *up;
787 	struct refclockproc *pp;
788 	int dtr = TIOCM_DTR;
789 
790 	/*
791 	 * If a timeout occurs in other than state 0, the call has
792 	 * failed. If in state 0, we just see if there is other work to
793 	 * do.
794 	 */
795 	pp = peer->procptr;
796 	up = (struct actsunit *)pp->unitptr;
797 	if (up->state) {
798 		acts_disc(peer);
799 		return;
800 	}
801 	switch (peer->ttl) {
802 
803 		/*
804 		 * In manual mode the ACTS calling program is activated
805 		 * by the ntpdc program using the enable flag (fudge
806 		 * flag1), either manually or by a cron job.
807 		 */
808 	    case MODE_MANUAL:
809 		up->run = 0;
810 		break;
811 
812 		/*
813 		 * In automatic mode the ACTS calling program runs
814 		 * continuously at intervals determined by the sys_poll
815 		 * variable.
816 		 */
817 	    case MODE_AUTO:
818 		if (!up->run)
819 		    pp->sloppyclockflag |= CLK_FLAG1;
820 		up->run = 1;
821 		break;
822 
823 		/*
824 		 * In backup mode the ACTS calling program is disabled,
825 		 * unless no system peer has been selected for MAXOUTAGE
826 		 * (3600 s). Once enabled, it runs until some other NTP
827 		 * peer shows up.
828 		 */
829 	    case MODE_BACKUP:
830 		if (!up->run && sys_peer == 0) {
831 			if (current_time - last_time > MAXOUTAGE) {
832 				up->run = 1;
833 				peer->hpoll = peer->minpoll;
834 				NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
835 					msyslog(LOG_NOTICE,
836 						"clock %s ACTS backup started ",
837 						ntoa(&peer->srcadr));
838 			}
839 		} else if (up->run && sys_peer->sstclktype != CTL_SST_TS_TELEPHONE) {
840 			peer->hpoll = peer->minpoll;
841 			up->run = 0;
842 			NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
843 				msyslog(LOG_NOTICE,
844 					"clock %s ACTS backup stopped",
845 					ntoa(&peer->srcadr));
846 		}
847 		break;
848 
849 	    default:
850 		msyslog(LOG_ERR,
851 			"clock %s ACTS invalid mode", ntoa(&peer->srcadr));
852 	}
853 
854 	/*
855 	 * The fudge flag1 is used as an enable/disable; if set either
856 	 * by the code or via ntpdc, the ACTS calling program is
857 	 * started; if reset, the phones stop ringing.
858 	 */
859 	if (!(pp->sloppyclockflag & CLK_FLAG1)) {
860 		up->pollcnt = 0;
861 		peer->nextdate = current_time + IDLE;
862 		return;
863 	}
864 
865 	/*
866 	 * Initiate a call to the ACTS service. If we wind up here in
867 	 * other than state 0, a successful call could not be completed
868 	 * within minpoll seconds. We advance to the next modem dial
869 	 * string. If none are left, we log a notice and clear the
870 	 * enable flag. For future enhancement: call the site RP and
871 	 * leave an obscene message in his voicemail.
872 	 */
873 	if (sys_phone[up->pollcnt][0] == '\0') {
874 		refclock_report(peer, CEVNT_TIMEOUT);
875 		NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
876 			msyslog(LOG_NOTICE,
877 				"clock %s ACTS calling program terminated",
878 				ntoa(&peer->srcadr));
879 		pp->sloppyclockflag &= ~CLK_FLAG1;
880 #ifdef DEBUG
881 		if (debug)
882 		    printf("acts: calling program terminated\n");
883 #endif
884 		up->pollcnt = 0;
885 		peer->nextdate = current_time + IDLE;
886 		return;
887 	}
888 
889 	/*
890 	 * Raise DTR, call ACTS and start the answer timeout. We think
891 	 * it strange if the OK status has not been received from the
892 	 * modem, but plow ahead anyway.
893 	 */
894 	if (strcmp(pp->a_lastcode, "OK") != 0)
895 	    NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
896 		    msyslog(LOG_NOTICE, "clock %s ACTS no modem status",
897 			    ntoa(&peer->srcadr));
898 	(void)ioctl(pp->io.fd, TIOCMBIS, (char *)&dtr);
899 	(void)acts_write(peer, sys_phone[up->pollcnt]);
900 	NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
901 		msyslog(LOG_NOTICE, "clock %s ACTS calling %s\n",
902 			ntoa(&peer->srcadr), sys_phone[up->pollcnt]);
903 	up->state = 1;
904 	up->pollcnt++;
905 	pp->polls++;
906 	peer->nextdate = current_time + ANSWER;
907 	return;
908 }
909 
910 
911 /*
912  * acts_disc - disconnect the call and wait for the ruckus to cool
913  */
914 static void
915 acts_disc (
916 	struct peer *peer
917 	)
918 {
919 	register struct actsunit *up;
920 	struct refclockproc *pp;
921 	int dtr = TIOCM_DTR;
922 
923 	/*
924 	 * We should never get here other than in state 0, unless a call
925 	 * has timed out. We drop DTR, which will reliably get the modem
926 	 * off the air, even while ACTS is hammering away full tilt.
927 	 */
928 	pp = peer->procptr;
929 	up = (struct actsunit *)pp->unitptr;
930 	(void)ioctl(pp->io.fd, TIOCMBIC, (char *)&dtr);
931 	if (up->state > 0) {
932 		NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
933 			msyslog(LOG_NOTICE, "clock %s ACTS call failed %d",
934 				ntoa(&peer->srcadr), up->state);
935 #ifdef DEBUG
936 		if (debug)
937 			printf("acts: call failed %d\n", up->state);
938 #endif
939 		up->state = 0;
940 	}
941 	peer->nextdate = current_time + WAIT;
942 }
943 
944 
945 /*
946  * acts_write - write a message to the serial port
947  */
948 static int
949 acts_write (
950 	struct peer *peer,
951 	const char *str
952 	)
953 {
954 	register struct actsunit *up;
955 	struct refclockproc *pp;
956 	int len;
957 	int code;
958 	char cr = '\r';
959 
960 	/*
961 	 * Not much to do here, other than send the message, handle
962 	 * debug and report faults.
963 	 */
964 	pp = peer->procptr;
965 	up = (struct actsunit *)pp->unitptr;
966 	len = strlen(str);
967 #ifdef DEBUG
968 	if (debug)
969 		printf("acts: state %d send %d %s\n", up->state, len,
970 		    str);
971 #endif
972 	code = write(pp->io.fd, str, (unsigned)len) == len;
973 	code &= write(pp->io.fd, &cr, 1) == 1;
974 	if (!code)
975 		refclock_report(peer, CEVNT_FAULT);
976 	return (code);
977 }
978 
979 #else
980 int refclock_acts_bs;
981 #endif /* REFCLOCK */
982