xref: /netbsd-src/external/bsd/ntp/dist/ntpd/refclock_nmea.c (revision a04395531661c5e8d314125d5ae77d4cbedd5d73)
1 /*	$NetBSD: refclock_nmea.c,v 1.13 2020/05/25 20:47:25 christos Exp $	*/
2 
3 /*
4  * refclock_nmea.c - clock driver for an NMEA GPS CLOCK
5  *		Michael Petry Jun 20, 1994
6  *		 based on refclock_heathn.c
7  *
8  * Updated to add support for Accord GPS Clock
9  *		Venu Gopal Dec 05, 2007
10  *		neo.venu@gmail.com, venugopal_d@pgad.gov.in
11  *
12  * Updated to process 'time1' fudge factor
13  *		Venu Gopal May 05, 2008
14  *
15  * Converted to common PPSAPI code, separate PPS fudge time1
16  * from serial timecode fudge time2.
17  *		Dave Hart July 1, 2009
18  *		hart@ntp.org, davehart@davehart.com
19  */
20 
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24 
25 #include "ntp_types.h"
26 
27 #if defined(REFCLOCK) && defined(CLOCK_NMEA)
28 
29 #define NMEA_WRITE_SUPPORT 0 /* no write support at the moment */
30 
31 #include <sys/stat.h>
32 #include <stdio.h>
33 #include <ctype.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37 
38 #include "ntpd.h"
39 #include "ntp_io.h"
40 #include "ntp_unixtime.h"
41 #include "ntp_refclock.h"
42 #include "ntp_stdlib.h"
43 #include "ntp_calgps.h"
44 #include "timespecops.h"
45 
46 #ifdef HAVE_PPSAPI
47 # include "ppsapi_timepps.h"
48 # include "refclock_atom.h"
49 #endif /* HAVE_PPSAPI */
50 
51 
52 /*
53  * This driver supports NMEA-compatible GPS receivers
54  *
55  * Prototype was refclock_trak.c, Thanks a lot.
56  *
57  * The receiver used spits out the NMEA sentences for boat navigation.
58  * And you thought it was an information superhighway.	Try a raging river
59  * filled with rapids and whirlpools that rip away your data and warp time.
60  *
61  * If HAVE_PPSAPI is defined code to use the PPSAPI will be compiled in.
62  * On startup if initialization of the PPSAPI fails, it will fall back
63  * to the "normal" timestamps.
64  *
65  * The PPSAPI part of the driver understands fudge flag2 and flag3. If
66  * flag2 is set, it will use the clear edge of the pulse. If flag3 is
67  * set, kernel hardpps is enabled.
68  *
69  * GPS sentences other than RMC (the default) may be enabled by setting
70  * the relevent bits of 'mode' in the server configuration line
71  * server 127.127.20.x mode X
72  *
73  * bit 0 - enables RMC (1)
74  * bit 1 - enables GGA (2)
75  * bit 2 - enables GLL (4)
76  * bit 3 - enables ZDA (8) - Standard Time & Date
77  * bit 3 - enables ZDG (8) - Accord GPS Clock's custom sentence with GPS time
78  *			     very close to standard ZDA
79  *
80  * Multiple sentences may be selected except when ZDG/ZDA is selected.
81  *
82  * bit 4/5/6 - selects the baudrate for serial port :
83  *		0 for 4800 (default)
84  *		1 for 9600
85  *		2 for 19200
86  *		3 for 38400
87  *		4 for 57600
88  *		5 for 115200
89  */
90 #define NMEA_MESSAGE_MASK	0x0000FF0FU
91 #define NMEA_BAUDRATE_MASK	0x00000070U
92 #define NMEA_BAUDRATE_SHIFT	4
93 
94 #define NMEA_DELAYMEAS_MASK	0x00000080U
95 #define NMEA_EXTLOG_MASK	0x00010000U
96 #define NMEA_QUIETPPS_MASK	0x00020000U
97 #define NMEA_DATETRUST_MASK	0x00040000U
98 
99 #define NMEA_PROTO_IDLEN	4	/* tag name must be at least 4 chars */
100 #define NMEA_PROTO_MINLEN	6	/* min chars in sentence, excluding CS */
101 #define NMEA_PROTO_MAXLEN	80	/* max chars in sentence, excluding CS */
102 #define NMEA_PROTO_FIELDS	32	/* not official; limit on fields per record */
103 
104 /*
105  * We check the timecode format and decode its contents.  We only care
106  * about a few of them, the most important being the $GPRMC format:
107  *
108  * $GPRMC,hhmmss,a,fddmm.xx,n,dddmmm.xx,w,zz.z,yyy.,ddmmyy,dd,v*CC
109  *
110  * mode (0,1,2,3) selects sentence ANY/ALL, RMC, GGA, GLL, ZDA
111  * $GPGLL,3513.8385,S,14900.7851,E,232420.594,A*21
112  * $GPGGA,232420.59,3513.8385,S,14900.7851,E,1,05,3.4,00519,M,,,,*3F
113  * $GPRMC,232418.19,A,3513.8386,S,14900.7853,E,00.0,000.0,121199,12.,E*77
114  *
115  * Defining GPZDA to support Standard Time & Date
116  * sentence. The sentence has the following format
117  *
118  *  $--ZDA,HHMMSS.SS,DD,MM,YYYY,TH,TM,*CS<CR><LF>
119  *
120  *  Apart from the familiar fields,
121  *  'TH'    Time zone Hours
122  *  'TM'    Time zone Minutes
123  *
124  * Defining GPZDG to support Accord GPS Clock's custom NMEA
125  * sentence. The sentence has the following format
126  *
127  *  $GPZDG,HHMMSS.S,DD,MM,YYYY,AA.BB,V*CS<CR><LF>
128  *
129  *  It contains the GPS timestamp valid for next PPS pulse.
130  *  Apart from the familiar fields,
131  *  'AA.BB' denotes the signal strength( should be < 05.00 )
132  *  'V'	    denotes the GPS sync status :
133  *	   '0' indicates INVALID time,
134  *	   '1' indicates accuracy of +/-20 ms
135  *	   '2' indicates accuracy of +/-100 ns
136  *
137  * Defining PGRMF for Garmin GPS Fix Data
138  * $PGRMF,WN,WS,DATE,TIME,LS,LAT,LAT_DIR,LON,LON_DIR,MODE,FIX,SPD,DIR,PDOP,TDOP
139  * WN  -- GPS week number (weeks since 1980-01-06, mod 1024)
140  * WS  -- GPS seconds in week
141  * LS  -- GPS leap seconds, accumulated ( UTC + LS == GPS )
142  * FIX -- Fix type: 0=nofix, 1=2D, 2=3D
143  * DATE/TIME are standard date/time strings in UTC time scale
144  *
145  * The GPS time can be used to get the full century for the truncated
146  * date spec.
147  */
148 
149 /*
150  * Definitions
151  */
152 #define	DEVICE		"/dev/gps%d"	/* GPS serial device */
153 #define	PPSDEV		"/dev/gpspps%d"	/* PPSAPI device override */
154 #define	SPEED232	B4800	/* uart speed (4800 bps) */
155 #define	PRECISION	(-9)	/* precision assumed (about 2 ms) */
156 #define	PPS_PRECISION	(-20)	/* precision assumed (about 1 us) */
157 #define	DATE_HOLD	16	/* seconds to hold on provided GPS date */
158 #define	DATE_HLIM	4	/* when do we take ANY date format */
159 #define	REFID		"GPS\0"	/* reference id */
160 #define	DESCRIPTION	"NMEA GPS Clock" /* who we are */
161 #ifndef O_NOCTTY
162 #define M_NOCTTY	0
163 #else
164 #define M_NOCTTY	O_NOCTTY
165 #endif
166 #ifndef O_NONBLOCK
167 #define M_NONBLOCK	0
168 #else
169 #define M_NONBLOCK	O_NONBLOCK
170 #endif
171 #define PPSOPENMODE	(O_RDWR | M_NOCTTY | M_NONBLOCK)
172 
173 /* NMEA sentence array indexes for those we use */
174 #define NMEA_GPRMC	0	/* recommended min. nav. */
175 #define NMEA_GPGGA	1	/* fix and quality */
176 #define NMEA_GPGLL	2	/* geo. lat/long */
177 #define NMEA_GPZDA	3	/* date/time */
178 /*
179  * $GPZDG is a proprietary sentence that violates the spec, by not
180  * using $P and an assigned company identifier to prefix the sentence
181  * identifier.	When used with this driver, the system needs to be
182  * isolated from other NTP networks, as it operates in GPS time, not
183  * UTC as is much more common.	GPS time is >15 seconds different from
184  * UTC due to not respecting leap seconds since 1970 or so.  Other
185  * than the different timebase, $GPZDG is similar to $GPZDA.
186  */
187 #define NMEA_GPZDG	4
188 #define NMEA_PGRMF	5
189 #define NMEA_PUBX04	6
190 #define NMEA_ARRAY_SIZE (NMEA_PUBX04 + 1)
191 
192 /*
193  * Sentence selection mode bits
194  */
195 #define USE_GPRMC		0x00000001u
196 #define USE_GPGGA		0x00000002u
197 #define USE_GPGLL		0x00000004u
198 #define USE_GPZDA		0x00000008u
199 #define USE_PGRMF		0x00000100u
200 #define USE_PUBX04		0x00000200u
201 
202 /* mapping from sentence index to controlling mode bit */
203 static const u_int32 sentence_mode[NMEA_ARRAY_SIZE] =
204 {
205 	USE_GPRMC,
206 	USE_GPGGA,
207 	USE_GPGLL,
208 	USE_GPZDA,
209 	USE_GPZDA,
210 	USE_PGRMF,
211 	USE_PUBX04
212 };
213 
214 /* date formats we support */
215 enum date_fmt {
216 	DATE_1_DDMMYY,	/* use 1 field	with 2-digit year */
217 	DATE_3_DDMMYYYY	/* use 3 fields with 4-digit year */
218 };
219 
220 /* date type */
221 enum date_type {
222 	DTYP_NONE,
223 	DTYP_Y2D,	/* 2-digit year */
224 	DTYP_W10B,	/* 10-bit week in GPS epoch */
225 	DTYP_Y4D,	/* 4-digit (full) year */
226 	DTYP_WEXT	/* extended week in GPS epoch */
227 };
228 
229 /* results for 'field_init()'
230  *
231  * Note: If a checksum is present, the checksum test must pass OK or the
232  * sentence is tagged invalid.
233  */
234 #define CHECK_EMPTY  -1	/* no data			*/
235 #define CHECK_INVALID 0	/* not a valid NMEA sentence	*/
236 #define CHECK_VALID   1	/* valid but without checksum	*/
237 #define CHECK_CSVALID 2	/* valid with checksum OK	*/
238 
239 /*
240  * Unit control structure
241  */
242 struct refclock_atom;
243 typedef struct refclock_atom TAtomUnit;
244 typedef struct {
245 #   ifdef HAVE_PPSAPI
246 	TAtomUnit	atom;		/* PPSAPI structure */
247 	int		ppsapi_fd;	/* fd used with PPSAPI */
248 	u_char		ppsapi_tried;	/* attempt PPSAPI once */
249 	u_char		ppsapi_lit;	/* time_pps_create() worked */
250 #   endif /* HAVE_PPSAPI */
251 	uint16_t	rcvtout;	/* one-shot for sample expiration */
252 	u_char		ppsapi_gate;	/* system is on PPS */
253 	u_char  	gps_time;	/* use GPS time, not UTC */
254 	l_fp		last_reftime;	/* last processed reference stamp */
255 	TNtpDatum	last_gpsdate;	/* last processed split date/time */
256 	u_short		hold_gpsdate;	/* validity ticker for above */
257 	u_short		type_gpsdate;	/* date info type for above */
258 	/* tally stats, reset each poll cycle */
259 	struct
260 	{
261 		u_int total;
262 		u_int accepted;
263 		u_int rejected;   /* GPS said not enough signal */
264 		u_int malformed;  /* Bad checksum, invalid date or time */
265 		u_int filtered;   /* mode bits, not GPZDG, same second */
266 		u_int pps_used;
267 	}
268 		tally;
269 	/* per sentence checksum seen flag */
270 	u_char		cksum_type[NMEA_ARRAY_SIZE];
271 
272 	/* line assembly buffer (NMEAD support) */
273 	u_short	lb_len;
274 	char	lb_buf[BMAX];	/* assembly buffer */
275 } nmea_unit;
276 
277 /*
278  * helper for faster field access
279  */
280 typedef struct {
281 	char  *base;	/* buffer base		*/
282 	char  *cptr;	/* current field ptr	*/
283 	int    blen;	/* buffer length	*/
284 	int    cidx;	/* current field index	*/
285 } nmea_data;
286 
287 /*
288  * Function prototypes
289  */
290 static	int	nmea_start	(int, struct peer *);
291 static	void	nmea_shutdown	(int, struct peer *);
292 static	void	nmea_receive	(struct recvbuf *);
293 static	void	nmea_poll	(int, struct peer *);
294 static	void	nmea_procrec	(struct peer *, l_fp);
295 #ifdef HAVE_PPSAPI
296 static	double	tabsdiffd	(l_fp, l_fp);
297 static	void	nmea_control	(int, const struct refclockstat *,
298 				 struct refclockstat *, struct peer *);
299 #define		NMEA_CONTROL	nmea_control
300 #else
301 #define		NMEA_CONTROL	noentry
302 #endif /* HAVE_PPSAPI */
303 static	void	nmea_timer	(int, struct peer *);
304 
305 /* parsing helpers */
306 static int	field_init	(nmea_data * data, char * cp, int len);
307 static char *	field_parse	(nmea_data * data, int fn);
308 static void	field_wipe	(nmea_data * data, ...);
309 static u_char	parse_qual	(nmea_data * data, int idx,
310 				 char tag, int inv);
311 static int	parse_time	(TCivilDate * jd, l_fp * fofs,
312 				 nmea_data *, int idx);
313 static int	parse_date	(TCivilDate * jd, nmea_data *,
314 				 int idx, enum date_fmt fmt);
315 static int	parse_gpsw	(TGpsDatum *, nmea_data *,
316 				 int weekidx, int timeidx, int leapidx);
317 
318 static int	nmead_open	(const char * device);
319 
320 /*
321  * If we want the driver to output sentences, too: re-enable the send
322  * support functions by defining NMEA_WRITE_SUPPORT to non-zero...
323  */
324 #if NMEA_WRITE_SUPPORT
325 
326 static	void gps_send(int, const char *, struct peer *);
327 # ifdef SYS_WINNT
328 #  undef write	/* ports/winnt/include/config.h: #define write _write */
329 extern int async_write(int, const void *, unsigned int);
330 #  define write(fd, data, octets)	async_write(fd, data, octets)
331 # endif /* SYS_WINNT */
332 
333 #endif /* NMEA_WRITE_SUPPORT */
334 
335 /*
336  * -------------------------------------------------------------------
337  * Transfer vector
338  * -------------------------------------------------------------------
339  */
340 struct refclock refclock_nmea = {
341 	nmea_start,		/* start up driver */
342 	nmea_shutdown,		/* shut down driver */
343 	nmea_poll,		/* transmit poll message */
344 	NMEA_CONTROL,		/* fudge control */
345 	noentry,		/* initialize driver */
346 	noentry,		/* buginfo */
347 	nmea_timer		/* called once per second */
348 };
349 
350 
351 /*
352  * -------------------------------------------------------------------
353  * nmea_start - open the GPS devices and initialize data for processing
354  *
355  * return 0 on error, 1 on success. Even on error the peer structures
356  * must be in a state that permits 'nmea_shutdown()' to clean up all
357  * resources, because it will be called immediately to do so.
358  * -------------------------------------------------------------------
359  */
360 static int
361 nmea_start(
362 	int		unit,
363 	struct peer *	peer
364 	)
365 {
366 	struct refclockproc * const	pp = peer->procptr;
367 	nmea_unit * const		up = emalloc_zero(sizeof(*up));
368 	char				device[20];
369 	size_t				devlen;
370 	u_int32				rate;
371 	int				baudrate;
372 	const char *			baudtext;
373 
374 
375 	/* Get baudrate choice from mode byte bits 4/5/6 */
376 	rate = (peer->ttl & NMEA_BAUDRATE_MASK) >> NMEA_BAUDRATE_SHIFT;
377 
378 	switch (rate) {
379 	case 0:
380 		baudrate = SPEED232;
381 		baudtext = "4800";
382 		break;
383 	case 1:
384 		baudrate = B9600;
385 		baudtext = "9600";
386 		break;
387 	case 2:
388 		baudrate = B19200;
389 		baudtext = "19200";
390 		break;
391 	case 3:
392 		baudrate = B38400;
393 		baudtext = "38400";
394 		break;
395 #   ifdef B57600
396 	case 4:
397 		baudrate = B57600;
398 		baudtext = "57600";
399 		break;
400 #   endif
401 #   ifdef B115200
402 	case 5:
403 		baudrate = B115200;
404 		baudtext = "115200";
405 		break;
406 #   endif
407 	default:
408 		baudrate = SPEED232;
409 		baudtext = "4800 (fallback)";
410 		break;
411 	}
412 
413 	/* Allocate and initialize unit structure */
414 	pp->unitptr = (caddr_t)up;
415 	pp->io.fd = -1;
416 	pp->io.clock_recv = nmea_receive;
417 	pp->io.srcclock = peer;
418 	pp->io.datalen = 0;
419 	/* force change detection on first valid message */
420 	memset(&up->last_reftime, 0xFF, sizeof(up->last_reftime));
421 	memset(&up->last_gpsdate, 0x00, sizeof(up->last_gpsdate));
422 	/* force checksum on GPRMC, see below */
423 	up->cksum_type[NMEA_GPRMC] = CHECK_CSVALID;
424 #   ifdef HAVE_PPSAPI
425 	up->ppsapi_fd = -1;
426 #   endif /* HAVE_PPSAPI */
427 	ZERO(up->tally);
428 
429 	/* Initialize miscellaneous variables */
430 	peer->precision = PRECISION;
431 	pp->clockdesc = DESCRIPTION;
432 	memcpy(&pp->refid, REFID, 4);
433 
434 	/* Open serial port. Use CLK line discipline, if available. */
435 	devlen = snprintf(device, sizeof(device), DEVICE, unit);
436 	if (devlen >= sizeof(device)) {
437 		msyslog(LOG_ERR, "%s clock device name too long",
438 			refnumtoa(&peer->srcadr));
439 		return FALSE; /* buffer overflow */
440 	}
441 	pp->io.fd = refclock_open(device, baudrate, LDISC_CLK);
442 	if (0 >= pp->io.fd) {
443 		pp->io.fd = nmead_open(device);
444 		if (-1 == pp->io.fd)
445 			return FALSE;
446 	}
447 	LOGIF(CLOCKINFO, (LOG_NOTICE, "%s serial %s open at %s bps",
448 	      refnumtoa(&peer->srcadr), device, baudtext));
449 
450 	/* succeed if this clock can be added */
451 	return io_addclock(&pp->io) != 0;
452 }
453 
454 /*
455  * -------------------------------------------------------------------
456  * nmea_shutdown - shut down a GPS clock
457  *
458  * NOTE this routine is called after nmea_start() returns failure,
459  * as well as during a normal shutdown due to ntpq :config unpeer.
460  * -------------------------------------------------------------------
461  */
462 static void
463 nmea_shutdown(
464 	int           unit,
465 	struct peer * peer
466 	)
467 {
468 	struct refclockproc * const pp = peer->procptr;
469 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
470 
471 	UNUSED_ARG(unit);
472 
473 	if (up != NULL) {
474 #	    ifdef HAVE_PPSAPI
475 		if (up->ppsapi_lit)
476 			time_pps_destroy(up->atom.handle);
477 		if (up->ppsapi_tried && up->ppsapi_fd != pp->io.fd)
478 			close(up->ppsapi_fd);
479 #	    endif
480 		free(up);
481 	}
482 	pp->unitptr = (caddr_t)NULL;
483 	if (-1 != pp->io.fd)
484 		io_closeclock(&pp->io);
485 	pp->io.fd = -1;
486 }
487 
488 /*
489  * -------------------------------------------------------------------
490  * nmea_control - configure fudge params
491  * -------------------------------------------------------------------
492  */
493 #ifdef HAVE_PPSAPI
494 static void
495 nmea_control(
496 	int                         unit,
497 	const struct refclockstat * in_st,
498 	struct refclockstat       * out_st,
499 	struct peer               * peer
500 	)
501 {
502 	struct refclockproc * const pp = peer->procptr;
503 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
504 
505 	char   device[32];
506 	size_t devlen;
507 
508 	UNUSED_ARG(in_st);
509 	UNUSED_ARG(out_st);
510 
511 	/*
512 	 * PPS control
513 	 *
514 	 * If /dev/gpspps$UNIT can be opened that will be used for
515 	 * PPSAPI.  Otherwise, the GPS serial device /dev/gps$UNIT
516 	 * already opened is used for PPSAPI as well. (This might not
517 	 * work, in which case the PPS API remains unavailable...)
518 	 */
519 
520 	/* Light up the PPSAPI interface if not yet attempted. */
521 	if ((CLK_FLAG1 & pp->sloppyclockflag) && !up->ppsapi_tried) {
522 		up->ppsapi_tried = TRUE;
523 		devlen = snprintf(device, sizeof(device), PPSDEV, unit);
524 		if (devlen < sizeof(device)) {
525 			up->ppsapi_fd = open(device, PPSOPENMODE,
526 					     S_IRUSR | S_IWUSR);
527 		} else {
528 			up->ppsapi_fd = -1;
529 			msyslog(LOG_ERR, "%s PPS device name too long",
530 				refnumtoa(&peer->srcadr));
531 		}
532 		if (-1 == up->ppsapi_fd)
533 			up->ppsapi_fd = pp->io.fd;
534 		if (refclock_ppsapi(up->ppsapi_fd, &up->atom)) {
535 			/* use the PPS API for our own purposes now. */
536 			up->ppsapi_lit = refclock_params(
537 				pp->sloppyclockflag, &up->atom);
538 			if (!up->ppsapi_lit) {
539 				/* failed to configure, drop PPS unit */
540 				time_pps_destroy(up->atom.handle);
541 				msyslog(LOG_WARNING,
542 					"%s set PPSAPI params fails",
543 					refnumtoa(&peer->srcadr));
544 			}
545 			/* note: the PPS I/O handle remains valid until
546 			 * flag1 is cleared or the clock is shut down.
547 			 */
548 		} else {
549 			msyslog(LOG_WARNING,
550 				"%s flag1 1 but PPSAPI fails",
551 				refnumtoa(&peer->srcadr));
552 		}
553 	}
554 
555 	/* shut down PPS API if activated */
556 	if ( !(CLK_FLAG1 & pp->sloppyclockflag) && up->ppsapi_tried) {
557 		/* shutdown PPS API */
558 		if (up->ppsapi_lit)
559 			time_pps_destroy(up->atom.handle);
560 		up->atom.handle = 0;
561 		/* close/drop PPS fd */
562 		if (up->ppsapi_fd != pp->io.fd)
563 			close(up->ppsapi_fd);
564 		up->ppsapi_fd = -1;
565 
566 		/* clear markers and peer items */
567 		up->ppsapi_gate  = FALSE;
568 		up->ppsapi_lit   = FALSE;
569 		up->ppsapi_tried = FALSE;
570 
571 		peer->flags &= ~FLAG_PPS;
572 		peer->precision = PRECISION;
573 	}
574 }
575 #endif /* HAVE_PPSAPI */
576 
577 /*
578  * -------------------------------------------------------------------
579  * nmea_timer - called once per second
580  *
581  * Usually 'nmea_receive()' can get a timestamp every second, but at
582  * least one Motorola unit needs prompting each time. Doing so in
583  * 'nmea_poll()' gives only one sample per poll cycle, which actually
584  * defeats the purpose of the median filter. Polling once per second
585  * seems a much better idea.
586  *
587  * Also takes care of sample expiration if the receiver fails to
588  * provide new input data.
589  * -------------------------------------------------------------------
590  */
591 static void
592 nmea_timer(
593 	int	      unit,
594 	struct peer * peer
595 	)
596 {
597 	struct refclockproc * const pp = peer->procptr;
598 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
599 
600 	UNUSED_ARG(unit);
601 
602 #   if NMEA_WRITE_SUPPORT
603 
604 	if (-1 != pp->io.fd) /* any mode bits to evaluate here? */
605 		gps_send(pp->io.fd, "$PMOTG,RMC,0000*1D\r\n", peer);
606 
607 #   endif /* NMEA_WRITE_SUPPORT */
608 
609 	/* receive timeout occurred? */
610 	if (up->rcvtout) {
611 		--up->rcvtout;
612 	} else if (pp->codeproc != pp->coderecv) {
613 		/* expire one (the oldest) sample, if any */
614 		refclock_samples_expire(pp, 1);
615 		/* reset message assembly buffer */
616 		up->lb_buf[0] = '\0';
617 		up->lb_len    = 0;
618 	}
619 
620 	if (up->hold_gpsdate && (--up->hold_gpsdate < DATE_HLIM))
621 		up->type_gpsdate = DTYP_NONE;
622 }
623 
624 /*
625  * -------------------------------------------------------------------
626  * nmea_procrec - receive data from the serial interface
627  *
628  * This is the workhorse for NMEA data evaluation:
629  *
630  * + it checks all NMEA data, and rejects sentences that are not valid
631  *   NMEA sentences
632  * + it checks whether a sentence is known and to be used
633  * + it parses the time and date data from the NMEA data string and
634  *   augments the missing bits. (century in date, whole date, ...)
635  * + it rejects data that is not from the first accepted sentence in a
636  *   burst
637  * + it eventually replaces the receive time with the PPS edge time.
638  * + it feeds the data to the internal processing stages.
639  *
640  * This function assumes a non-empty line in the unit line buffer.
641  * -------------------------------------------------------------------
642  */
643 static void
644 nmea_procrec(
645 	struct peer * const	peer,
646 	l_fp 	  		rd_timestamp
647 	)
648 {
649 	/* declare & init control structure pointers */
650 	struct refclockproc * const pp = peer->procptr;
651 	nmea_unit	    * const up = (nmea_unit*)pp->unitptr;
652 
653 	/* Use these variables to hold data until we decide its worth keeping */
654 	nmea_data rdata;
655 	l_fp 	  rd_reftime;
656 
657 	/* working stuff */
658 	TCivilDate	date;	/* to keep & convert the time stamp */
659 	TGpsDatum	wgps;	/* week time storage */
660 	TNtpDatum	dntp;
661 	l_fp		tofs;	/* offset to full-second reftime */
662 	/* results of sentence/date/time parsing */
663 	u_char		sentence;	/* sentence tag */
664 	int		checkres;
665 	int		warp;		/* warp to GPS base date */
666 	char *		cp;
667 	int		rc_date, rc_time;
668 	u_short		rc_dtyp;
669 #   ifdef HAVE_PPSAPI
670 	int		withpps = 0;
671 #   endif /* HAVE_PPSAPI */
672 
673 	/* make sure data has defined pristine state */
674 	ZERO(tofs);
675 	ZERO(date);
676 	ZERO(wgps);
677 	ZERO(dntp);
678 
679 	/*
680 	 * Read the timecode and timestamp, then initialize field
681 	 * processing. The <CR><LF> at the NMEA line end is translated
682 	 * to <LF><LF> by the terminal input routines on most systems,
683 	 * and this gives us one spurious empty read per record which we
684 	 * better ignore silently.
685 	 */
686 	checkres = field_init(&rdata, up->lb_buf, up->lb_len);
687 	switch (checkres) {
688 
689 	case CHECK_INVALID:
690 		DPRINTF(1, ("%s invalid data: '%s'\n",
691 			refnumtoa(&peer->srcadr), up->lb_buf));
692 		refclock_report(peer, CEVNT_BADREPLY);
693 		return;
694 
695 	case CHECK_EMPTY:
696 		return;
697 
698 	default:
699 		DPRINTF(1, ("%s gpsread: %d '%s'\n",
700 			refnumtoa(&peer->srcadr), up->lb_len,
701 			up->lb_buf));
702 		break;
703 	}
704 	up->tally.total++;
705 
706 	/*
707 	 * --> below this point we have a valid NMEA sentence <--
708 	 *
709 	 * Check sentence name. Skip first 2 chars (talker ID) in most
710 	 * cases, to allow for $GLGGA and $GPGGA etc. Since the name
711 	 * field has at least 5 chars we can simply shift the field
712 	 * start.
713 	 */
714 	cp = field_parse(&rdata, 0);
715 	if      (strncmp(cp + 2, "RMC,", 4) == 0)
716 		sentence = NMEA_GPRMC;
717 	else if (strncmp(cp + 2, "GGA,", 4) == 0)
718 		sentence = NMEA_GPGGA;
719 	else if (strncmp(cp + 2, "GLL,", 4) == 0)
720 		sentence = NMEA_GPGLL;
721 	else if (strncmp(cp + 2, "ZDA,", 4) == 0)
722 		sentence = NMEA_GPZDA;
723 	else if (strncmp(cp + 2, "ZDG,", 4) == 0)
724 		sentence = NMEA_GPZDG;
725 	else if (strncmp(cp,   "PGRMF,", 6) == 0)
726 		sentence = NMEA_PGRMF;
727 	else if (strncmp(cp,   "PUBX,04,", 8) == 0)
728 		sentence = NMEA_PUBX04;
729 	else
730 		return;	/* not something we know about */
731 
732 	/* Eventually output delay measurement now. */
733 	if (peer->ttl & NMEA_DELAYMEAS_MASK) {
734 		mprintf_clock_stats(&peer->srcadr, "delay %0.6f %.*s",
735 			 ldexp(rd_timestamp.l_uf, -32),
736 			 (int)(strchr(up->lb_buf, ',') - up->lb_buf),
737 			 up->lb_buf);
738 	}
739 
740 	/* See if I want to process this message type */
741 	if ((peer->ttl & NMEA_MESSAGE_MASK) &&
742 	    !(peer->ttl & sentence_mode[sentence])) {
743 		up->tally.filtered++;
744 		return;
745 	}
746 
747 	/*
748 	 * make sure it came in clean
749 	 *
750 	 * Apparently, older NMEA specifications (which are expensive)
751 	 * did not require the checksum for all sentences.  $GPMRC is
752 	 * the only one so far identified which has always been required
753 	 * to include a checksum.
754 	 *
755 	 * Today, most NMEA GPS receivers checksum every sentence.  To
756 	 * preserve its error-detection capabilities with modern GPSes
757 	 * while allowing operation without checksums on all but $GPMRC,
758 	 * we keep track of whether we've ever seen a valid checksum on
759 	 * a given sentence, and if so, reject future instances without
760 	 * checksum.  ('up->cksum_type[NMEA_GPRMC]' is set in
761 	 * 'nmea_start()' to enforce checksums for $GPRMC right from the
762 	 * start.)
763 	 */
764 	if (up->cksum_type[sentence] <= (u_char)checkres) {
765 		up->cksum_type[sentence] = (u_char)checkres;
766 	} else {
767 		DPRINTF(1, ("%s checksum missing: '%s'\n",
768 			refnumtoa(&peer->srcadr), up->lb_buf));
769 		refclock_report(peer, CEVNT_BADREPLY);
770 		up->tally.malformed++;
771 		return;
772 	}
773 
774 	/*
775 	 * $GPZDG provides GPS time not UTC, and the two mix poorly.
776 	 * Once have processed a $GPZDG, do not process any further UTC
777 	 * sentences (all but $GPZDG currently).
778 	 */
779 	if (sentence == NMEA_GPZDG) {
780 		if (!up->gps_time) {
781 			msyslog(LOG_INFO,
782 				"%s using GPS time as if it were UTC",
783 				refnumtoa(&peer->srcadr));
784 			up->gps_time = 1;
785 		}
786 	} else {
787 		if (up->gps_time) {
788 			up->tally.filtered++;
789 			return;
790 		}
791 	}
792 
793 	DPRINTF(1, ("%s processing %d bytes, timecode '%s'\n",
794 		refnumtoa(&peer->srcadr), up->lb_len, up->lb_buf));
795 
796 	/*
797 	 * Grab fields depending on clock string type and possibly wipe
798 	 * sensitive data from the last timecode.
799 	 */
800 	rc_date = -1;	/* assume we have to do day-time mapping */
801 	rc_dtyp = DTYP_NONE;
802        	switch (sentence) {
803 
804 	case NMEA_GPRMC:
805 		/* Check quality byte, fetch data & time */
806 		rc_time	 = parse_time(&date, &tofs, &rdata, 1);
807 		pp->leap = parse_qual(&rdata, 2, 'A', 0);
808 		if (up->type_gpsdate <= DTYP_Y2D) {
809 			rc_date	= parse_date(&date, &rdata, 9, DATE_1_DDMMYY);
810 			rc_dtyp = DTYP_Y2D;
811 		}
812  		if (CLK_FLAG4 & pp->sloppyclockflag)
813 			field_wipe(&rdata, 3, 4, 5, 6, -1);
814 		break;
815 
816 	case NMEA_GPGGA:
817 		/* Check quality byte, fetch time only */
818 		rc_time	 = parse_time(&date, &tofs, &rdata, 1);
819 		pp->leap = parse_qual(&rdata, 6, '0', 1);
820 		if (CLK_FLAG4 & pp->sloppyclockflag)
821 			field_wipe(&rdata, 2, 4, -1);
822 		break;
823 
824 	case NMEA_GPGLL:
825 		/* Check quality byte, fetch time only */
826 		rc_time	 = parse_time(&date, &tofs, &rdata, 5);
827 		pp->leap = parse_qual(&rdata, 6, 'A', 0);
828 		if (CLK_FLAG4 & pp->sloppyclockflag)
829 			field_wipe(&rdata, 1, 3, -1);
830 		break;
831 
832 	case NMEA_GPZDA:
833 		/* No quality.	Assume best, fetch time & full date */
834 		rc_time	= parse_time(&date, &tofs, &rdata, 1);
835 		if (up->type_gpsdate <= DTYP_Y4D) {
836 			rc_date	= parse_date(&date, &rdata, 2, DATE_3_DDMMYYYY);
837 			rc_dtyp = DTYP_Y4D;
838 		}
839 		break;
840 
841 	case NMEA_GPZDG:
842 		/* Check quality byte, fetch time & full date */
843 		rc_time	 = parse_time(&date, &tofs, &rdata, 1);
844 		pp->leap = parse_qual(&rdata, 4, '0', 1);
845 		--tofs.l_ui; /* GPZDG gives *following* second */
846 		if (up->type_gpsdate <= DTYP_Y4D) {
847 			rc_date	= parse_date(&date, &rdata, 2, DATE_3_DDMMYYYY);
848 			rc_dtyp = DTYP_Y4D;
849 		}
850 		break;
851 
852 	case NMEA_PGRMF:
853 		/* get time, qualifier and GPS weektime. */
854 		rc_time = parse_time(&date, &tofs, &rdata, 4);
855 		if (up->type_gpsdate <= DTYP_W10B) {
856 			rc_date = parse_gpsw(&wgps, &rdata, 1, 2, 5);
857 			rc_dtyp = DTYP_W10B;
858 		}
859 		pp->leap = parse_qual(&rdata, 11, '0', 1);
860 		if (CLK_FLAG4 & pp->sloppyclockflag)
861 			field_wipe(&rdata, 6, 8, -1);
862 		break;
863 
864 	case NMEA_PUBX04:
865 		/* PUBX,04 is peculiar. The UTC time-of-week is the *internal*
866 		 * time base, which is not exactly on par with the fix time.
867 		 */
868 		rc_time = parse_time(&date, &tofs, &rdata, 2);
869 		if (up->type_gpsdate <= DTYP_WEXT) {
870 			rc_date = parse_gpsw(&wgps, &rdata, 5, 4, -1);
871 			rc_dtyp = DTYP_WEXT;
872 		}
873 		break;
874 
875 	default:
876 		INVARIANT(0);	/* Coverity 97123 */
877 		return;
878 	}
879 
880 	/* check clock sanity; [bug 2143] */
881 	if (pp->leap == LEAP_NOTINSYNC) { /* no good status? */
882 		checkres = CEVNT_PROP;
883 		up->tally.rejected++;
884 	}
885 	/* Check sanity of time-of-day. */
886 	else if (rc_time == 0) {	/* no time or conversion error? */
887 		checkres = CEVNT_BADTIME;
888 		up->tally.malformed++;
889 	}
890 	/* Check sanity of date. */
891 	else if (rc_date == 0) {	/* no date or conversion error? */
892 		checkres = CEVNT_BADDATE;
893 		up->tally.malformed++;
894 	}
895 	else {
896 		checkres = -1;
897 	}
898 
899 	if (checkres != -1) {
900 		refclock_save_lcode(pp, up->lb_buf, up->lb_len);
901 		refclock_report(peer, checkres);
902 		return;
903 	}
904 
905 	/* See if we can augment the receive time stamp. If not, apply
906 	 * fudge time 2 to the receive time stamp directly.
907 	 */
908 #   ifdef HAVE_PPSAPI
909 	if (up->ppsapi_lit && pp->leap != LEAP_NOTINSYNC)
910 		withpps = refclock_ppsaugment(
911 			&up->atom, &rd_timestamp,
912 			pp->fudgetime2, pp->fudgetime1);
913 	else
914 #   endif /* HAVE_PPSAPI */
915 		rd_timestamp = ntpfp_with_fudge(
916 			rd_timestamp, pp->fudgetime2);
917 
918 	/* set the GPS base date, if possible */
919 	warp = !(peer->ttl & NMEA_DATETRUST_MASK);
920 	if (rc_dtyp != DTYP_NONE) {
921 		DPRINTF(1, ("%s saving date, type=%hu\n",
922 			    refnumtoa(&peer->srcadr), rc_dtyp));
923 		switch (rc_dtyp) {
924 		case DTYP_W10B:
925 			up->last_gpsdate = gpsntp_from_gpscal_ex(
926 				&wgps, (warp = TRUE));
927 			break;
928 		case DTYP_WEXT:
929 			up->last_gpsdate = gpsntp_from_gpscal_ex(
930 				&wgps, warp);
931 			break;
932 		default:
933 			up->last_gpsdate = gpsntp_from_calendar_ex(
934 				&date, tofs, warp);
935 			break;
936 		}
937 		up->type_gpsdate = rc_dtyp;
938 		up->hold_gpsdate = DATE_HOLD;
939 	}
940 	/* now convert and possibly extend/expand the time stamp. */
941 	if (up->hold_gpsdate) {	/* time of day, based */
942 		dntp = gpsntp_from_daytime2_ex(
943 			&date, tofs, &up->last_gpsdate, warp);
944 	} else {		/* time of day, floating */
945 		dntp = gpsntp_from_daytime1_ex(
946 			&date, tofs, rd_timestamp, warp);
947 	}
948 
949 	if (debug) {
950 		/* debug print time stamp */
951 		gpsntp_to_calendar(&date, &dntp);
952 #	    ifdef HAVE_PPSAPI
953 		DPRINTF(1, ("%s effective timecode: %s (%s PPS)\n",
954 			    refnumtoa(&peer->srcadr),
955 			    ntpcal_iso8601std(NULL, 0, &date),
956 			    (withpps ? "with" : "without")));
957 #	    else /* ?HAVE_PPSAPI */
958 		DPRINTF(1, ("%s effective timecode: %s\n",
959 			    refnumtoa(&peer->srcadr),
960 			    ntpcal_iso8601std(NULL, 0, &date)));
961 #	    endif /* !HAVE_PPSAPI */
962 	}
963 
964 	/* Get the reference time stamp from the calendar buffer.
965 	 * Process the new sample in the median filter and determine the
966 	 * timecode timestamp, but only if the PPS is not in control.
967 	 * Discard sentence if reference time did not change.
968 	 */
969 	rd_reftime = ntpfp_from_ntpdatum(&dntp);
970 	if (L_ISEQU(&up->last_reftime, &rd_reftime)) {
971 		/* Do not touch pp->a_lastcode on purpose! */
972 		up->tally.filtered++;
973 		return;
974 	}
975 	up->last_reftime = rd_reftime;
976 
977 	DPRINTF(1, ("%s using '%s'\n",
978 		    refnumtoa(&peer->srcadr), up->lb_buf));
979 
980 	/* Data will be accepted. Update stats & log data. */
981 	up->tally.accepted++;
982 	refclock_save_lcode(pp, up->lb_buf, up->lb_len);
983 	pp->lastrec = rd_timestamp;
984 
985 	/* If we have PPS augmented receive time, we *must* have a
986 	 * working PPS source and we must set the flags accordingly.
987 	 */
988 #   ifdef HAVE_PPSAPI
989 	if (withpps) {
990 		up->ppsapi_gate = TRUE;
991 		peer->precision = PPS_PRECISION;
992 		if (tabsdiffd(rd_reftime, rd_timestamp) < 0.5) {
993 			if ( ! (peer->ttl & NMEA_QUIETPPS_MASK))
994 				peer->flags |= FLAG_PPS;
995 			DPRINTF(2, ("%s PPS_RELATE_PHASE\n",
996 				    refnumtoa(&peer->srcadr)));
997 			up->tally.pps_used++;
998 		} else {
999 			DPRINTF(2, ("%s PPS_RELATE_EDGE\n",
1000 				    refnumtoa(&peer->srcadr)));
1001 		}
1002 		/* !Note! 'FLAG_PPS' is reset in 'nmea_poll()' */
1003 	}
1004 #   endif /* HAVE_PPSAPI */
1005 	/* Whether the receive time stamp is PPS-augmented or not,
1006 	 * the proper fudge offset is already applied. There's no
1007 	 * residual fudge to process.
1008 	 */
1009 	refclock_process_offset(pp, rd_reftime, rd_timestamp, 0.0);
1010 	up->rcvtout = 2;
1011 }
1012 
1013 /*
1014  * -------------------------------------------------------------------
1015  * nmea_receive - receive data from the serial interface
1016  *
1017  * With serial IO only, a single call to 'refclock_gtlin()' to get the
1018  * string would suffice to get the NMEA data. When using NMEAD, this
1019  * does unfortunately no longer hold, since TCP is stream oriented and
1020  * not line oriented, and there's no one to do the line-splitting work
1021  * of the TTY driver in line/cooked mode.
1022  *
1023  * So we have to do this manually here, and we have to live with the
1024  * fact that there could be more than one sentence in a receive buffer.
1025  * Likewise, there can be partial messages on either end. (Strictly
1026  * speaking, a receive buffer could also contain just a single fragment,
1027  * though that's unlikely.)
1028  *
1029  * We deal with that by scanning the input buffer, copying bytes from
1030  * the receive buffer to the assembly buffer as we go and calling the
1031  * record processor every time we hit a CR/LF, provided the resulting
1032  * line is not empty. Any leftovers are kept for the next round.
1033  *
1034  * Note: When used with a serial data stream, there's no change to the
1035  * previous line-oriented input: One line is copied to the buffer and
1036  * processed per call. Only with NMEAD the behavior changes, and the
1037  * timing is badly affected unless a PPS channel is also associated with
1038  * the clock instance. TCP leaves us nothing to improve on here.
1039  * -------------------------------------------------------------------
1040  */
1041 static void
1042 nmea_receive(
1043 	struct recvbuf * rbufp
1044 	)
1045 {
1046 	/* declare & init control structure pointers */
1047 	struct peer	    * const peer = rbufp->recv_peer;
1048 	struct refclockproc * const pp = peer->procptr;
1049 	nmea_unit	    * const up = (nmea_unit*)pp->unitptr;
1050 
1051 	const char *sp, *se;
1052 	char	   *dp, *de;
1053 
1054 	/* paranoia check: */
1055 	if (up->lb_len >= sizeof(up->lb_buf))
1056 		up->lb_len = 0;
1057 
1058 	/* pick up last assembly position; leave room for NUL */
1059 	dp = up->lb_buf + up->lb_len;
1060 	de = up->lb_buf + sizeof(up->lb_buf) - 1;
1061 	/* set up input range */
1062 	sp = (const char *)rbufp->recv_buffer;
1063 	se = sp + rbufp->recv_length;
1064 
1065 	/* walk over the input data, dropping parity bits and control
1066 	 * chars as we go, and calling the record processor for each
1067 	 * complete non-empty line.
1068 	 */
1069 	while (sp != se) {
1070 		char ch = (*sp++ & 0x7f);
1071 		if (dp == up->lb_buf) {
1072 			if (ch == '$')
1073 				*dp++ = ch;
1074 		} else if (dp > de) {
1075 			dp = up->lb_buf;
1076 		} else if (ch == '\n' || ch == '\r') {
1077 			*dp = '\0';
1078 			up->lb_len = (int)(dp - up->lb_buf);
1079 			dp = up->lb_buf;
1080 			nmea_procrec(peer, rbufp->recv_time);
1081 		} else if (ch >= 0x20 && ch < 0x7f) {
1082 			*dp++ = ch;
1083 		}
1084 	}
1085 	/* update state to keep for next round */
1086 	*dp = '\0';
1087 	up->lb_len = (int)(dp - up->lb_buf);
1088 }
1089 
1090 /*
1091  * -------------------------------------------------------------------
1092  * nmea_poll - called by the transmit procedure
1093  *
1094  * Does the necessary bookkeeping stuff to keep the reported state of
1095  * the clock in sync with reality.
1096  *
1097  * We go to great pains to avoid changing state here, since there may
1098  * be more than one eavesdropper receiving the same timecode.
1099  * -------------------------------------------------------------------
1100  */
1101 static void
1102 nmea_poll(
1103 	int           unit,
1104 	struct peer * peer
1105 	)
1106 {
1107 	struct refclockproc * const pp = peer->procptr;
1108 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
1109 
1110 	/*
1111 	 * Process median filter samples. If none received, declare a
1112 	 * timeout and keep going.
1113 	 */
1114 #   ifdef HAVE_PPSAPI
1115 	/*
1116 	 * If we don't have PPS pulses and time stamps, turn PPS down
1117 	 * for now.
1118 	 */
1119 	if (!up->ppsapi_gate) {
1120 		peer->flags &= ~FLAG_PPS;
1121 		peer->precision = PRECISION;
1122 	} else {
1123 		up->ppsapi_gate = FALSE;
1124 	}
1125 #   endif /* HAVE_PPSAPI */
1126 
1127 	/*
1128 	 * If the median filter is empty, claim a timeout. Else process
1129 	 * the input data and keep the stats going.
1130 	 */
1131 	if (pp->coderecv == pp->codeproc) {
1132 		peer->flags &= ~FLAG_PPS;
1133 		if (pp->currentstatus < CEVNT_TIMEOUT)
1134 		    refclock_report(peer, CEVNT_TIMEOUT);
1135 		memset(&up->last_gpsdate, 0, sizeof(up->last_gpsdate));
1136 	} else {
1137 		pp->polls++;
1138 		pp->lastref = pp->lastrec;
1139 		refclock_receive(peer);
1140 		if (pp->currentstatus > CEVNT_NOMINAL)
1141 		    refclock_report(peer, CEVNT_NOMINAL);
1142 	}
1143 
1144 	/*
1145 	 * If extended logging is required, write the tally stats to the
1146 	 * clockstats file; otherwise just do a normal clock stats
1147 	 * record. Clear the tally stats anyway.
1148 	*/
1149 	if (peer->ttl & NMEA_EXTLOG_MASK) {
1150 		/* Log & reset counters with extended logging */
1151 		const char *nmea = pp->a_lastcode;
1152 		if (*nmea == '\0') nmea = "(none)";
1153 		mprintf_clock_stats(
1154 		  &peer->srcadr, "%s  %u %u %u %u %u %u",
1155 		  nmea,
1156 		  up->tally.total, up->tally.accepted,
1157 		  up->tally.rejected, up->tally.malformed,
1158 		  up->tally.filtered, up->tally.pps_used);
1159 	} else {
1160 		record_clock_stats(&peer->srcadr, pp->a_lastcode);
1161 	}
1162 	ZERO(up->tally);
1163 }
1164 
1165 #if NMEA_WRITE_SUPPORT
1166 /*
1167  * -------------------------------------------------------------------
1168  *  gps_send(fd, cmd, peer)	Sends a command to the GPS receiver.
1169  *   as in gps_send(fd, "rqts,u", peer);
1170  *
1171  * If 'cmd' starts with a '$' it is assumed that this command is in raw
1172  * format, that is, starts with '$', ends with '<cr><lf>' and that any
1173  * checksum is correctly provided; the command will be send 'as is' in
1174  * that case. Otherwise the function will create the necessary frame
1175  * (start char, chksum, final CRLF) on the fly.
1176  *
1177  * We don't currently send any data, but would like to send RTCM SC104
1178  * messages for differential positioning. It should also give us better
1179  * time. Without a PPS output, we're Just fooling ourselves because of
1180  * the serial code paths
1181  * -------------------------------------------------------------------
1182  */
1183 static void
1184 gps_send(
1185 	int           fd,
1186 	const char  * cmd,
1187 	struct peer * peer
1188 	)
1189 {
1190 	/* $...*xy<CR><LF><NUL> add 7 */
1191 	char	      buf[NMEA_PROTO_MAXLEN + 7];
1192 	int	      len;
1193 	u_char	      dcs;
1194 	const u_char *beg, *end;
1195 
1196 	if (*cmd != '$') {
1197 		/* get checksum and length */
1198 		beg = end = (const u_char*)cmd;
1199 		dcs = 0;
1200 		while (*end >= ' ' && *end != '*')
1201 			dcs ^= *end++;
1202 		len = end - beg;
1203 		/* format into output buffer with overflow check */
1204 		len = snprintf(buf, sizeof(buf), "$%.*s*%02X\r\n",
1205 			       len, beg, dcs);
1206 		if ((size_t)len >= sizeof(buf)) {
1207 			DPRINTF(1, ("%s gps_send: buffer overflow for command '%s'\n",
1208 				    refnumtoa(&peer->srcadr), cmd));
1209 			return;	/* game over player 1 */
1210 		}
1211 		cmd = buf;
1212 	} else {
1213 		len = strlen(cmd);
1214 	}
1215 
1216 	DPRINTF(1, ("%s gps_send: '%.*s'\n", refnumtoa(&peer->srcadr),
1217 		len - 2, cmd));
1218 
1219 	/* send out the whole stuff */
1220 	if (write(fd, cmd, len) == -1)
1221 		refclock_report(peer, CEVNT_FAULT);
1222 }
1223 #endif /* NMEA_WRITE_SUPPORT */
1224 
1225 /*
1226  * -------------------------------------------------------------------
1227  * helpers for faster field splitting
1228  * -------------------------------------------------------------------
1229  *
1230  * set up a field record, check syntax and verify checksum
1231  *
1232  * format is $XXXXX,1,2,3,4*ML
1233  *
1234  * 8-bit XOR of characters between $ and * noninclusive is transmitted
1235  * in last two chars M and L holding most and least significant nibbles
1236  * in hex representation such as:
1237  *
1238  *   $GPGLL,5057.970,N,00146.110,E,142451,A*27
1239  *   $GPVTG,089.0,T,,,15.2,N,,*7F
1240  *
1241  * Some other constraints:
1242  * + The field name must be at least 5 upcase characters or digits and
1243  *   must start with a character.
1244  * + The checksum (if present) must be uppercase hex digits.
1245  * + The length of a sentence is limited to 80 characters (not including
1246  *   the final CR/LF nor the checksum, but including the leading '$')
1247  *
1248  * Return values:
1249  *  + CHECK_INVALID
1250  *	The data does not form a valid NMEA sentence or a checksum error
1251  *	occurred.
1252  *  + CHECK_VALID
1253  *	The data is a valid NMEA sentence but contains no checksum.
1254  *  + CHECK_CSVALID
1255  *	The data is a valid NMEA sentence and passed the checksum test.
1256  * -------------------------------------------------------------------
1257  */
1258 static int
1259 field_init(
1260 	nmea_data * data,	/* context structure		       */
1261 	char 	  * cptr,	/* start of raw data		       */
1262 	int	    dlen	/* data len, not counting trailing NUL */
1263 	)
1264 {
1265 	u_char cs_l;	/* checksum local computed	*/
1266 	u_char cs_r;	/* checksum remote given	*/
1267 	char * eptr;	/* buffer end end pointer	*/
1268 	char   tmp;	/* char buffer 			*/
1269 
1270 	cs_l = 0;
1271 	cs_r = 0;
1272 	/* some basic input constraints */
1273 	if (dlen < 0)
1274 		dlen = 0;
1275 	eptr = cptr + dlen;
1276 	*eptr = '\0';
1277 
1278 	/* load data context */
1279 	data->base = cptr;
1280 	data->cptr = cptr;
1281 	data->cidx = 0;
1282 	data->blen = dlen;
1283 
1284 	/* syntax check follows here. check allowed character
1285 	 * sequences, updating the local computed checksum as we go.
1286 	 *
1287 	 * regex equiv: '^\$[A-Z][A-Z0-9]{4,}[^*]*(\*[0-9A-F]{2})?$'
1288 	 */
1289 
1290 	/* -*- start character: '^\$' */
1291 	if (*cptr == '\0')
1292 		return CHECK_EMPTY;
1293 	if (*cptr++ != '$')
1294 		return CHECK_INVALID;
1295 
1296 	/* -*- advance context beyond start character */
1297 	data->base++;
1298 	data->cptr++;
1299 	data->blen--;
1300 
1301 	/* -*- field name: '[A-Z][A-Z0-9]{4,},' */
1302 	if (*cptr < 'A' || *cptr > 'Z')
1303 		return CHECK_INVALID;
1304 	cs_l ^= *cptr++;
1305 	while ((*cptr >= 'A' && *cptr <= 'Z') ||
1306 	       (*cptr >= '0' && *cptr <= '9')  )
1307 		cs_l ^= *cptr++;
1308 	if (*cptr != ',' || (cptr - data->base) < NMEA_PROTO_IDLEN)
1309 		return CHECK_INVALID;
1310 	cs_l ^= *cptr++;
1311 
1312 	/* -*- data: '[^*]*' */
1313 	while (*cptr && *cptr != '*')
1314 		cs_l ^= *cptr++;
1315 
1316 	/* -*- checksum field: (\*[0-9A-F]{2})?$ */
1317 	if (*cptr == '\0')
1318 		return CHECK_VALID;
1319 	if (*cptr != '*' || cptr != eptr - 3 ||
1320 	    (cptr - data->base) >= NMEA_PROTO_MAXLEN)
1321 		return CHECK_INVALID;
1322 
1323 	for (cptr++; (tmp = *cptr) != '\0'; cptr++) {
1324 		if (tmp >= '0' && tmp <= '9')
1325 			cs_r = (cs_r << 4) + (tmp - '0');
1326 		else if (tmp >= 'A' && tmp <= 'F')
1327 			cs_r = (cs_r << 4) + (tmp - 'A' + 10);
1328 		else
1329 			break;
1330 	}
1331 
1332 	/* -*- make sure we are at end of string and csum matches */
1333 	if (cptr != eptr || cs_l != cs_r)
1334 		return CHECK_INVALID;
1335 
1336 	return CHECK_CSVALID;
1337 }
1338 
1339 /*
1340  * -------------------------------------------------------------------
1341  * fetch a data field by index, zero being the name field. If this
1342  * function is called repeatedly with increasing indices, the total load
1343  * is O(n), n being the length of the string; if it is called with
1344  * decreasing indices, the total load is O(n^2). Try not to go backwards
1345  * too often.
1346  * -------------------------------------------------------------------
1347  */
1348 static char *
1349 field_parse(
1350 	nmea_data * data,
1351 	int 	    fn
1352 	)
1353 {
1354 	char tmp;
1355 
1356 	if (fn < data->cidx) {
1357 		data->cidx = 0;
1358 		data->cptr = data->base;
1359 	}
1360 	while ((fn > data->cidx) && (tmp = *data->cptr) != '\0') {
1361 		data->cidx += (tmp == ',');
1362 		data->cptr++;
1363 	}
1364 	return data->cptr;
1365 }
1366 
1367 /*
1368  * -------------------------------------------------------------------
1369  * Wipe (that is, overwrite with '_') data fields and the checksum in
1370  * the last timecode.  The list of field indices is given as integers
1371  * in a varargs list, preferably in ascending order, in any case
1372  * terminated by a negative field index.
1373  *
1374  * A maximum number of 8 fields can be overwritten at once to guard
1375  * against runaway (that is, unterminated) argument lists.
1376  *
1377  * This function affects what a remote user can see with
1378  *
1379  * ntpq -c clockvar <server>
1380  *
1381  * Note that this also removes the wiped fields from any clockstats
1382  * log.	 Some NTP operators monitor their NMEA GPS using the change in
1383  * location in clockstats over time as as a proxy for the quality of
1384  * GPS reception and thereby time reported.
1385  * -------------------------------------------------------------------
1386  */
1387 static void
1388 field_wipe(
1389 	nmea_data * data,
1390 	...
1391 	)
1392 {
1393 	va_list	va;		/* vararg index list */
1394 	int	fcnt;		/* safeguard against runaway arglist */
1395 	int	fidx;		/* field to nuke, or -1 for checksum */
1396 	char  * cp;		/* overwrite destination */
1397 
1398 	fcnt = 8;
1399 	cp = NULL;
1400 	va_start(va, data);
1401 	do {
1402 		fidx = va_arg(va, int);
1403 		if (fidx >= 0 && fidx <= NMEA_PROTO_FIELDS) {
1404 			cp = field_parse(data, fidx);
1405 		} else {
1406 			cp = data->base + data->blen;
1407 			if (data->blen >= 3 && cp[-3] == '*')
1408 				cp -= 2;
1409 		}
1410 		for ( ; '\0' != *cp && '*' != *cp && ',' != *cp; cp++)
1411 			if ('.' != *cp)
1412 				*cp = '_';
1413 	} while (fcnt-- && fidx >= 0);
1414 	va_end(va);
1415 }
1416 
1417 /*
1418  * -------------------------------------------------------------------
1419  * PARSING HELPERS
1420  * -------------------------------------------------------------------
1421  */
1422 typedef unsigned char const UCC;
1423 
1424 static char const * const s_eof_chars = ",*\r\n";
1425 
1426 static int field_length(UCC *cp, unsigned int nfields)
1427 {
1428 	char const * ep = (char const*)cp;
1429 	ep = strpbrk(ep, s_eof_chars);
1430 	if (ep && nfields)
1431 		while (--nfields && ep && *ep == ',')
1432 			ep = strpbrk(ep + 1, s_eof_chars);
1433 	return (ep)
1434 	    ? (int)((UCC*)ep - cp)
1435 	    : (int)strlen((char const*)cp);
1436 }
1437 
1438 /* /[,*\r\n]/ --> skip */
1439 static int _parse_eof(UCC *cp, UCC ** ep)
1440 {
1441 	int rc = (strchr(s_eof_chars, *(char const*)cp) != NULL);
1442 	*ep = cp + rc;
1443 	return rc;
1444 }
1445 
1446 /* /,/ --> skip */
1447 static int _parse_sep(UCC *cp, UCC ** ep)
1448 {
1449 	int rc = (*cp == ',');
1450 	*ep = cp + rc;
1451 	return rc;
1452 }
1453 
1454 /* /[[:digit:]]{2}/ --> uint16_t */
1455 static int _parse_num2d(UCC *cp, UCC ** ep, uint16_t *into)
1456 {
1457 	int	rc = FALSE;
1458 
1459 	if (isdigit(cp[0]) && isdigit(cp[1])) {
1460 		*into = (cp[0] - '0') * 10 + (cp[1] - '0');
1461 		cp += 2;
1462 		rc = TRUE;
1463 	}
1464 	*ep = cp;
1465 	return rc;
1466 }
1467 
1468 /* /[[:digit:]]+/ --> uint16_t */
1469 static int _parse_u16(UCC *cp, UCC **ep, uint16_t *into, unsigned int ndig)
1470 {
1471 	uint16_t	num = 0;
1472 	int		rc  = FALSE;
1473 	if (isdigit(*cp) && ndig) {
1474 		rc = TRUE;
1475 		do
1476 			num = (num * 10) + (*cp - '0');
1477 		while (isdigit(*++cp) && --ndig);
1478 		*into = num;
1479 	}
1480 	*ep = cp;
1481 	return rc;
1482 }
1483 
1484 /* /[[:digit:]]+/ --> uint32_t */
1485 static int _parse_u32(UCC *cp, UCC **ep, uint32_t *into, unsigned int ndig)
1486 {
1487 	uint32_t	num = 0;
1488 	int		rc  = FALSE;
1489 	if (isdigit(*cp) && ndig) {
1490 		rc = TRUE;
1491 		do
1492 			num = (num * 10) + (*cp - '0');
1493 		while (isdigit(*++cp) && --ndig);
1494 		*into = num;
1495 	}
1496 	*ep = cp;
1497 	return rc;
1498 }
1499 
1500 /* /(\.[[:digit:]]*)?/ --> l_fp{0, f}
1501  * read fractional seconds, convert to l_fp
1502  *
1503  * Only the first 9 decimal digits are evaluated; any excess is parsed
1504  * away but silently ignored. (--> truncation to 1 nanosecond)
1505  */
1506 static int _parse_frac(UCC *cp, UCC **ep, l_fp *into)
1507 {
1508 	static const uint32_t powtab[10] = {
1509 		        0,
1510 		100000000, 10000000, 1000000,
1511 		   100000,    10000,    1000,
1512 		      100,       10,       1
1513 	};
1514 
1515 	struct timespec	ts;
1516 	ZERO(ts);
1517 	if (*cp == '.') {
1518 		uint32_t fval = 0;
1519 		UCC *    sp   = cp + 1;
1520 		if (_parse_u32(sp, &cp, &fval, 9))
1521 			ts.tv_nsec = fval * powtab[(size_t)(cp - sp)];
1522 		while (isdigit(*cp))
1523 			++cp;
1524 	}
1525 
1526 	*ep   = cp;
1527 	*into = tspec_intv_to_lfp(ts);
1528 	return TRUE;
1529 }
1530 
1531 /* /[[:digit:]]{6}/ --> time-of-day
1532  * parses a number string representing 'HHMMSS'
1533  */
1534 static int _parse_time(UCC *cp, UCC ** ep, TCivilDate *into)
1535 {
1536 	uint16_t	s, m, h;
1537 	int		rc;
1538 	UCC *		xp = cp;
1539 
1540 	rc =   _parse_num2d(cp, &cp, &h) && (h < 24)
1541 	    && _parse_num2d(cp, &cp, &m) && (m < 60)
1542 	    && _parse_num2d(cp, &cp, &s) && (s < 61); /* leap seconds! */
1543 
1544 	if (rc) {
1545 		into->hour   = (uint8_t)h;
1546 		into->minute = (uint8_t)m;
1547 		into->second = (uint8_t)s;
1548 		*ep = cp;
1549 	} else {
1550 		*ep = xp;
1551 		DPRINTF(1, ("nmea: invalid time code: '%.*s'\n",
1552 			    field_length(xp, 1), xp));
1553 	}
1554 	return rc;
1555 }
1556 
1557 /* /[[:digit:]]{6}/ --> civil date
1558  * parses a number string representing 'ddmmyy'
1559  */
1560 static int _parse_date1(UCC *cp, UCC **ep, TCivilDate *into)
1561 {
1562 	unsigned short	d, m, y;
1563 	int		rc;
1564 	UCC *		xp = cp;
1565 
1566 	rc =   _parse_num2d(cp, &cp, &d) && (d - 1 < 31)
1567 	    && _parse_num2d(cp, &cp, &m) && (m - 1 < 12)
1568 	    && _parse_num2d(cp, &cp, &y)
1569 	    && _parse_eof(cp, ep);
1570 	if (rc) {
1571 		into->monthday = (uint8_t )d;
1572 		into->month    = (uint8_t )m;
1573 		into->year     = (uint16_t)y;
1574 		*ep = cp;
1575 	} else {
1576 		*ep = xp;
1577 		DPRINTF(1, ("nmea: invalid date code: '%.*s'\n",
1578 			    field_length(xp, 1), xp));
1579 	}
1580 	return rc;
1581 }
1582 
1583 /* /[[:digit:]]+,[[:digit:]]+,[[:digit:]]+/ --> civil date
1584  * parses three successive numeric fields as date: day,month,year
1585  */
1586 static int _parse_date3(UCC *cp, UCC **ep, TCivilDate *into)
1587 {
1588 	uint16_t	d, m, y;
1589 	int		rc;
1590 	UCC *		xp = cp;
1591 
1592 	rc =   _parse_u16(cp, &cp, &d, 2) && (d - 1 < 31)
1593 	    && _parse_sep(cp, &cp)
1594 	    && _parse_u16(cp, &cp, &m, 2) && (m - 1 < 12)
1595 	    && _parse_sep(cp, &cp)
1596 	    && _parse_u16(cp, &cp, &y, 4) && (y > 1980)
1597 	    && _parse_eof(cp, ep);
1598 	if (rc) {
1599 		into->monthday = (uint8_t )d;
1600 		into->month    = (uint8_t )m;
1601 		into->year     = (uint16_t)y;
1602 		*ep = cp;
1603 	} else {
1604 		*ep = xp;
1605 		DPRINTF(1, ("nmea: invalid date code: '%.*s'\n",
1606 			    field_length(xp, 3), xp));
1607 	}
1608 	return rc;
1609 }
1610 
1611 /*
1612  * -------------------------------------------------------------------
1613  * Check sync status
1614  *
1615  * If the character at the data field start matches the tag value,
1616  * return LEAP_NOWARNING and LEAP_NOTINSYNC otherwise. If the 'inverted'
1617  * flag is given, just the opposite value is returned. If there is no
1618  * data field (*cp points to the NUL byte) the result is LEAP_NOTINSYNC.
1619  * -------------------------------------------------------------------
1620  */
1621 static u_char
1622 parse_qual(
1623 	nmea_data * rd,
1624 	int         idx,
1625 	char        tag,
1626 	int         inv
1627 	)
1628 {
1629 	static const u_char table[2] = {
1630 		LEAP_NOTINSYNC, LEAP_NOWARNING };
1631 
1632 	char * dp = field_parse(rd, idx);
1633 
1634 	return table[ *dp && ((*dp == tag) == !inv) ];
1635 }
1636 
1637 /*
1638  * -------------------------------------------------------------------
1639  * Parse a time stamp in HHMMSS[.sss] format with error checking.
1640  *
1641  * returns 1 on success, 0 on failure
1642  * -------------------------------------------------------------------
1643  */
1644 static int
1645 parse_time(
1646 	struct calendar * jd,	/* result calendar pointer */
1647 	l_fp		* fofs,	/* storage for nsec fraction */
1648 	nmea_data       * rd,
1649 	int		  idx
1650 	)
1651 {
1652 	UCC * 	dp = (UCC*)field_parse(rd, idx);
1653 
1654 	return _parse_time(dp, &dp, jd)
1655 	    && _parse_frac(dp, &dp, fofs)
1656 	    && _parse_eof (dp, &dp);
1657 }
1658 
1659 /*
1660  * -------------------------------------------------------------------
1661  * Parse a date string from an NMEA sentence. This could either be a
1662  * partial date in DDMMYY format in one field, or DD,MM,YYYY full date
1663  * spec spanning three fields. This function does some extensive error
1664  * checking to make sure the date string was consistent.
1665  *
1666  * returns 1 on success, 0 on failure
1667  * -------------------------------------------------------------------
1668  */
1669 static int
1670 parse_date(
1671 	struct calendar * jd,	/* result pointer */
1672 	nmea_data       * rd,
1673 	int		  idx,
1674 	enum date_fmt	  fmt
1675 	)
1676 {
1677 	UCC  * dp = (UCC*)field_parse(rd, idx);
1678 
1679 	switch (fmt) {
1680 	case DATE_1_DDMMYY:
1681 		return _parse_date1(dp, &dp, jd);
1682 	case DATE_3_DDMMYYYY:
1683 		return _parse_date3(dp, &dp, jd);
1684 	default:
1685 		DPRINTF(1, ("nmea: invalid parse format: %d\n", fmt));
1686 		break;
1687 	}
1688 	return FALSE;
1689 }
1690 
1691 /*
1692  * -------------------------------------------------------------------
1693  * Parse GPS week time info from an NMEA sentence. This info contains
1694  * the GPS week number, the GPS time-of-week and the leap seconds GPS
1695  * to UTC.
1696  *
1697  * returns 1 on success, 0 on failure
1698  * -------------------------------------------------------------------
1699  */
1700 static int
1701 parse_gpsw(
1702 	TGpsDatum *  wd,
1703 	nmea_data *  rd,
1704 	int          weekidx,
1705 	int          timeidx,
1706 	int          leapidx
1707 	)
1708 {
1709 	uint32_t	secs;
1710 	uint16_t	week, leap = 0;
1711 	l_fp		fofs;
1712 	int		rc;
1713 
1714 	UCC *	dpw = (UCC*)field_parse(rd, weekidx);
1715 	UCC *	dps = (UCC*)field_parse(rd, timeidx);
1716 
1717 	rc =   _parse_u16 (dpw, &dpw, &week, 5)
1718 	    && _parse_eof (dpw, &dpw)
1719 	    && _parse_u32 (dps, &dps, &secs, 9)
1720 	    && _parse_frac(dps, &dps, &fofs)
1721 	    && _parse_eof (dps, &dps)
1722 	    && (secs < 7*SECSPERDAY);
1723 	if (rc && leapidx > 0) {
1724 		UCC *	dpl = (UCC*)field_parse(rd, leapidx);
1725 		rc =   _parse_u16 (dpl, &dpl, &leap, 5)
1726 		    && _parse_eof (dpl, &dpl);
1727 	}
1728 	if (rc) {
1729 		fofs.l_ui -= leap;
1730 		*wd = gpscal_from_gpsweek(week, secs, fofs);
1731 	} else {
1732 		DPRINTF(1, ("nmea: parse_gpsw: invalid weektime spec\n"));
1733 	}
1734 	return rc;
1735 }
1736 
1737 
1738 #ifdef HAVE_PPSAPI
1739 static double
1740 tabsdiffd(
1741 	l_fp	t1,
1742 	l_fp	t2
1743 	)
1744 {
1745 	double	dd;
1746 	L_SUB(&t1, &t2);
1747 	LFPTOD(&t1, dd);
1748 	return fabs(dd);
1749 }
1750 #endif /* HAVE_PPSAPI */
1751 
1752 /*
1753  * ===================================================================
1754  *
1755  * NMEAD support
1756  *
1757  * original nmead support added by Jon Miner (cp_n18@yahoo.com)
1758  *
1759  * See http://home.hiwaay.net/~taylorc/gps/nmea-server/
1760  * for information about nmead
1761  *
1762  * To use this, you need to create a link from /dev/gpsX to
1763  * the server:port where nmead is running.  Something like this:
1764  *
1765  * ln -s server:port /dev/gps1
1766  *
1767  * Split into separate function by Juergen Perlinger
1768  * (perlinger-at-ntp-dot-org)
1769  *
1770  * ===================================================================
1771  */
1772 static int
1773 nmead_open(
1774 	const char * device
1775 	)
1776 {
1777 	int	fd = -1;		/* result file descriptor */
1778 
1779 #   ifdef HAVE_READLINK
1780 	char	host[80];		/* link target buffer	*/
1781 	char  * port;			/* port name or number	*/
1782 	int	rc;			/* result code (several)*/
1783 	int     sh;			/* socket handle	*/
1784 	struct addrinfo	 ai_hint;	/* resolution hint	*/
1785 	struct addrinfo	*ai_list;	/* resolution result	*/
1786 	struct addrinfo *ai;		/* result scan ptr	*/
1787 
1788 	fd = -1;
1789 
1790 	/* try to read as link, make sure no overflow occurs */
1791 	rc = readlink(device, host, sizeof(host));
1792 	if ((size_t)rc >= sizeof(host))
1793 		return fd;	/* error / overflow / truncation */
1794 	host[rc] = '\0';	/* readlink does not place NUL	*/
1795 
1796 	/* get port */
1797 	port = strchr(host, ':');
1798 	if (!port)
1799 		return fd; /* not 'host:port' syntax ? */
1800 	*port++ = '\0';	/* put in separator */
1801 
1802 	/* get address infos and try to open socket
1803 	 *
1804 	 * This getaddrinfo() is naughty in ntpd's nonblocking main
1805 	 * thread, but you have to go out of your wary to use this code
1806 	 * and typically the blocking is at startup where its impact is
1807 	 * reduced. The same holds for the 'connect()', as it is
1808 	 * blocking, too...
1809 	 */
1810 	ZERO(ai_hint);
1811 	ai_hint.ai_protocol = IPPROTO_TCP;
1812 	ai_hint.ai_socktype = SOCK_STREAM;
1813 	if (getaddrinfo(host, port, &ai_hint, &ai_list))
1814 		return fd;
1815 
1816 	for (ai = ai_list; ai && (fd == -1); ai = ai->ai_next) {
1817 		sh = socket(ai->ai_family, ai->ai_socktype,
1818 			    ai->ai_protocol);
1819 		if (INVALID_SOCKET == sh)
1820 			continue;
1821 		rc = connect(sh, ai->ai_addr, ai->ai_addrlen);
1822 		if (-1 != rc)
1823 			fd = sh;
1824 		else
1825 			close(sh);
1826 	}
1827 	freeaddrinfo(ai_list);
1828 	if (fd != -1)
1829 		make_socket_nonblocking(fd);
1830 #   else
1831 	fd = -1;
1832 #   endif
1833 
1834 	return fd;
1835 }
1836 #else
1837 NONEMPTY_TRANSLATION_UNIT
1838 #endif /* REFCLOCK && CLOCK_NMEA */
1839