xref: /openbsd-src/sys/kern/tty_endrun.c (revision e5157e49389faebcb42b7237d55fbf096d9c2523)
1 /*	$OpenBSD: tty_endrun.c,v 1.6 2014/11/03 03:08:00 deraadt Exp $ */
2 
3 /*
4  * Copyright (c) 2008 Marc Balmer <mbalmer@openbsd.org>
5  * Copyright (c) 2009 Kevin Steves <stevesk@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*
21  * A tty line discipline to decode the EndRun Technologies native
22  * time-of-day message.
23  * http://www.endruntechnologies.com/
24  */
25 
26 /*
27  * EndRun Format:
28  *
29  * T YYYY DDD HH:MM:SS zZZ m<CR><LF>
30  *
31  * T is the Time Figure of Merit (TFOM) character (described below).
32  * This is the on-time character, transmitted during the first
33  * millisecond of each second.
34  *
35  * YYYY is the year
36  * DDD is the day-of-year
37  * : is the colon character (0x3A)
38  * HH is the hour of the day
39  * MM is the minute of the hour
40  * SS is the second of the minute
41  * z is the sign of the offset to UTC, + implies time is ahead of UTC.
42  * ZZ is the magnitude of the offset to UTC in units of half-hours.
43  * Non-zero only when the Timemode is Local.
44  * m is the Timemode character and is one of:
45  *   G = GPS
46  *   L = Local
47  *   U = UTC
48  * <CR> is the ASCII carriage return character (0x0D)
49  * <LF> is the ASCII line feed character (0x0A)
50  */
51 
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/malloc.h>
55 #include <sys/sensors.h>
56 #include <sys/tty.h>
57 #include <sys/conf.h>
58 #include <sys/time.h>
59 
60 #ifdef ENDRUN_DEBUG
61 #define DPRINTFN(n, x)	do { if (endrundebug > (n)) printf x; } while (0)
62 int endrundebug = 0;
63 #else
64 #define DPRINTFN(n, x)
65 #endif
66 #define DPRINTF(x)	DPRINTFN(0, x)
67 
68 int	endrunopen(dev_t, struct tty *, struct proc *p);
69 int	endrunclose(struct tty *, int, struct proc *p);
70 int	endruninput(int, struct tty *);
71 void	endrunattach(int);
72 
73 #define ENDRUNLEN	27 /* strlen("6 2009 018 20:41:17 +00 U\r\n") */
74 #define NUMFLDS		6
75 #ifdef ENDRUN_DEBUG
76 #define TRUSTTIME	30
77 #else
78 #define TRUSTTIME	(10 * 60)	/* 10 minutes */
79 #endif
80 
81 int endrun_count, endrun_nxid;
82 
83 struct endrun {
84 	char			cbuf[ENDRUNLEN];	/* receive buffer */
85 	struct ksensor		time;		/* the timedelta sensor */
86 	struct ksensor		signal;		/* signal status */
87 	struct ksensordev	timedev;
88 	struct timespec		ts;		/* current timestamp */
89 	struct timespec		lts;		/* timestamp of last TFOM */
90 	struct timeout		endrun_tout;	/* invalidate sensor */
91 	int64_t			gap;		/* gap between two sentences */
92 	int64_t			last;		/* last time rcvd */
93 #define SYNC_SCAN	1	/* scanning for '\n' */
94 #define SYNC_EOL	2	/* '\n' seen, next char TFOM */
95 	int			sync;
96 	int			pos;		/* position in rcv buffer */
97 	int			no_pps;		/* no PPS although requested */
98 #ifdef ENDRUN_DEBUG
99 	char			tfom;
100 #endif
101 };
102 
103 /* EndRun decoding */
104 void	endrun_scan(struct endrun *, struct tty *);
105 void	endrun_decode(struct endrun *, struct tty *, char *fld[], int fldcnt);
106 
107 /* date and time conversion */
108 int	endrun_atoi(char *s, int len);
109 int	endrun_date_to_nano(char *s1, char *s2, int64_t *nano);
110 int	endrun_time_to_nano(char *s, int64_t *nano);
111 int	endrun_offset_to_nano(char *s, int64_t *nano);
112 
113 /* degrade the timedelta sensor */
114 void	endrun_timeout(void *);
115 
116 void
117 endrunattach(int dummy)
118 {
119 }
120 
121 int
122 endrunopen(dev_t dev, struct tty *tp, struct proc *p)
123 {
124 	struct endrun *np;
125 	int error;
126 
127 	DPRINTF(("endrunopen\n"));
128 	if (tp->t_line == ENDRUNDISC)
129 		return ENODEV;
130 	if ((error = suser(p, 0)) != 0)
131 		return error;
132 	np = malloc(sizeof(struct endrun), M_DEVBUF, M_WAITOK|M_ZERO);
133 	snprintf(np->timedev.xname, sizeof(np->timedev.xname), "endrun%d",
134 	    endrun_nxid++);
135 	endrun_count++;
136 	np->time.status = SENSOR_S_UNKNOWN;
137 	np->time.type = SENSOR_TIMEDELTA;
138 #ifndef ENDRUN_DEBUG
139 	np->time.flags = SENSOR_FINVALID;
140 #endif
141 	sensor_attach(&np->timedev, &np->time);
142 
143 	np->signal.type = SENSOR_PERCENT;
144 	np->signal.status = SENSOR_S_UNKNOWN;
145 	np->signal.value = 100000LL;
146 	strlcpy(np->signal.desc, "Signal", sizeof(np->signal.desc));
147 	sensor_attach(&np->timedev, &np->signal);
148 
149 	np->sync = SYNC_SCAN;
150 #ifdef ENDRUN_DEBUG
151 	np->tfom = '0';
152 #endif
153 	tp->t_sc = (caddr_t)np;
154 
155 	error = linesw[TTYDISC].l_open(dev, tp, p);
156 	if (error) {
157 		free(np, M_DEVBUF, sizeof(*np));
158 		tp->t_sc = NULL;
159 	} else {
160 		sensordev_install(&np->timedev);
161 		timeout_set(&np->endrun_tout, endrun_timeout, np);
162 	}
163 
164 	return error;
165 }
166 
167 int
168 endrunclose(struct tty *tp, int flags, struct proc *p)
169 {
170 	struct endrun *np = (struct endrun *)tp->t_sc;
171 
172 	DPRINTF(("endrunclose\n"));
173 	tp->t_line = TTYDISC;	/* switch back to termios */
174 	timeout_del(&np->endrun_tout);
175 	sensordev_deinstall(&np->timedev);
176 	free(np, M_DEVBUF, sizeof(*np));
177 	tp->t_sc = NULL;
178 	endrun_count--;
179 	if (endrun_count == 0)
180 		endrun_nxid = 0;
181 	return linesw[TTYDISC].l_close(tp, flags, p);
182 }
183 
184 /* collect EndRun sentence from tty */
185 int
186 endruninput(int c, struct tty *tp)
187 {
188 	struct endrun *np = (struct endrun *)tp->t_sc;
189 	struct timespec ts;
190 	int64_t gap;
191 	long tmin, tmax;
192 
193 	if (np->sync == SYNC_EOL) {
194 		nanotime(&ts);
195 		np->pos = 0;
196 		np->sync = SYNC_SCAN;
197 		np->cbuf[np->pos++] = c; /* TFOM char */
198 
199 		gap = (ts.tv_sec * 1000000000LL + ts.tv_nsec) -
200 		    (np->lts.tv_sec * 1000000000LL + np->lts.tv_nsec);
201 
202 		np->lts.tv_sec = ts.tv_sec;
203 		np->lts.tv_nsec = ts.tv_nsec;
204 
205 		if (gap <= np->gap)
206 			goto nogap;
207 
208 		np->ts.tv_sec = ts.tv_sec;
209 		np->ts.tv_nsec = ts.tv_nsec;
210 		np->gap = gap;
211 
212 		/*
213 		 * If a tty timestamp is available, make sure its value is
214 		 * reasonable by comparing against the timestamp just taken.
215 		 * If they differ by more than 2 seconds, assume no PPS signal
216 		 * is present, note the fact, and keep using the timestamp
217 		 * value.  When this happens, the sensor state is set to
218 		 * CRITICAL later when the EndRun sentence is decoded.
219 		 */
220 		if (tp->t_flags & (TS_TSTAMPDCDSET | TS_TSTAMPDCDCLR |
221 		    TS_TSTAMPCTSSET | TS_TSTAMPCTSCLR)) {
222 			tmax = lmax(np->ts.tv_sec, tp->t_tv.tv_sec);
223 			tmin = lmin(np->ts.tv_sec, tp->t_tv.tv_sec);
224 			if (tmax - tmin > 1)
225 				np->no_pps = 1;
226 			else {
227 				np->ts.tv_sec = tp->t_tv.tv_sec;
228 				np->ts.tv_nsec = tp->t_tv.tv_usec *
229 				    1000L;
230 				np->no_pps = 0;
231 			}
232 		}
233 	} else if (c == '\n') {
234 		if (np->pos == ENDRUNLEN - 1) {
235 			/* don't copy '\n' into cbuf */
236 			np->cbuf[np->pos] = '\0';
237 			endrun_scan(np, tp);
238 		}
239 		np->sync = SYNC_EOL;
240 	} else {
241 		if (np->pos < ENDRUNLEN - 1)
242 			np->cbuf[np->pos++] = c;
243 	}
244 
245 nogap:
246 	/* pass data to termios */
247 	return linesw[TTYDISC].l_rint(c, tp);
248 }
249 
250 /* Scan the EndRun sentence just received */
251 void
252 endrun_scan(struct endrun *np, struct tty *tp)
253 {
254 	int fldcnt = 0, n;
255 	char *fld[NUMFLDS], *cs;
256 
257 	DPRINTFN(1, ("%s\n", np->cbuf));
258 	/* split into fields */
259 	fld[fldcnt++] = &np->cbuf[0];
260 	for (cs = NULL, n = 0; n < np->pos && cs == NULL; n++) {
261 		switch (np->cbuf[n]) {
262 		case '\r':
263 			np->cbuf[n] = '\0';
264 			cs = &np->cbuf[n + 1];
265 			break;
266 		case ' ':
267 			if (fldcnt < NUMFLDS) {
268 				np->cbuf[n] = '\0';
269 				fld[fldcnt++] = &np->cbuf[n + 1];
270 			} else {
271 				DPRINTF(("endrun: nr of fields in sentence "
272 				    "exceeds expected: %d\n", NUMFLDS));
273 				return;
274 			}
275 			break;
276 		}
277 	}
278 	endrun_decode(np, tp, fld, fldcnt);
279 }
280 
281 /* Decode the time string */
282 void
283 endrun_decode(struct endrun *np, struct tty *tp, char *fld[], int fldcnt)
284 {
285 	int64_t date_nano, time_nano, offset_nano, endrun_now;
286 	char tfom;
287 	int jumped = 0;
288 
289 	if (fldcnt != NUMFLDS) {
290 		DPRINTF(("endrun: field count mismatch, %d\n", fldcnt));
291 		return;
292 	}
293 	if (endrun_time_to_nano(fld[3], &time_nano) == -1) {
294 		DPRINTF(("endrun: illegal time, %s\n", fld[3]));
295 		return;
296 	}
297 	if (endrun_date_to_nano(fld[1], fld[2], &date_nano) == -1) {
298 		DPRINTF(("endrun: illegal date, %s %s\n", fld[1], fld[2]));
299 		return;
300 	}
301 	offset_nano = 0;
302 	/* only parse offset when timemode is local */
303 	if (fld[5][0] == 'L' &&
304 	    endrun_offset_to_nano(fld[4], &offset_nano) == -1) {
305 		DPRINTF(("endrun: illegal offset, %s\n", fld[4]));
306 		return;
307 	}
308 
309 	endrun_now = date_nano + time_nano + offset_nano;
310 	if (endrun_now <= np->last) {
311 		DPRINTF(("endrun: time not monotonically increasing "
312 		    "last %lld now %lld\n",
313 		    (long long)np->last, (long long)endrun_now));
314 		jumped = 1;
315 	}
316 	np->last = endrun_now;
317 	np->gap = 0LL;
318 #ifdef ENDRUN_DEBUG
319 	if (np->time.status == SENSOR_S_UNKNOWN) {
320 		np->time.status = SENSOR_S_OK;
321 		timeout_add_sec(&np->endrun_tout, TRUSTTIME);
322 	}
323 #endif
324 
325 	np->time.value = np->ts.tv_sec * 1000000000LL +
326 	    np->ts.tv_nsec - endrun_now;
327 	np->time.tv.tv_sec = np->ts.tv_sec;
328 	np->time.tv.tv_usec = np->ts.tv_nsec / 1000L;
329 	if (np->time.status == SENSOR_S_UNKNOWN) {
330 		np->time.status = SENSOR_S_OK;
331 		np->time.flags &= ~SENSOR_FINVALID;
332 		strlcpy(np->time.desc, "EndRun", sizeof(np->time.desc));
333 	}
334 	/*
335 	 * Only update the timeout if the clock reports the time as valid.
336 	 *
337 	 * Time Figure Of Merit (TFOM) values:
338 	 *
339 	 * 6  - time error is < 100 us
340 	 * 7  - time error is < 1 ms
341 	 * 8  - time error is < 10 ms
342 	 * 9  - time error is > 10 ms,
343 	 *      unsynchronized state if never locked to CDMA
344 	 */
345 
346 	switch (tfom = fld[0][0]) {
347 	case '6':
348 	case '7':
349 	case '8':
350 		np->time.status = SENSOR_S_OK;
351 		np->signal.status = SENSOR_S_OK;
352 		break;
353 	case '9':
354 		np->signal.status = SENSOR_S_WARN;
355 		break;
356 	default:
357 		DPRINTF(("endrun: invalid TFOM: '%c'\n", tfom));
358 		np->signal.status = SENSOR_S_CRIT;
359 		break;
360 	}
361 
362 #ifdef ENDRUN_DEBUG
363 	if (np->tfom != tfom) {
364 		DPRINTF(("endrun: TFOM changed from %c to %c\n",
365 		    np->tfom, tfom));
366 		np->tfom = tfom;
367 	}
368 #endif
369 	if (jumped)
370 		np->time.status = SENSOR_S_WARN;
371 	if (np->time.status == SENSOR_S_OK)
372 		timeout_add_sec(&np->endrun_tout, TRUSTTIME);
373 
374 	/*
375 	 * If tty timestamping is requested, but no PPS signal is present, set
376 	 * the sensor state to CRITICAL.
377 	 */
378 	if (np->no_pps)
379 		np->time.status = SENSOR_S_CRIT;
380 }
381 
382 int
383 endrun_atoi(char *s, int len)
384 {
385 	int n;
386 	char *p;
387 
388 	/* make sure the input contains only numbers */
389 	for (n = 0, p = s; n < len && *p && *p >= '0' && *p <= '9'; n++, p++)
390 		;
391 	if (n != len || *p != '\0')
392 		return -1;
393 
394 	for (n = 0; *s; s++)
395 		n = n * 10 + *s - '0';
396 
397 	return n;
398 }
399 
400 /*
401  * Convert date fields from EndRun to nanoseconds since the epoch.
402  * The year string must be of the form YYYY .
403  * The day of year string must be of the form DDD .
404  * Return 0 on success, -1 if illegal characters are encountered.
405  */
406 int
407 endrun_date_to_nano(char *y, char *doy, int64_t *nano)
408 {
409 	struct clock_ymdhms clock;
410 	time_t secs;
411 	int n, i;
412 	int year_days = 365;
413 	int month_days[] = {
414 		0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
415 	};
416 
417 #define FEBRUARY		2
418 
419 #define LEAPYEAR(x)		\
420 	((x) % 4 == 0 &&	\
421 	(x) % 100 != 0) ||	\
422 	(x) % 400 == 0
423 
424 	if ((n = endrun_atoi(y, 4)) == -1)
425 		return -1;
426 	clock.dt_year = n;
427 
428 	if (LEAPYEAR(n)) {
429 		month_days[FEBRUARY]++;
430 		year_days++;
431 	}
432 
433 	if ((n = endrun_atoi(doy, 3)) == -1 || n == 0 || n > year_days)
434 		return -1;
435 
436 	/* convert day of year to month, day */
437 	for (i = 1; n > month_days[i]; i++) {
438 		n -= month_days[i];
439 	}
440 	clock.dt_mon = i;
441 	clock.dt_day = n;
442 
443 	DPRINTFN(1, ("mm/dd %d/%d\n", i, n));
444 
445 	clock.dt_hour = clock.dt_min = clock.dt_sec = 0;
446 
447 	secs = clock_ymdhms_to_secs(&clock);
448 	*nano = secs * 1000000000LL;
449 	return 0;
450 }
451 
452 /*
453  * Convert time field from EndRun to nanoseconds since midnight.
454  * The string must be of the form HH:MM:SS .
455  * Return 0 on success, -1 if illegal characters are encountered.
456  */
457 int
458 endrun_time_to_nano(char *s, int64_t *nano)
459 {
460 	struct clock_ymdhms clock;
461 	time_t secs;
462 	int n;
463 
464 	if (s[2] != ':' || s[5] != ':')
465 		return -1;
466 
467 	s[2] = '\0';
468 	s[5] = '\0';
469 
470 	if ((n = endrun_atoi(&s[0], 2)) == -1 || n > 23)
471 		return -1;
472 	clock.dt_hour = n;
473 	if ((n = endrun_atoi(&s[3], 2)) == -1 || n > 59)
474 		return -1;
475 	clock.dt_min = n;
476 	if ((n = endrun_atoi(&s[6], 2)) == -1 || n > 60)
477 		return -1;
478 	clock.dt_sec = n;
479 
480 	DPRINTFN(1, ("hh:mm:ss %d:%d:%d\n", (int)clock.dt_hour,
481 	    (int)clock.dt_min,
482 	    (int)clock.dt_sec));
483 	secs = clock.dt_hour * 3600
484 	    + clock.dt_min * 60
485 	    + clock.dt_sec;
486 
487 	DPRINTFN(1, ("secs %lu\n", (unsigned long)secs));
488 
489 	*nano = secs * 1000000000LL;
490 	return 0;
491 }
492 
493 int
494 endrun_offset_to_nano(char *s, int64_t *nano)
495 {
496 	time_t secs;
497 	int n;
498 
499 	if (!(s[0] == '+' || s[0] == '-'))
500 		return -1;
501 
502 	if ((n = endrun_atoi(&s[1], 2)) == -1)
503 		return -1;
504 	secs = n * 30 * 60;
505 
506 	*nano = secs * 1000000000LL;
507 	if (s[0] == '+')
508 		*nano = -*nano;
509 
510 	DPRINTFN(1, ("offset secs %lu nanosecs %lld\n",
511 	    (unsigned long)secs, (long long)*nano));
512 
513 	return 0;
514 }
515 
516 /*
517  * Degrade the sensor state if we received no EndRun string for more than
518  * TRUSTTIME seconds.
519  */
520 void
521 endrun_timeout(void *xnp)
522 {
523 	struct endrun *np = xnp;
524 
525 	if (np->time.status == SENSOR_S_OK) {
526 		np->time.status = SENSOR_S_WARN;
527 		/*
528 		 * further degrade in TRUSTTIME seconds if no new valid EndRun
529 		 * strings are received.
530 		 */
531 		timeout_add_sec(&np->endrun_tout, TRUSTTIME);
532 	} else
533 		np->time.status = SENSOR_S_CRIT;
534 }
535