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