xref: /openbsd-src/usr.bin/at/parsetime.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: parsetime.c,v 1.20 2014/01/13 23:18:57 millert Exp $	*/
2 
3 /*
4  * parsetime.c - parse time for at(1)
5  * Copyright (C) 1993, 1994  Thomas Koenig
6  *
7  * modifications for english-language times
8  * Copyright (C) 1993  David Parsons
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. The name of the author(s) may not be used to endorse or promote
16  *    products derived from this software without specific prior written
17  *    permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  *  at [NOW] PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS|MONTHS|YEARS
31  *     /NUMBER [DOT NUMBER] [AM|PM]\ /[MONTH NUMBER [NUMBER]]             \
32  *     |NOON                       | |[TOMORROW]                          |
33  *     |MIDNIGHT                   | |[DAY OF WEEK]                       |
34  *     \TEATIME                    / |NUMBER [SLASH NUMBER [SLASH NUMBER]]|
35  *                                   \PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS|MONTHS|YEARS/
36  */
37 
38 #include <sys/types.h>
39 #include <errno.h>
40 #include <ctype.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <time.h>
45 #include <tzfile.h>
46 #include <unistd.h>
47 
48 #include "globals.h"
49 #include "at.h"
50 
51 /* Structures and unions */
52 
53 enum {	/* symbols */
54 	MIDNIGHT, NOON, TEATIME,
55 	PM, AM, TOMORROW, TODAY, NOW,
56 	MINUTES, HOURS, DAYS, WEEKS, MONTHS, YEARS,
57 	NUMBER, NEXT, PLUS, DOT, SLASH, ID, JUNK,
58 	JAN, FEB, MAR, APR, MAY, JUN,
59 	JUL, AUG, SEP, OCT, NOV, DEC,
60 	SUN, MON, TUE, WED, THU, FRI, SAT
61 };
62 
63 /*
64  * parse translation table - table driven parsers can be your FRIEND!
65  */
66 struct {
67 	char *name;	/* token name */
68 	int value;	/* token id */
69 	int plural;	/* is this plural? */
70 } Specials[] = {
71 	{ "midnight", MIDNIGHT, 0 },	/* 00:00:00 of today or tomorrow */
72 	{ "noon", NOON, 0 },		/* 12:00:00 of today or tomorrow */
73 	{ "teatime", TEATIME, 0 },	/* 16:00:00 of today or tomorrow */
74 	{ "am", AM, 0 },		/* morning times for 0-12 clock */
75 	{ "pm", PM, 0 },		/* evening times for 0-12 clock */
76 	{ "tomorrow", TOMORROW, 0 },	/* execute 24 hours from time */
77 	{ "today", TODAY, 0 },		/* execute today - don't advance time */
78 	{ "now", NOW, 0 },		/* opt prefix for PLUS */
79 	{ "next", NEXT, 0 },		/* opt prefix for + 1 */
80 
81 	{ "minute", MINUTES, 0 },	/* minutes multiplier */
82 	{ "min", MINUTES, 0 },
83 	{ "m", MINUTES, 0 },
84 	{ "minutes", MINUTES, 1 },	/* (pluralized) */
85 	{ "hour", HOURS, 0 },		/* hours ... */
86 	{ "hr", HOURS, 0 },		/* abbreviated */
87 	{ "h", HOURS, 0 },
88 	{ "hours", HOURS, 1 },		/* (pluralized) */
89 	{ "day", DAYS, 0 },		/* days ... */
90 	{ "d", DAYS, 0 },
91 	{ "days", DAYS, 1 },		/* (pluralized) */
92 	{ "week", WEEKS, 0 },		/* week ... */
93 	{ "w", WEEKS, 0 },
94 	{ "weeks", WEEKS, 1 },		/* (pluralized) */
95 	{ "month", MONTHS, 0 },		/* month ... */
96 	{ "mo", MONTHS, 0 },
97 	{ "mth", MONTHS, 0 },
98 	{ "months", MONTHS, 1 },	/* (pluralized) */
99 	{ "year", YEARS, 0 },		/* year ... */
100 	{ "y", YEARS, 0 },
101 	{ "years", YEARS, 1 },		/* (pluralized) */
102 	{ "jan", JAN, 0 },
103 	{ "feb", FEB, 0 },
104 	{ "mar", MAR, 0 },
105 	{ "apr", APR, 0 },
106 	{ "may", MAY, 0 },
107 	{ "jun", JUN, 0 },
108 	{ "jul", JUL, 0 },
109 	{ "aug", AUG, 0 },
110 	{ "sep", SEP, 0 },
111 	{ "oct", OCT, 0 },
112 	{ "nov", NOV, 0 },
113 	{ "dec", DEC, 0 },
114 	{ "january", JAN,0 },
115 	{ "february", FEB,0 },
116 	{ "march", MAR,0 },
117 	{ "april", APR,0 },
118 	{ "may", MAY,0 },
119 	{ "june", JUN,0 },
120 	{ "july", JUL,0 },
121 	{ "august", AUG,0 },
122 	{ "september", SEP,0 },
123 	{ "october", OCT,0 },
124 	{ "november", NOV,0 },
125 	{ "december", DEC,0 },
126 	{ "sunday", SUN, 0 },
127 	{ "sun", SUN, 0 },
128 	{ "monday", MON, 0 },
129 	{ "mon", MON, 0 },
130 	{ "tuesday", TUE, 0 },
131 	{ "tue", TUE, 0 },
132 	{ "wednesday", WED, 0 },
133 	{ "wed", WED, 0 },
134 	{ "thursday", THU, 0 },
135 	{ "thu", THU, 0 },
136 	{ "friday", FRI, 0 },
137 	{ "fri", FRI, 0 },
138 	{ "saturday", SAT, 0 },
139 	{ "sat", SAT, 0 },
140 };
141 
142 static char **scp;	/* scanner - pointer at arglist */
143 static int scc;		/* scanner - count of remaining arguments */
144 static char *sct;	/* scanner - next char pointer in current argument */
145 static int need;	/* scanner - need to advance to next argument */
146 static char *sc_token;	/* scanner - token buffer */
147 static size_t sc_len;   /* scanner - length of token buffer */
148 static int sc_tokid;	/* scanner - token id */
149 static int sc_tokplur;	/* scanner - is token plural? */
150 
151 /*
152  * parse a token, checking if it's something special to us
153  */
154 static int
155 parse_token(char *arg)
156 {
157 	int i;
158 
159 	for (i=0; i < sizeof(Specials) / sizeof(Specials[0]); i++) {
160 		if (strcasecmp(Specials[i].name, arg) == 0) {
161 			sc_tokplur = Specials[i].plural;
162 		    	return (sc_tokid = Specials[i].value);
163 		}
164 	}
165 
166 	/* not special - must be some random id */
167 	return (ID);
168 }
169 
170 
171 /*
172  * init_scanner() sets up the scanner to eat arguments
173  */
174 static int
175 init_scanner(int argc, char **argv)
176 {
177 	scp = argv;
178 	scc = argc;
179 	need = 1;
180 	sc_len = 1;
181 	while (argc-- > 0)
182 		sc_len += strlen(*argv++);
183 
184 	if ((sc_token = (char *) malloc(sc_len)) == NULL) {
185 		fprintf(stderr, "%s: Insufficient virtual memory\n",
186 		    ProgramName);
187 		return (-1);
188 	}
189 	return (0);
190 }
191 
192 /*
193  * token() fetches a token from the input stream
194  */
195 static int
196 token(void)
197 {
198 	int idx;
199 
200 	for (;;) {
201 		bzero(sc_token, sc_len);
202 		sc_tokid = EOF;
203 		sc_tokplur = 0;
204 		idx = 0;
205 
206 		/*
207 		 * if we need to read another argument, walk along the
208 		 * argument list; when we fall off the arglist, we'll
209 		 * just return EOF forever
210 		 */
211 		if (need) {
212 			if (scc < 1)
213 				return (sc_tokid);
214 			sct = *scp;
215 			scp++;
216 			scc--;
217 			need = 0;
218 		}
219 		/*
220 		 * eat whitespace now - if we walk off the end of the argument,
221 		 * we'll continue, which puts us up at the top of the while loop
222 		 * to fetch the next argument in
223 		 */
224 		while (isspace((unsigned char)*sct))
225 			++sct;
226 		if (!*sct) {
227 			need = 1;
228 			continue;
229 		}
230 
231 		/*
232 		 * preserve the first character of the new token
233 		 */
234 		sc_token[0] = *sct++;
235 
236 		/*
237 		 * then see what it is
238 		 */
239 		if (isdigit((unsigned char)sc_token[0])) {
240 			while (isdigit((unsigned char)*sct))
241 				sc_token[++idx] = *sct++;
242 			sc_token[++idx] = 0;
243 			return ((sc_tokid = NUMBER));
244 		} else if (isalpha((unsigned char)sc_token[0])) {
245 			while (isalpha((unsigned char)*sct))
246 				sc_token[++idx] = *sct++;
247 			sc_token[++idx] = 0;
248 			return (parse_token(sc_token));
249 		}
250 		else if (sc_token[0] == ':' || sc_token[0] == '.')
251 			return ((sc_tokid = DOT));
252 		else if (sc_token[0] == '+')
253 			return ((sc_tokid = PLUS));
254 		else if (sc_token[0] == '/')
255 			return ((sc_tokid = SLASH));
256 		else
257 			return ((sc_tokid = JUNK));
258 	}
259 }
260 
261 
262 /*
263  * plonk() gives an appropriate error message if a token is incorrect
264  */
265 static void
266 plonk(int tok)
267 {
268 	fprintf(stderr, "%s: %s time\n", ProgramName,
269 	    (tok == EOF) ? "incomplete" : "garbled");
270 }
271 
272 
273 /*
274  * expect() gets a token and returns -1 if it's not the token we want
275  */
276 static int
277 expect(int desired)
278 {
279 	if (token() != desired) {
280 		plonk(sc_tokid);
281 		return (-1);
282 	}
283 	return (0);
284 }
285 
286 
287 /*
288  * dateadd() adds a number of minutes to a date.  It is extraordinarily
289  * stupid regarding day-of-month overflow, and will most likely not
290  * work properly
291  */
292 static void
293 dateadd(int minutes, struct tm *tm)
294 {
295 	/* increment days */
296 
297 	while (minutes > 24*60) {
298 		minutes -= 24*60;
299 		tm->tm_mday++;
300 	}
301 
302 	/* increment hours */
303 	while (minutes > 60) {
304 		minutes -= 60;
305 		tm->tm_hour++;
306 		if (tm->tm_hour > 23) {
307 			tm->tm_mday++;
308 			tm->tm_hour = 0;
309 		}
310 	}
311 
312 	/* increment minutes */
313 	tm->tm_min += minutes;
314 
315 	if (tm->tm_min > 59) {
316 		tm->tm_hour++;
317 		tm->tm_min -= 60;
318 
319 		if (tm->tm_hour > 23) {
320 			tm->tm_mday++;
321 			tm->tm_hour = 0;
322 		}
323 	}
324 }
325 
326 
327 /*
328  * plus() parses a now + time
329  *
330  *  at [NOW] PLUS NUMBER [MINUTES|HOURS|DAYS|WEEKS|MONTHS|YEARS]
331  *
332  */
333 static int
334 plus(struct tm *tm)
335 {
336 	int increment;
337 	int expectplur;
338 
339 	if (sc_tokid == NEXT) {
340 		increment = 1;
341 		expectplur = 0;
342 	} else {
343 		if (expect(NUMBER) != 0)
344 			return (-1);
345 		increment = atoi(sc_token);
346 		expectplur = (increment != 1) ? 1 : 0;
347 	}
348 
349 	switch (token()) {
350 	case YEARS:
351 		tm->tm_year += increment;
352 		return (0);
353 	case MONTHS:
354 		tm->tm_mon += increment;
355 		while (tm->tm_mon >= 12) {
356 		    tm->tm_year++;
357 		    tm->tm_mon -= 12;
358 		}
359 		return (0);
360 	case WEEKS:
361 		increment *= 7;
362 		/* FALLTHROUGH */
363 	case DAYS:
364 		increment *= 24;
365 		/* FALLTHROUGH */
366 	case HOURS:
367 		increment *= 60;
368 		/* FALLTHROUGH */
369 	case MINUTES:
370 		if (expectplur != sc_tokplur)
371 			fprintf(stderr, "%s: pluralization is wrong\n",
372 			    ProgramName);
373 		dateadd(increment, tm);
374 		return (0);
375 	}
376 
377 	plonk(sc_tokid);
378 	return (-1);
379 }
380 
381 
382 /*
383  * tod() computes the time of day
384  *     [NUMBER [DOT NUMBER] [AM|PM]]
385  */
386 static int
387 tod(struct tm *tm)
388 {
389 	int hour, minute = 0;
390 	size_t tlen;
391 
392 	hour = atoi(sc_token);
393 	tlen = strlen(sc_token);
394 
395 	/*
396 	 * first pick out the time of day - if it's 4 digits, we assume
397 	 * a HHMM time, otherwise it's HH DOT MM time
398 	 */
399 	if (token() == DOT) {
400 		if (expect(NUMBER) != 0)
401 			return (-1);
402 		minute = atoi(sc_token);
403 		if (minute > 59)
404 			goto bad;
405 		token();
406 	} else if (tlen == 4) {
407 		minute = hour % 100;
408 		if (minute > 59)
409 			goto bad;
410 		hour = hour / 100;
411 	}
412 
413 	/*
414 	 * check if an AM or PM specifier was given
415 	 */
416 	if (sc_tokid == AM || sc_tokid == PM) {
417 		if (hour > 12)
418 			goto bad;
419 
420 		if (sc_tokid == PM) {
421 			if (hour != 12)	/* 12:xx PM is 12:xx, not 24:xx */
422 				hour += 12;
423 		} else {
424 			if (hour == 12)	/* 12:xx AM is 00:xx, not 12:xx */
425 				hour = 0;
426 		}
427 		token();
428 	} else if (hour > 23)
429 		goto bad;
430 
431 	/*
432 	 * if we specify an absolute time, we don't want to bump the day even
433 	 * if we've gone past that time - but if we're specifying a time plus
434 	 * a relative offset, it's okay to bump things
435 	 */
436 	if ((sc_tokid == EOF || sc_tokid == PLUS || sc_tokid == NEXT) &&
437 	    tm->tm_hour > hour) {
438 		tm->tm_mday++;
439 		tm->tm_wday++;
440 	}
441 
442 	tm->tm_hour = hour;
443 	tm->tm_min = minute;
444 	if (tm->tm_hour == 24) {
445 		tm->tm_hour = 0;
446 		tm->tm_mday++;
447 	}
448 	return (0);
449 bad:
450 	fprintf(stderr, "%s: garbled time\n", ProgramName);
451 	return (-1);
452 }
453 
454 
455 /*
456  * assign_date() assigns a date, wrapping to next year if needed
457  */
458 static void
459 assign_date(struct tm *tm, int mday, int mon, int year)
460 {
461 
462 	/*
463 	 * Convert year into tm_year format (year - 1900).
464 	 * We may be given the year in 2 digit, 4 digit, or tm_year format.
465 	 */
466 	if (year != -1) {
467 		if (year >= TM_YEAR_BASE)
468 			year -= TM_YEAR_BASE;	/* convert from 4 digit year */
469 		else if (year < 100) {
470 			/* Convert to tm_year assuming current century */
471 			year += (tm->tm_year / 100) * 100;
472 
473 			if (year == tm->tm_year - 1)
474 				year++;		/* Common off by one error */
475 			else if (year < tm->tm_year)
476 				year += 100;	/* must be in next century */
477 		}
478 	}
479 
480 	if (year < 0 &&
481 	    (tm->tm_mon > mon ||(tm->tm_mon == mon && tm->tm_mday > mday)))
482 		year = tm->tm_year + 1;
483 
484 	tm->tm_mday = mday;
485 	tm->tm_mon = mon;
486 
487 	if (year >= 0)
488 		tm->tm_year = year;
489 }
490 
491 
492 /*
493  * month() picks apart a month specification
494  *
495  *  /[<month> NUMBER [NUMBER]]           \
496  *  |[TOMORROW]                          |
497  *  |[DAY OF WEEK]                       |
498  *  |NUMBER [SLASH NUMBER [SLASH NUMBER]]|
499  *  \PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS|MONTHS|YEARS/
500  */
501 static int
502 month(struct tm *tm)
503 {
504 	int year = (-1);
505 	int mday, wday, mon;
506 	size_t tlen;
507 
508 	switch (sc_tokid) {
509 	case NEXT:
510 	case PLUS:
511 		if (plus(tm) != 0)
512 			return (-1);
513 		break;
514 
515 	case TOMORROW:
516 		/* do something tomorrow */
517 		tm->tm_mday++;
518 		tm->tm_wday++;
519 	case TODAY:
520 		/* force ourselves to stay in today - no further processing */
521 		token();
522 		break;
523 
524 	case JAN: case FEB: case MAR: case APR: case MAY: case JUN:
525 	case JUL: case AUG: case SEP: case OCT: case NOV: case DEC:
526 		/*
527 		 * do month mday [year]
528 		 */
529 		mon = sc_tokid - JAN;
530 		if (expect(NUMBER) != 0)
531 			return (-1);
532 		mday = atoi(sc_token);
533 		if (token() == NUMBER) {
534 			year = atoi(sc_token);
535 			token();
536 		}
537 		assign_date(tm, mday, mon, year);
538 		break;
539 
540 	case SUN: case MON: case TUE:
541 	case WED: case THU: case FRI:
542 	case SAT:
543 		/* do a particular day of the week */
544 		wday = sc_tokid - SUN;
545 
546 		mday = tm->tm_mday;
547 
548 		/* if this day is < today, then roll to next week */
549 		if (wday < tm->tm_wday)
550 			mday += 7 - (tm->tm_wday - wday);
551 		else
552 			mday += (wday - tm->tm_wday);
553 
554 		tm->tm_wday = wday;
555 
556 		assign_date(tm, mday, tm->tm_mon, tm->tm_year);
557 		break;
558 
559 	case NUMBER:
560 		/*
561 		 * get numeric MMDDYY, mm/dd/yy, or dd.mm.yy
562 		 */
563 		tlen = strlen(sc_token);
564 		mon = atoi(sc_token);
565 		token();
566 
567 		if (sc_tokid == SLASH || sc_tokid == DOT) {
568 			int sep;
569 
570 			sep = sc_tokid;
571 			if (expect(NUMBER) != 0)
572 				return (-1);
573 			mday = atoi(sc_token);
574 			if (token() == sep) {
575 				if (expect(NUMBER) != 0)
576 					return (-1);
577 				year = atoi(sc_token);
578 				token();
579 			}
580 
581 			/*
582 			 * flip months and days for european timing
583 			 */
584 			if (sep == DOT) {
585 				int x = mday;
586 				mday = mon;
587 				mon = x;
588 			}
589 		} else if (tlen == 6 || tlen == 8) {
590 			if (tlen == 8) {
591 				year = (mon % 10000) - TM_YEAR_BASE;
592 				mon /= 10000;
593 			} else {
594 				year = mon % 100;
595 				mon /= 100;
596 			}
597 			mday = mon % 100;
598 			mon /= 100;
599 		} else
600 			goto bad;
601 
602 		mon--;
603 		if (mon < 0 || mon > 11 || mday < 1 || mday > 31)
604 			goto bad;
605 
606 		assign_date(tm, mday, mon, year);
607 		break;
608 	}
609 	return (0);
610 bad:
611 	fprintf(stderr, "%s: garbled time\n", ProgramName);
612 	return (-1);
613 }
614 
615 
616 time_t
617 parsetime(int argc, char **argv)
618 {
619 	/*
620 	 * Do the argument parsing, die if necessary, and return the
621 	 * time the job should be run.
622 	 */
623 	time_t nowtimer, runtimer;
624 	struct tm nowtime, runtime;
625 	int hr = 0;
626 	/* this MUST be initialized to zero for midnight/noon/teatime */
627 
628 	if (argc == 0)
629 		return (-1);
630 
631 	nowtimer = time(NULL);
632 	nowtime = *localtime(&nowtimer);
633 
634 	runtime = nowtime;
635 	runtime.tm_sec = 0;
636 	runtime.tm_isdst = 0;
637 
638 	if (init_scanner(argc, argv) == -1)
639 		return (-1);
640 
641 	switch (token()) {
642 	case NOW:	/* now is optional prefix for PLUS tree */
643 		token();
644 		if (sc_tokid == EOF) {
645 			runtime = nowtime;
646 			break;
647 		}
648 		else if (sc_tokid != PLUS && sc_tokid != NEXT)
649 			plonk(sc_tokid);
650 	case NEXT:
651 	case PLUS:
652 		if (plus(&runtime) != 0)
653 			return (-1);
654 		break;
655 
656 	case NUMBER:
657 		if (tod(&runtime) != 0 || month(&runtime) != 0)
658 			return (-1);
659 		break;
660 
661 		/*
662 		 * evil coding for TEATIME|NOON|MIDNIGHT - we've initialised
663 		 * hr to zero up above, then fall into this case in such a
664 		 * way so we add +12 +4 hours to it for teatime, +12 hours
665 		 * to it for noon, and nothing at all for midnight, then
666 		 * set our runtime to that hour before leaping into the
667 		 * month scanner
668 		 */
669 	case TEATIME:
670 		hr += 4;
671 		/* FALLTHROUGH */
672 	case NOON:
673 		hr += 12;
674 		/* FALLTHROUGH */
675 	case MIDNIGHT:
676 		if (runtime.tm_hour >= hr) {
677 			runtime.tm_mday++;
678 			runtime.tm_wday++;
679 		}
680 		runtime.tm_hour = hr;
681 		runtime.tm_min = 0;
682 		token();
683 		/* fall through to month setting */
684 		/* FALLTHROUGH */
685 	default:
686 		if (month(&runtime) != 0)
687 			return (-1);
688 		break;
689 	} /* ugly case statement */
690 	if (expect(EOF) != 0)
691 		return (-1);
692 
693 	/*
694 	 * adjust for daylight savings time
695 	 */
696 	runtime.tm_isdst = -1;
697 	runtimer = mktime(&runtime);
698 	if (runtime.tm_isdst > 0) {
699 		runtimer -= 3600;
700 		runtimer = mktime(&runtime);
701 	}
702 
703 	if (runtimer < 0) {
704 		fprintf(stderr, "%s: garbled time\n", ProgramName);
705 		return (-1);
706 	}
707 
708 	if (nowtimer > runtimer) {
709 		fprintf(stderr, "%s: cannot schedule jobs in the past\n",
710 		    ProgramName);
711 		return (-1);
712 	}
713 
714 	return (runtimer);
715 }
716