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