/*-1* parsetime.c - parse time for at(1)2*3* SPDX-License-Identifier: BSD-2-Clause4*5* Copyright (C) 1993, 1994 Thomas Koenig6*7* modifications for English-language times8* Copyright (C) 1993 David Parsons9*10* Redistribution and use in source and binary forms, with or without11* modification, are permitted provided that the following conditions12* are met:13* 1. Redistributions of source code must retain the above copyright14* notice, this list of conditions and the following disclaimer.15* 2. The name of the author(s) may not be used to endorse or promote16* products derived from this software without specific prior written17* permission.18*19* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR20* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES21* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.22* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,23* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT24* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26* THEORY OF LIABILITY, WETHER IN CONTRACT, STRICT LIABILITY, OR TORT27* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF28* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*30* at [NOW] PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS31* /NUMBER [DOT NUMBER] [AM|PM]\ /[MONTH NUMBER [NUMBER]] \32* |NOON | |[TOMORROW] |33* |MIDNIGHT | |[DAY OF WEEK] |34* \TEATIME / |NUMBER [SLASH NUMBER [SLASH NUMBER]]|35* \PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS/36*/3738#include <sys/cdefs.h>39/* System Headers */4041#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 __FreeBSD__51#include <getopt.h>52#endif5354/* Local headers */5556#include "at.h"57#include "panic.h"58#include "parsetime.h"596061/* Structures and unions */6263enum { /* symbols */64MIDNIGHT, NOON, TEATIME,65PM, AM, TOMORROW, TODAY, NOW,66MINUTES, HOURS, DAYS, WEEKS, MONTHS, YEARS,67NUMBER, PLUS, MINUS, DOT, SLASH, ID, JUNK,68JAN, FEB, MAR, APR, MAY, JUN,69JUL, AUG, SEP, OCT, NOV, DEC,70SUN, MON, TUE, WED, THU, FRI, SAT71};7273/* parse translation table - table driven parsers can be your FRIEND!74*/75static const struct {76const char *name; /* token name */77int value; /* token id */78int plural; /* is this plural? */79} Specials[] = {80{ "midnight", MIDNIGHT,0 }, /* 00:00:00 of today or tomorrow */81{ "noon", NOON,0 }, /* 12:00:00 of today or tomorrow */82{ "teatime", TEATIME,0 }, /* 16:00:00 of today or tomorrow */83{ "am", AM,0 }, /* morning times for 0-12 clock */84{ "pm", PM,0 }, /* evening times for 0-12 clock */85{ "tomorrow", TOMORROW,0 }, /* execute 24 hours from time */86{ "today", TODAY, 0 }, /* execute today - don't advance time */87{ "now", NOW,0 }, /* opt prefix for PLUS */8889{ "minute", MINUTES,0 }, /* minutes multiplier */90{ "minutes", MINUTES,1 }, /* (pluralized) */91{ "hour", HOURS,0 }, /* hours ... */92{ "hours", HOURS,1 }, /* (pluralized) */93{ "day", DAYS,0 }, /* days ... */94{ "days", DAYS,1 }, /* (pluralized) */95{ "week", WEEKS,0 }, /* week ... */96{ "weeks", WEEKS,1 }, /* (pluralized) */97{ "month", MONTHS,0 }, /* month ... */98{ "months", MONTHS,1 }, /* (pluralized) */99{ "year", YEARS,0 }, /* year ... */100{ "years", YEARS,1 }, /* (pluralized) */101{ "jan", JAN,0 },102{ "feb", FEB,0 },103{ "mar", MAR,0 },104{ "apr", APR,0 },105{ "may", MAY,0 },106{ "jun", JUN,0 },107{ "jul", JUL,0 },108{ "aug", AUG,0 },109{ "sep", SEP,0 },110{ "oct", OCT,0 },111{ "nov", NOV,0 },112{ "dec", DEC,0 },113{ "january", JAN,0 },114{ "february", FEB,0 },115{ "march", MAR,0 },116{ "april", APR,0 },117{ "may", MAY,0 },118{ "june", JUN,0 },119{ "july", JUL,0 },120{ "august", AUG,0 },121{ "september", SEP,0 },122{ "october", OCT,0 },123{ "november", NOV,0 },124{ "december", DEC,0 },125{ "sunday", SUN, 0 },126{ "sun", SUN, 0 },127{ "monday", MON, 0 },128{ "mon", MON, 0 },129{ "tuesday", TUE, 0 },130{ "tue", TUE, 0 },131{ "wednesday", WED, 0 },132{ "wed", WED, 0 },133{ "thursday", THU, 0 },134{ "thu", THU, 0 },135{ "friday", FRI, 0 },136{ "fri", FRI, 0 },137{ "saturday", SAT, 0 },138{ "sat", SAT, 0 },139} ;140141/* File scope variables */142143static char **scp; /* scanner - pointer at arglist */144static char scc; /* scanner - count of remaining arguments */145static char *sct; /* scanner - next char pointer in current argument */146static int need; /* scanner - need to advance to next argument */147148static char *sc_token; /* scanner - token buffer */149static size_t sc_len; /* scanner - length of token buffer */150static int sc_tokid; /* scanner - token id */151static int sc_tokplur; /* scanner - is token plural? */152153/* Local functions */154155/*156* parse a token, checking if it's something special to us157*/158static int159parse_token(char *arg)160{161size_t i;162163for (i=0; i<(sizeof Specials/sizeof Specials[0]); i++)164if (strcasecmp(Specials[i].name, arg) == 0) {165sc_tokplur = Specials[i].plural;166return sc_tokid = Specials[i].value;167}168169/* not special - must be some random id */170return ID;171} /* parse_token */172173174/*175* init_scanner() sets up the scanner to eat arguments176*/177static void178init_scanner(int argc, char **argv)179{180scp = argv;181scc = argc;182need = 1;183sc_len = 1;184while (argc-- > 0)185sc_len += strlen(*argv++);186187if ((sc_token = malloc(sc_len)) == NULL)188errx(EXIT_FAILURE, "virtual memory exhausted");189} /* init_scanner */190191/*192* token() fetches a token from the input stream193*/194static int195token(void)196{197int idx;198199while (1) {200memset(sc_token, 0, sc_len);201sc_tokid = EOF;202sc_tokplur = 0;203idx = 0;204205/* if we need to read another argument, walk along the argument list;206* when we fall off the arglist, we'll just return EOF forever207*/208if (need) {209if (scc < 1)210return sc_tokid;211sct = *scp;212scp++;213scc--;214need = 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 loop218* to fetch the next argument in219*/220while (isspace(*sct))221++sct;222if (!*sct) {223need = 1;224continue;225}226227/* preserve the first character of the new token228*/229sc_token[0] = *sct++;230231/* then see what it is232*/233if (isdigit(sc_token[0])) {234while (isdigit(*sct))235sc_token[++idx] = *sct++;236sc_token[++idx] = 0;237return sc_tokid = NUMBER;238}239else if (isalpha(sc_token[0])) {240while (isalpha(*sct))241sc_token[++idx] = *sct++;242sc_token[++idx] = 0;243return parse_token(sc_token);244}245else if (sc_token[0] == ':' || sc_token[0] == '.')246return sc_tokid = DOT;247else if (sc_token[0] == '+')248return sc_tokid = PLUS;249else if (sc_token[0] == '-')250return sc_tokid = MINUS;251else if (sc_token[0] == '/')252return sc_tokid = SLASH;253else254return sc_tokid = JUNK;255} /* while (1) */256} /* token */257258259/*260* plonk() gives an appropriate error message if a token is incorrect261*/262static void263plonk(int tok)264{265panic((tok == EOF) ? "incomplete time"266: "garbled time");267} /* plonk */268269270/*271* expect() gets a token and dies most horribly if it's not the token we want272*/273static void274expect(int desired)275{276if (token() != desired)277plonk(sc_tokid); /* and we die here... */278} /* expect */279280281/*282* plus_or_minus() holds functionality common to plus() and minus()283*/284static void285plus_or_minus(struct tm *tm, int delay)286{287int expectplur;288289expectplur = (delay != 1 && delay != -1) ? 1 : 0;290291switch (token()) {292case YEARS:293tm->tm_year += delay;294break;295case MONTHS:296tm->tm_mon += delay;297break;298case WEEKS:299delay *= 7;300case DAYS:301tm->tm_mday += delay;302break;303case HOURS:304tm->tm_hour += delay;305break;306case MINUTES:307tm->tm_min += delay;308break;309default:310plonk(sc_tokid);311break;312}313314if (expectplur != sc_tokplur)315warnx("pluralization is wrong");316317tm->tm_isdst = -1;318if (mktime(tm) < 0)319plonk(sc_tokid);320} /* plus_or_minus */321322323/*324* plus() parses a now + time325*326* at [NOW] PLUS NUMBER [MINUTES|HOURS|DAYS|WEEKS|MONTHS|YEARS]327*328*/329static void330plus(struct tm *tm)331{332int delay;333334expect(NUMBER);335336delay = atoi(sc_token);337plus_or_minus(tm, delay);338} /* plus */339340341/*342* minus() is like plus but can not be used with NOW343*/344static void345minus(struct tm *tm)346{347int delay;348349expect(NUMBER);350351delay = -atoi(sc_token);352plus_or_minus(tm, delay);353} /* minus */354355356/*357* tod() computes the time of day358* [NUMBER [DOT NUMBER] [AM|PM]]359*/360static void361tod(struct tm *tm)362{363int hour, minute = 0;364int tlen;365366hour = atoi(sc_token);367tlen = strlen(sc_token);368369/* first pick out the time of day - if it's 4 digits, we assume370* a HHMM time, otherwise it's HH DOT MM time371*/372if (token() == DOT) {373expect(NUMBER);374minute = atoi(sc_token);375if (minute > 59)376panic("garbled time");377token();378}379else if (tlen == 4) {380minute = hour%100;381if (minute > 59)382panic("garbled time");383hour = hour/100;384}385386/* check if an AM or PM specifier was given387*/388if (sc_tokid == AM || sc_tokid == PM) {389if (hour > 12)390panic("garbled time");391392if (sc_tokid == PM) {393if (hour != 12) /* 12:xx PM is 12:xx, not 24:xx */394hour += 12;395} else {396if (hour == 12) /* 12:xx AM is 00:xx, not 12:xx */397hour = 0;398}399token();400}401else if (hour > 23)402panic("garbled time");403404/* if we specify an absolute time, we don't want to bump the day even405* if we've gone past that time - but if we're specifying a time plus406* a relative offset, it's okay to bump things407*/408if ((sc_tokid == EOF || sc_tokid == PLUS || sc_tokid == MINUS) &&409tm->tm_hour > hour) {410tm->tm_mday++;411tm->tm_wday++;412}413414tm->tm_hour = hour;415tm->tm_min = minute;416if (tm->tm_hour == 24) {417tm->tm_hour = 0;418tm->tm_mday++;419}420} /* tod */421422423/*424* assign_date() assigns a date, wrapping to next year if needed425*/426static void427assign_date(struct tm *tm, long mday, long mon, long year)428{429430/*431* Convert year into tm_year format (year - 1900).432* We may be given the year in 2 digit, 4 digit, or tm_year format.433*/434if (year != -1) {435if (year >= 1900)436year -= 1900; /* convert from 4 digit year */437else if (year < 100) {438/* convert from 2 digit year */439struct tm *lt;440time_t now;441442time(&now);443lt = localtime(&now);444445/* Convert to tm_year assuming current century */446year += (lt->tm_year / 100) * 100;447448if (year == lt->tm_year - 1) year++;449else if (year < lt->tm_year)450year += 100; /* must be in next century */451}452}453454if (year < 0 &&455(tm->tm_mon > mon ||(tm->tm_mon == mon && tm->tm_mday > mday)))456year = tm->tm_year + 1;457458tm->tm_mday = mday;459tm->tm_mon = mon;460461if (year >= 0)462tm->tm_year = year;463} /* assign_date */464465466/*467* month() picks apart a month specification468*469* /[<month> NUMBER [NUMBER]] \470* |[TOMORROW] |471* |[DAY OF WEEK] |472* |NUMBER [SLASH NUMBER [SLASH NUMBER]]|473* \PLUS NUMBER MINUTES|HOURS|DAYS|WEEKS/474*/475static void476month(struct tm *tm)477{478long year= (-1);479long mday = 0, wday, mon;480int tlen;481482switch (sc_tokid) {483case PLUS:484plus(tm);485break;486case MINUS:487minus(tm);488break;489490case TOMORROW:491/* do something tomorrow */492tm->tm_mday ++;493tm->tm_wday ++;494case TODAY: /* force ourselves to stay in today - no further processing */495token();496break;497498case JAN: case FEB: case MAR: case APR: case MAY: case JUN:499case JUL: case AUG: case SEP: case OCT: case NOV: case DEC:500/* do month mday [year]501*/502mon = (sc_tokid-JAN);503expect(NUMBER);504mday = atol(sc_token);505if (token() == NUMBER) {506year = atol(sc_token);507token();508}509assign_date(tm, mday, mon, year);510break;511512case SUN: case MON: case TUE:513case WED: case THU: case FRI:514case SAT:515/* do a particular day of the week516*/517wday = (sc_tokid-SUN);518519mday = tm->tm_mday;520521/* if this day is < today, then roll to next week522*/523if (wday < tm->tm_wday)524mday += 7 - (tm->tm_wday - wday);525else526mday += (wday - tm->tm_wday);527528tm->tm_wday = wday;529530assign_date(tm, mday, tm->tm_mon, tm->tm_year);531break;532533case NUMBER:534/* get numeric MMDDYY, mm/dd/yy, or dd.mm.yy535*/536tlen = strlen(sc_token);537mon = atol(sc_token);538token();539540if (sc_tokid == SLASH || sc_tokid == DOT) {541int sep;542543sep = sc_tokid;544expect(NUMBER);545mday = atol(sc_token);546if (token() == sep) {547expect(NUMBER);548year = atol(sc_token);549token();550}551552/* flip months and days for European timing553*/554if (sep == DOT) {555int x = mday;556mday = mon;557mon = x;558}559}560else if (tlen == 6 || tlen == 8) {561if (tlen == 8) {562year = (mon % 10000) - 1900;563mon /= 10000;564}565else {566year = mon % 100;567mon /= 100;568}569mday = mon % 100;570mon /= 100;571}572else573panic("garbled time");574575mon--;576if (mon < 0 || mon > 11 || mday < 1 || mday > 31)577panic("garbled time");578579assign_date(tm, mday, mon, year);580break;581} /* case */582} /* month */583584585/* Global functions */586587time_t588parsetime(int argc, char **argv)589{590/* Do the argument parsing, die if necessary, and return the time the job591* should be run.592*/593time_t nowtimer, runtimer;594struct tm nowtime, runtime;595int hr = 0;596/* this MUST be initialized to zero for midnight/noon/teatime */597598nowtimer = time(NULL);599nowtime = *localtime(&nowtimer);600601runtime = nowtime;602runtime.tm_sec = 0;603runtime.tm_isdst = 0;604605if (argc <= optind)606usage();607608init_scanner(argc-optind, argv+optind);609610switch (token()) {611case NOW:612if (scc < 1) {613return nowtimer;614}615/* now is optional prefix for PLUS tree */616expect(PLUS);617/* FALLTHROUGH */618case PLUS:619plus(&runtime);620break;621622/* MINUS is different from PLUS in that NOW is not623* an optional prefix for it624*/625case MINUS:626minus(&runtime);627break;628case NUMBER:629tod(&runtime);630month(&runtime);631break;632633/* evil coding for TEATIME|NOON|MIDNIGHT - we've initialised634* hr to zero up above, then fall into this case in such a635* way so we add +12 +4 hours to it for teatime, +12 hours636* to it for noon, and nothing at all for midnight, then637* set our runtime to that hour before leaping into the638* month scanner639*/640case TEATIME:641hr += 4;642/* FALLTHROUGH */643case NOON:644hr += 12;645/* FALLTHROUGH */646case MIDNIGHT:647if (runtime.tm_hour >= hr) {648runtime.tm_mday++;649runtime.tm_wday++;650}651runtime.tm_hour = hr;652runtime.tm_min = 0;653token();654/* FALLTHROUGH to month setting */655default:656month(&runtime);657break;658} /* ugly case statement */659expect(EOF);660661/* convert back to time_t662*/663runtime.tm_isdst = -1;664runtimer = mktime(&runtime);665666if (runtimer < 0)667panic("garbled time");668669if (nowtimer > runtimer)670panic("trying to travel back in time");671672return runtimer;673} /* parsetime */674675676