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