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