parsetime.c revision 54158
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#ifndef lint
37static const char rcsid[] =
38  "$FreeBSD: head/usr.bin/at/parsetime.c 54158 1999-12-05 19:57:14Z charnier $";
39#endif /* not lint */
40
41/* System Headers */
42
43#include <sys/types.h>
44#include <ctype.h>
45#include <err.h>
46#include <errno.h>
47#include <stdio.h>
48#include <stdlib.h>
49#include <string.h>
50#include <time.h>
51#include <unistd.h>
52#ifndef __FreeBSD__
53#include <getopt.h>
54#endif
55
56/* Local headers */
57
58#include "at.h"
59#include "panic.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    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    int 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    sc_token = (char *) mymalloc(sc_len);
189} /* init_scanner */
190
191/*
192 * token() fetches a token from the input stream
193 */
194static int
195token()
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 */
260static void
261plonk(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 */
271static void
272expect(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
286static void
287plus(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 */
334static void
335tod(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 */
399static void
400assign_date(struct tm *tm, long mday, long mon, long year)
401{
402    if (year > 99) {
403	if (year > 1899)
404	    year -= 1900;
405	else
406	    panic("garbled time");
407    } else if (year != -1) {
408	struct tm *lt;
409	time_t now;
410
411	time(&now);
412	lt = localtime(&now);
413
414	/*
415	 * check if the specified year is in the next century.
416	 * allow for one year of user error as many people will
417	 * enter n - 1 at the start of year n.
418	 */
419	if (year < (lt->tm_year % 100) - 1)
420	    year += 100;
421	/* adjust for the year 2000 and beyond */
422	year += lt->tm_year - (lt->tm_year % 100);
423    }
424
425    if (year < 0 &&
426	(tm->tm_mon > mon ||(tm->tm_mon == mon && tm->tm_mday > mday)))
427	year = tm->tm_year + 1;
428
429    tm->tm_mday = mday;
430    tm->tm_mon = mon;
431
432    if (year >= 0)
433	tm->tm_year = year;
434} /* assign_date */
435
436
437/*
438 * month() picks apart a month specification
439 *
440 *  /[<month> NUMBER [NUMBER]]           \
441 *  |[TOMORROW]                          |
442 *  |[DAY OF WEEK]                       |
443 *  |NUMBER [SLASH NUMBER [SLASH NUMBER]]|
444 *  \PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS/
445 */
446static void
447month(struct tm *tm)
448{
449    long year= (-1);
450    long mday = 0, wday, mon;
451    int tlen;
452
453    switch (sc_tokid) {
454    case PLUS:
455	    plus(tm);
456	    break;
457
458    case TOMORROW:
459	    /* do something tomorrow */
460	    tm->tm_mday ++;
461	    tm->tm_wday ++;
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
555time_t
556parsetime(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:	/* now is optional prefix for PLUS tree */
580	    expect(PLUS);
581    case PLUS:
582	    plus(&runtime);
583	    break;
584
585    case NUMBER:
586	    tod(&runtime);
587	    month(&runtime);
588	    break;
589
590	    /* evil coding for TEATIME|NOON|MIDNIGHT - we've initialised
591	     * hr to zero up above, then fall into this case in such a
592	     * way so we add +12 +4 hours to it for teatime, +12 hours
593	     * to it for noon, and nothing at all for midnight, then
594	     * set our runtime to that hour before leaping into the
595	     * month scanner
596	     */
597    case TEATIME:
598	    hr += 4;
599    case NOON:
600	    hr += 12;
601    case MIDNIGHT:
602	    if (runtime.tm_hour >= hr) {
603		runtime.tm_mday++;
604		runtime.tm_wday++;
605	    }
606	    runtime.tm_hour = hr;
607	    runtime.tm_min = 0;
608	    token();
609	    /* FALLTHROUGH to month setting */
610    default:
611	    month(&runtime);
612	    break;
613    } /* ugly case statement */
614    expect(EOF);
615
616    /* adjust for daylight savings time
617     */
618    runtime.tm_isdst = -1;
619    runtimer = mktime(&runtime);
620    if (runtime.tm_isdst > 0) {
621	runtimer -= 3600;
622	runtimer = mktime(&runtime);
623    }
624
625    if (runtimer < 0)
626	panic("garbled time");
627
628    if (nowtimer > runtimer)
629	panic("trying to travel back in time");
630
631    return runtimer;
632} /* parsetime */
633