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