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