xref: /freebsd/usr.bin/at/parsetime.c (revision 39beb93c)
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, 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 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 = SLASH;
251 	else
252 	    return sc_tokid = JUNK;
253     } /* while (1) */
254 } /* token */
255 
256 
257 /*
258  * plonk() gives an appropriate error message if a token is incorrect
259  */
260 static void
261 plonk(int tok)
262 {
263     panic((tok == EOF) ? "incomplete time"
264 		       : "garbled time");
265 } /* plonk */
266 
267 
268 /*
269  * expect() gets a token and dies most horribly if it's not the token we want
270  */
271 static void
272 expect(int desired)
273 {
274     if (token() != desired)
275 	plonk(sc_tokid);	/* and we die here... */
276 } /* expect */
277 
278 
279 /*
280  * plus() parses a now + time
281  *
282  *  at [NOW] PLUS NUMBER [MINUTES|HOURS|DAYS|WEEKS|MONTHS|YEARS]
283  *
284  */
285 
286 static void
287 plus(struct tm *tm)
288 {
289     int delay;
290     int expectplur;
291 
292     expect(NUMBER);
293 
294     delay = atoi(sc_token);
295     expectplur = (delay != 1) ? 1 : 0;
296 
297     switch (token()) {
298     case YEARS:
299 	    tm->tm_year += delay;
300 	    break;
301     case MONTHS:
302 	    tm->tm_mon += delay;
303 	    break;
304     case WEEKS:
305 	    delay *= 7;
306     case DAYS:
307 	    tm->tm_mday += delay;
308 	    break;
309     case HOURS:
310 	    tm->tm_hour += delay;
311 	    break;
312     case MINUTES:
313 	    tm->tm_min += delay;
314 	    break;
315     default:
316     	    plonk(sc_tokid);
317 	    break;
318     }
319 
320     if (expectplur != sc_tokplur)
321 	warnx("pluralization is wrong");
322 
323     tm->tm_isdst = -1;
324     if (mktime(tm) < 0)
325 	plonk(sc_tokid);
326 
327 } /* plus */
328 
329 
330 /*
331  * tod() computes the time of day
332  *     [NUMBER [DOT NUMBER] [AM|PM]]
333  */
334 static void
335 tod(struct tm *tm)
336 {
337     int hour, minute = 0;
338     int tlen;
339 
340     hour = atoi(sc_token);
341     tlen = strlen(sc_token);
342 
343     /* first pick out the time of day - if it's 4 digits, we assume
344      * a HHMM time, otherwise it's HH DOT MM time
345      */
346     if (token() == DOT) {
347 	expect(NUMBER);
348 	minute = atoi(sc_token);
349 	if (minute > 59)
350 	    panic("garbled time");
351 	token();
352     }
353     else if (tlen == 4) {
354 	minute = hour%100;
355 	if (minute > 59)
356 	    panic("garbled time");
357 	hour = hour/100;
358     }
359 
360     /* check if an AM or PM specifier was given
361      */
362     if (sc_tokid == AM || sc_tokid == PM) {
363 	if (hour > 12)
364 	    panic("garbled time");
365 
366 	if (sc_tokid == PM) {
367 	    if (hour != 12)	/* 12:xx PM is 12:xx, not 24:xx */
368 			hour += 12;
369 	} else {
370 	    if (hour == 12)	/* 12:xx AM is 00:xx, not 12:xx */
371 			hour = 0;
372 	}
373 	token();
374     }
375     else if (hour > 23)
376 	panic("garbled time");
377 
378     /* if we specify an absolute time, we don't want to bump the day even
379      * if we've gone past that time - but if we're specifying a time plus
380      * a relative offset, it's okay to bump things
381      */
382     if ((sc_tokid == EOF || sc_tokid == PLUS) && tm->tm_hour > hour) {
383 	tm->tm_mday++;
384 	tm->tm_wday++;
385     }
386 
387     tm->tm_hour = hour;
388     tm->tm_min = minute;
389     if (tm->tm_hour == 24) {
390 	tm->tm_hour = 0;
391 	tm->tm_mday++;
392     }
393 } /* tod */
394 
395 
396 /*
397  * assign_date() assigns a date, wrapping to next year if needed
398  */
399 static void
400 assign_date(struct tm *tm, long mday, long mon, long year)
401 {
402 
403    /*
404     * Convert year into tm_year format (year - 1900).
405     * We may be given the year in 2 digit, 4 digit, or tm_year format.
406     */
407     if (year != -1) {
408 	if (year >= 1900)
409 		year -= 1900;   /* convert from 4 digit year */
410 	else if (year < 100) {
411 		/* convert from 2 digit year */
412 		struct tm *lt;
413 		time_t now;
414 
415 		time(&now);
416 		lt = localtime(&now);
417 
418 		/* Convert to tm_year assuming current century */
419 		year += (lt->tm_year / 100) * 100;
420 
421 		if (year == lt->tm_year - 1) year++;
422 		else if (year < lt->tm_year)
423 			year += 100;    /* must be in next century */
424 	}
425     }
426 
427     if (year < 0 &&
428 	(tm->tm_mon > mon ||(tm->tm_mon == mon && tm->tm_mday > mday)))
429 	year = tm->tm_year + 1;
430 
431     tm->tm_mday = mday;
432     tm->tm_mon = mon;
433 
434     if (year >= 0)
435 	tm->tm_year = year;
436 } /* assign_date */
437 
438 
439 /*
440  * month() picks apart a month specification
441  *
442  *  /[<month> NUMBER [NUMBER]]           \
443  *  |[TOMORROW]                          |
444  *  |[DAY OF WEEK]                       |
445  *  |NUMBER [SLASH NUMBER [SLASH NUMBER]]|
446  *  \PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS/
447  */
448 static void
449 month(struct tm *tm)
450 {
451     long year= (-1);
452     long mday = 0, wday, mon;
453     int tlen;
454 
455     switch (sc_tokid) {
456     case PLUS:
457 	    plus(tm);
458 	    break;
459 
460     case TOMORROW:
461 	    /* do something tomorrow */
462 	    tm->tm_mday ++;
463 	    tm->tm_wday ++;
464     case TODAY:	/* force ourselves to stay in today - no further processing */
465 	    token();
466 	    break;
467 
468     case JAN: case FEB: case MAR: case APR: case MAY: case JUN:
469     case JUL: case AUG: case SEP: case OCT: case NOV: case DEC:
470 	    /* do month mday [year]
471 	     */
472 	    mon = (sc_tokid-JAN);
473 	    expect(NUMBER);
474 	    mday = atol(sc_token);
475 	    if (token() == NUMBER) {
476 		year = atol(sc_token);
477 		token();
478 	    }
479 	    assign_date(tm, mday, mon, year);
480 	    break;
481 
482     case SUN: case MON: case TUE:
483     case WED: case THU: case FRI:
484     case SAT:
485 	    /* do a particular day of the week
486 	     */
487 	    wday = (sc_tokid-SUN);
488 
489 	    mday = tm->tm_mday;
490 
491 	    /* if this day is < today, then roll to next week
492 	     */
493 	    if (wday < tm->tm_wday)
494 		mday += 7 - (tm->tm_wday - wday);
495 	    else
496 		mday += (wday - tm->tm_wday);
497 
498 	    tm->tm_wday = wday;
499 
500 	    assign_date(tm, mday, tm->tm_mon, tm->tm_year);
501 	    break;
502 
503     case NUMBER:
504 	    /* get numeric MMDDYY, mm/dd/yy, or dd.mm.yy
505 	     */
506 	    tlen = strlen(sc_token);
507 	    mon = atol(sc_token);
508 	    token();
509 
510 	    if (sc_tokid == SLASH || sc_tokid == DOT) {
511 		int sep;
512 
513 		sep = sc_tokid;
514 		expect(NUMBER);
515 		mday = atol(sc_token);
516 		if (token() == sep) {
517 		    expect(NUMBER);
518 		    year = atol(sc_token);
519 		    token();
520 		}
521 
522 		/* flip months and days for European timing
523 		 */
524 		if (sep == DOT) {
525 		    int x = mday;
526 		    mday = mon;
527 		    mon = x;
528 		}
529 	    }
530 	    else if (tlen == 6 || tlen == 8) {
531 		if (tlen == 8) {
532 		    year = (mon % 10000) - 1900;
533 		    mon /= 10000;
534 		}
535 		else {
536 		    year = mon % 100;
537 		    mon /= 100;
538 		}
539 		mday = mon % 100;
540 		mon /= 100;
541 	    }
542 	    else
543 		panic("garbled time");
544 
545 	    mon--;
546 	    if (mon < 0 || mon > 11 || mday < 1 || mday > 31)
547 		panic("garbled time");
548 
549 	    assign_date(tm, mday, mon, year);
550 	    break;
551     } /* case */
552 } /* month */
553 
554 
555 /* Global functions */
556 
557 time_t
558 parsetime(int argc, char **argv)
559 {
560 /* Do the argument parsing, die if necessary, and return the time the job
561  * should be run.
562  */
563     time_t nowtimer, runtimer;
564     struct tm nowtime, runtime;
565     int hr = 0;
566     /* this MUST be initialized to zero for midnight/noon/teatime */
567 
568     nowtimer = time(NULL);
569     nowtime = *localtime(&nowtimer);
570 
571     runtime = nowtime;
572     runtime.tm_sec = 0;
573     runtime.tm_isdst = 0;
574 
575     if (argc <= optind)
576 	usage();
577 
578     init_scanner(argc-optind, argv+optind);
579 
580     switch (token()) {
581     case NOW:
582 	    if (scc < 1) {
583 		return nowtimer;
584 	    }
585 	    /* now is optional prefix for PLUS tree */
586 	    expect(PLUS);
587     case PLUS:
588 	    plus(&runtime);
589 	    break;
590 
591     case NUMBER:
592 	    tod(&runtime);
593 	    month(&runtime);
594 	    break;
595 
596 	    /* evil coding for TEATIME|NOON|MIDNIGHT - we've initialised
597 	     * hr to zero up above, then fall into this case in such a
598 	     * way so we add +12 +4 hours to it for teatime, +12 hours
599 	     * to it for noon, and nothing at all for midnight, then
600 	     * set our runtime to that hour before leaping into the
601 	     * month scanner
602 	     */
603     case TEATIME:
604 	    hr += 4;
605     case NOON:
606 	    hr += 12;
607     case MIDNIGHT:
608 	    if (runtime.tm_hour >= hr) {
609 		runtime.tm_mday++;
610 		runtime.tm_wday++;
611 	    }
612 	    runtime.tm_hour = hr;
613 	    runtime.tm_min = 0;
614 	    token();
615 	    /* FALLTHROUGH to month setting */
616     default:
617 	    month(&runtime);
618 	    break;
619     } /* ugly case statement */
620     expect(EOF);
621 
622     /* convert back to time_t
623      */
624     runtime.tm_isdst = -1;
625     runtimer = mktime(&runtime);
626 
627     if (runtimer < 0)
628 	panic("garbled time");
629 
630     if (nowtimer > runtimer)
631 	panic("trying to travel back in time");
632 
633     return runtimer;
634 } /* parsetime */
635