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