Import complex arithmetic functions from {Net,Free}BSD.
[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.27 2005/08/18 08:18:02 stefanf Exp $
36  * $DragonFly: src/usr.bin/at/parsetime.c,v 1.6 2007/08/26 16:12:27 pavalos 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
51 /* Local headers */
52
53 #include "at.h"
54 #include "panic.h"
55 #include "parsetime.h"
56
57
58 /* Structures and unions */
59
60 enum {  /* symbols */
61     MIDNIGHT, NOON, TEATIME,
62     PM, AM, TOMORROW, TODAY, NOW,
63     MINUTES, HOURS, DAYS, WEEKS, MONTHS, YEARS,
64     NUMBER, PLUS, DOT, SLASH, ID, JUNK,
65     JAN, FEB, MAR, APR, MAY, JUN,
66     JUL, AUG, SEP, OCT, NOV, DEC,
67     SUN, MON, TUE, WED, THU, FRI, SAT
68     };
69
70 /* parse translation table - table driven parsers can be your FRIEND!
71  */
72 struct {
73     const char *name;   /* token name */
74     int value;          /* token id */
75     int plural;         /* is this plural? */
76 } Specials[] = {
77     { "midnight", MIDNIGHT,0 }, /* 00:00:00 of today or tomorrow */
78     { "noon", NOON,0 },         /* 12:00:00 of today or tomorrow */
79     { "teatime", TEATIME,0 },   /* 16:00:00 of today or tomorrow */
80     { "am", AM,0 },             /* morning times for 0-12 clock */
81     { "pm", PM,0 },             /* evening times for 0-12 clock */
82     { "tomorrow", TOMORROW,0 }, /* execute 24 hours from time */
83     { "today", TODAY, 0 },      /* execute today - don't advance time */
84     { "now", NOW,0 },           /* opt prefix for PLUS */
85
86     { "minute", MINUTES,0 },    /* minutes multiplier */
87     { "minutes", MINUTES,1 },   /* (pluralized) */
88     { "hour", HOURS,0 },        /* hours ... */
89     { "hours", HOURS,1 },       /* (pluralized) */
90     { "day", DAYS,0 },          /* days ... */
91     { "days", DAYS,1 },         /* (pluralized) */
92     { "week", WEEKS,0 },        /* week ... */
93     { "weeks", WEEKS,1 },       /* (pluralized) */
94     { "month", MONTHS,0 },      /* month ... */
95     { "months", MONTHS,1 },     /* (pluralized) */
96     { "year", YEARS,0 },        /* year ... */
97     { "years", YEARS,1 },       /* (pluralized) */
98     { "jan", JAN,0 },
99     { "feb", FEB,0 },
100     { "mar", MAR,0 },
101     { "apr", APR,0 },
102     { "may", MAY,0 },
103     { "jun", JUN,0 },
104     { "jul", JUL,0 },
105     { "aug", AUG,0 },
106     { "sep", SEP,0 },
107     { "oct", OCT,0 },
108     { "nov", NOV,0 },
109     { "dec", DEC,0 },
110     { "january", JAN,0 },
111     { "february", FEB,0 },
112     { "march", MAR,0 },
113     { "april", APR,0 },
114     { "may", MAY,0 },
115     { "june", JUN,0 },
116     { "july", JUL,0 },
117     { "august", AUG,0 },
118     { "september", SEP,0 },
119     { "october", OCT,0 },
120     { "november", NOV,0 },
121     { "december", DEC,0 },
122     { "sunday", SUN, 0 },
123     { "sun", SUN, 0 },
124     { "monday", MON, 0 },
125     { "mon", MON, 0 },
126     { "tuesday", TUE, 0 },
127     { "tue", TUE, 0 },
128     { "wednesday", WED, 0 },
129     { "wed", WED, 0 },
130     { "thursday", THU, 0 },
131     { "thu", THU, 0 },
132     { "friday", FRI, 0 },
133     { "fri", FRI, 0 },
134     { "saturday", SAT, 0 },
135     { "sat", SAT, 0 },
136 } ;
137
138 /* File scope variables */
139
140 static char **scp;      /* scanner - pointer at arglist */
141 static char scc;        /* scanner - count of remaining arguments */
142 static char *sct;       /* scanner - next char pointer in current argument */
143 static int need;        /* scanner - need to advance to next argument */
144
145 static char *sc_token;  /* scanner - token buffer */
146 static size_t sc_len;   /* scanner - length of token buffer */
147 static int sc_tokid;    /* scanner - token id */
148 static int sc_tokplur;  /* scanner - is token plural? */
149
150 /* Local functions */
151
152 /*
153  * parse a token, checking if it's something special to us
154  */
155 static int
156 parse_token(char *arg)
157 {
158     size_t i;
159
160     for (i=0; i<(sizeof Specials/sizeof Specials[0]); i++)
161         if (strcasecmp(Specials[i].name, arg) == 0) {
162             sc_tokplur = Specials[i].plural;
163             return sc_tokid = Specials[i].value;
164         }
165
166     /* not special - must be some random id */
167     return ID;
168 } /* parse_token */
169
170
171 /*
172  * init_scanner() sets up the scanner to eat arguments
173  */
174 static void
175 init_scanner(int argc, char **argv)
176 {
177     scp = argv;
178     scc = argc;
179     need = 1;
180     sc_len = 1;
181     while (argc-- > 0)
182         sc_len += strlen(*argv++);
183
184     if ((sc_token = malloc(sc_len)) == NULL)
185         errx(EXIT_FAILURE, "virtual memory exhausted");
186 } /* init_scanner */
187
188 /*
189  * token() fetches a token from the input stream
190  */
191 static int
192 token(void)
193 {
194     int idx;
195
196     while (1) {
197         memset(sc_token, 0, sc_len);
198         sc_tokid = EOF;
199         sc_tokplur = 0;
200         idx = 0;
201
202         /* if we need to read another argument, walk along the argument list;
203          * when we fall off the arglist, we'll just return EOF forever
204          */
205         if (need) {
206             if (scc < 1)
207                 return sc_tokid;
208             sct = *scp;
209             scp++;
210             scc--;
211             need = 0;
212         }
213         /* eat whitespace now - if we walk off the end of the argument,
214          * we'll continue, which puts us up at the top of the while loop
215          * to fetch the next argument in
216          */
217         while (isspace(*sct))
218             ++sct;
219         if (!*sct) {
220             need = 1;
221             continue;
222         }
223
224         /* preserve the first character of the new token
225          */
226         sc_token[0] = *sct++;
227
228         /* then see what it is
229          */
230         if (isdigit(sc_token[0])) {
231             while (isdigit(*sct))
232                 sc_token[++idx] = *sct++;
233             sc_token[++idx] = 0;
234             return sc_tokid = NUMBER;
235         }
236         else if (isalpha(sc_token[0])) {
237             while (isalpha(*sct))
238                 sc_token[++idx] = *sct++;
239             sc_token[++idx] = 0;
240             return parse_token(sc_token);
241         }
242         else if (sc_token[0] == ':' || sc_token[0] == '.')
243             return sc_tokid = DOT;
244         else if (sc_token[0] == '+')
245             return sc_tokid = PLUS;
246         else if (sc_token[0] == '/')
247             return sc_tokid = SLASH;
248         else
249             return sc_tokid = JUNK;
250     } /* while (1) */
251 } /* token */
252
253
254 /*
255  * plonk() gives an appropriate error message if a token is incorrect
256  */
257 static void
258 plonk(int tok)
259 {
260     panic((tok == EOF) ? "incomplete time"
261                        : "garbled time");
262 } /* plonk */
263
264
265 /* 
266  * expect() gets a token and dies most horribly if it's not the token we want
267  */
268 static void
269 expect(int desired)
270 {
271     if (token() != desired)
272         plonk(sc_tokid);        /* and we die here... */
273 } /* expect */
274
275
276 /*
277  * plus() parses a now + time
278  *
279  *  at [NOW] PLUS NUMBER [MINUTES|HOURS|DAYS|WEEKS|MONTHS|YEARS]
280  *
281  */
282
283 static void
284 plus(struct tm *tm)
285 {
286     int delay;
287     int expectplur;
288
289     expect(NUMBER);
290
291     delay = atoi(sc_token);
292     expectplur = (delay != 1) ? 1 : 0;
293
294     switch (token()) {
295     case YEARS:
296             tm->tm_year += delay;
297             break;
298     case MONTHS:
299             tm->tm_mon += delay;
300             break;
301     case WEEKS:
302             delay *= 7;
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
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
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 += (lt->tm_year / 100) * 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
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     case TODAY: /* force ourselves to stay in today - no further processing */
462             token();
463             break;
464
465     case JAN: case FEB: case MAR: case APR: case MAY: case JUN:
466     case JUL: case AUG: case SEP: case OCT: case NOV: case DEC:
467             /* do month mday [year]
468              */
469             mon = (sc_tokid-JAN);
470             expect(NUMBER);
471             mday = atol(sc_token);
472             if (token() == NUMBER) {
473                 year = atol(sc_token);
474                 token();
475             }
476             assign_date(tm, mday, mon, year);
477             break;
478
479     case SUN: case MON: case TUE:
480     case WED: case THU: case FRI:
481     case SAT:
482             /* do a particular day of the week
483              */
484             wday = (sc_tokid-SUN);
485
486             mday = tm->tm_mday;
487
488             /* if this day is < today, then roll to next week
489              */
490             if (wday < tm->tm_wday)
491                 mday += 7 - (tm->tm_wday - wday);
492             else
493                 mday += (wday - tm->tm_wday);
494
495             tm->tm_wday = wday;
496
497             assign_date(tm, mday, tm->tm_mon, tm->tm_year);
498             break;
499
500     case NUMBER:
501             /* get numeric MMDDYY, mm/dd/yy, or dd.mm.yy
502              */
503             tlen = strlen(sc_token);
504             mon = atol(sc_token);
505             token();
506
507             if (sc_tokid == SLASH || sc_tokid == DOT) {
508                 int sep;
509
510                 sep = sc_tokid;
511                 expect(NUMBER);
512                 mday = atol(sc_token);
513                 if (token() == sep) {
514                     expect(NUMBER);
515                     year = atol(sc_token);
516                     token();
517                 }
518
519                 /* flip months and days for European timing
520                  */
521                 if (sep == DOT) {
522                     int x = mday;
523                     mday = mon;
524                     mon = x;
525                 }
526             }
527             else if (tlen == 6 || tlen == 8) {
528                 if (tlen == 8) {
529                     year = (mon % 10000) - 1900;
530                     mon /= 10000;
531                 }
532                 else {
533                     year = mon % 100;
534                     mon /= 100;
535                 }
536                 mday = mon % 100;
537                 mon /= 100;
538             }
539             else
540                 panic("garbled time");
541
542             mon--;
543             if (mon < 0 || mon > 11 || mday < 1 || mday > 31)
544                 panic("garbled time");
545
546             assign_date(tm, mday, mon, year);
547             break;
548     } /* case */
549 } /* month */
550
551
552 /* Global functions */
553
554 time_t
555 parsetime(int argc, char **argv)
556 {
557 /* Do the argument parsing, die if necessary, and return the time the job
558  * should be run.
559  */
560     time_t nowtimer, runtimer;
561     struct tm nowtime, runtime;
562     int hr = 0;
563     /* this MUST be initialized to zero for midnight/noon/teatime */
564
565     nowtimer = time(NULL);
566     nowtime = *localtime(&nowtimer);
567
568     runtime = nowtime;
569     runtime.tm_sec = 0;
570     runtime.tm_isdst = 0;
571
572     if (argc <= optind)
573         usage();
574
575     init_scanner(argc-optind, argv+optind);
576
577     switch (token()) {
578     case NOW:   
579             if (scc < 1) {
580                 return nowtimer;
581             }
582             /* now is optional prefix for PLUS tree */
583             expect(PLUS);
584     case PLUS:
585             plus(&runtime);
586             break;
587
588     case NUMBER:
589             tod(&runtime);
590             month(&runtime);
591             break;
592
593             /* evil coding for TEATIME|NOON|MIDNIGHT - we've initialised
594              * hr to zero up above, then fall into this case in such a
595              * way so we add +12 +4 hours to it for teatime, +12 hours
596              * to it for noon, and nothing at all for midnight, then
597              * set our runtime to that hour before leaping into the
598              * month scanner
599              */
600     case TEATIME:
601             hr += 4;
602     case NOON:
603             hr += 12;
604     case MIDNIGHT:
605             if (runtime.tm_hour >= hr) {
606                 runtime.tm_mday++;
607                 runtime.tm_wday++;
608             }
609             runtime.tm_hour = hr;
610             runtime.tm_min = 0;
611             token();
612             /* FALLTHROUGH to month setting */
613     default:
614             month(&runtime);
615             break;
616     } /* ugly case statement */
617     expect(EOF);
618
619     /* convert back to time_t
620      */
621     runtime.tm_isdst = -1;
622     runtimer = mktime(&runtime);
623
624     if (runtimer < 0)
625         panic("garbled time");
626
627     if (nowtimer > runtimer)
628         panic("trying to travel back in time");
629
630     return runtimer;
631 } /* parsetime */