Home | History | Annotate | Line # | Download | only in calendar
calendar.c revision 1.31
      1 /*	$NetBSD: calendar.c,v 1.31 2004/11/29 17:03:43 jwise Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1989, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\n\
     35 	The Regents of the University of California.  All rights reserved.\n");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)calendar.c	8.4 (Berkeley) 1/7/95";
     41 #endif
     42 __RCSID("$NetBSD: calendar.c,v 1.31 2004/11/29 17:03:43 jwise Exp $");
     43 #endif /* not lint */
     44 
     45 #include <sys/param.h>
     46 #include <sys/time.h>
     47 #include <sys/stat.h>
     48 #include <sys/uio.h>
     49 #include <sys/wait.h>
     50 
     51 #include <ctype.h>
     52 #include <err.h>
     53 #include <errno.h>
     54 #include <fcntl.h>
     55 #include <pwd.h>
     56 #include <stdio.h>
     57 #include <stdlib.h>
     58 #include <string.h>
     59 #include <time.h>
     60 #include <tzfile.h>
     61 #include <unistd.h>
     62 
     63 #include "pathnames.h"
     64 
     65 #ifndef TRUE
     66 #define TRUE 1
     67 #endif
     68 #ifndef FALSE
     69 #define FALSE 0
     70 #endif
     71 
     72 static unsigned short lookahead = 1, weekend = 2;
     73 static char *fname = NULL, *datestr = NULL;
     74 static char *defaultnames[] = {"calendar", ".calendar", "/etc/calendar", NULL};
     75 static struct passwd *pw;
     76 static int doall;
     77 static char path[MAXPATHLEN + 1];
     78 
     79 /* 1-based month, 0-based days, cumulative */
     80 static int daytab[][14] = {
     81 	{ 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
     82 	{ 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
     83 };
     84 static struct tm *tp;
     85 static int *cumdays, offset, yrdays;
     86 static char dayname[10];
     87 
     88 static struct iovec header[] = {
     89 	{ "From: ", 6 },
     90 	{ NULL, 0 },
     91 	{ " (Reminder Service)\nTo: ", 24 },
     92 	{ NULL, 0 },
     93 	{ "\nSubject: ", 10 },
     94 	{ NULL, 0 },
     95 	{ "'s Calendar\nPrecedence: bulk\n\n",  30 },
     96 };
     97 
     98 static char *days[] = {
     99 	"sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
    100 };
    101 
    102 static char *months[] = {
    103 	"jan", "feb", "mar", "apr", "may", "jun",
    104 	"jul", "aug", "sep", "oct", "nov", "dec", NULL,
    105 };
    106 
    107 int	 main(int, char **);
    108 
    109 static void	 atodays(int, char *, unsigned short *);
    110 static void	 cal(void);
    111 static void	 closecal(FILE *);
    112 static int	 getday(char *);
    113 static int	 getfield(char *, char **, int *);
    114 static void	 getmmdd(struct tm *, char *);
    115 static int	 getmonth(char *);
    116 static int	 isnow(char *);
    117 static FILE	*opencal(void);
    118 static void	 settime(void);
    119 static void	 usage(void) __attribute__((__noreturn__));
    120 
    121 int
    122 main(argc, argv)
    123 	int argc;
    124 	char *argv[];
    125 {
    126 	int ch;
    127 	const char *caldir;
    128 
    129 	while ((ch = getopt(argc, argv, "-ad:f:l:w:")) != -1)
    130 		switch (ch) {
    131 		case '-':		/* backward contemptible */
    132 		case 'a':
    133 			if (getuid()) {
    134 				errno = EPERM;
    135 				err(1, NULL);
    136 			}
    137 			doall = 1;
    138 			break;
    139 		case 'd':
    140 			datestr = optarg;
    141 			break;
    142 		case 'f':
    143 			fname = optarg;
    144 			break;
    145 		case 'l':
    146 			atodays(ch, optarg, &lookahead);
    147 			break;
    148 		case 'w':
    149 			atodays(ch, optarg, &weekend);
    150 			break;
    151 		case '?':
    152 		default:
    153 			usage();
    154 		}
    155 	argc -= optind;
    156 	argv += optind;
    157 
    158 	if (argc)
    159 		usage();
    160 
    161 	settime();
    162 	if (doall) {
    163 		while ((pw = getpwent()) != NULL) {
    164 			(void)setegid(pw->pw_gid);
    165 			(void)seteuid(pw->pw_uid);
    166 			if (!chdir(pw->pw_dir))
    167 				cal();
    168 			(void)seteuid(0);
    169 		}
    170 	} else if ((caldir = getenv("CALENDAR_DIR")) != NULL) {
    171 		if(!chdir(caldir))
    172 			cal();
    173 	} else {
    174 		cal();
    175 	}
    176 	exit(0);
    177 }
    178 
    179 static void
    180 cal(void)
    181 {
    182 	int printing;
    183 	FILE *fp;
    184 	char *line;
    185 
    186 	if ((fp = opencal()) == NULL)
    187 		return;
    188 	while ((line = fparseln(stdin, NULL, NULL, NULL, FPARSELN_UNESCCOMM))
    189 	    != NULL) {
    190 		if (line[0] == '\0')
    191 			continue;
    192 		if (line[0] != '\t')
    193 			printing = isnow(line) ? 1 : 0;
    194 		if (printing)
    195 			(void)fprintf(fp, "%s\n", line);
    196 		free(line);
    197 
    198 	}
    199 	closecal(fp);
    200 }
    201 
    202 
    203 static void
    204 settime(void)
    205 {
    206 	time_t now;
    207 
    208 	(void)time(&now);
    209 	tp = localtime(&now);
    210 	if (datestr) {
    211 		getmmdd(tp, datestr);
    212 	}
    213 	if (isleap(tp->tm_year + TM_YEAR_BASE)) {
    214 		yrdays = DAYSPERLYEAR;
    215 		cumdays = daytab[1];
    216 	} else {
    217 		yrdays = DAYSPERNYEAR;
    218 		cumdays = daytab[0];
    219 	}
    220 	/* Friday displays Monday's events */
    221 	offset = tp->tm_wday == 5 ? lookahead + weekend : lookahead;
    222 	header[5].iov_base = dayname;
    223 	header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
    224 }
    225 
    226 /*
    227  * Possible date formats include any combination of:
    228  *	3-charmonth			(January, Jan, Jan)
    229  *	3-charweekday			(Friday, Monday, mon.)
    230  *	numeric month or day		(1, 2, 04)
    231  *
    232  * Any character may separate them, or they may not be separated.  Any line,
    233  * following a line that is matched, that starts with "whitespace", is shown
    234  * along with the matched line.
    235  */
    236 static int
    237 isnow(endp)
    238 	char *endp;
    239 {
    240 	int day, flags, month, v1, v2;
    241 
    242 #define	F_ISMONTH	0x01
    243 #define	F_ISDAY		0x02
    244 	flags = 0;
    245 	/* didn't recognize anything, skip it */
    246 	if (!(v1 = getfield(endp, &endp, &flags)))
    247 		return (0);
    248 	if (flags & F_ISDAY || v1 > 12) {
    249 		/* found a day */
    250 		day = v1;
    251 		month = tp->tm_mon + 1;
    252 	} else if (flags & F_ISMONTH) {
    253 		month = v1;
    254 		/* if no recognizable day, assume the first */
    255 		if (!(day = getfield(endp, &endp, &flags)))
    256 			day = 1;
    257 	} else {
    258 		v2 = getfield(endp, &endp, &flags);
    259 		if (flags & F_ISMONTH) {
    260 			day = v1;
    261 			month = v2;
    262 		} else {
    263 			/* F_ISDAY set, v2 > 12, or no way to tell */
    264 			month = v1;
    265 			/* if no recognizable day, assume the first */
    266 			day = v2 ? v2 : 1;
    267 		}
    268 	}
    269 	if (flags & F_ISDAY)
    270 		day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
    271 	day = cumdays[month] + day;
    272 
    273 	/* if today or today + offset days */
    274 	if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
    275 		return (1);
    276 	/* if number of days left in this year + days to event in next year */
    277 	if (yrdays - tp->tm_yday + day <= offset)
    278 		return (1);
    279 	return (0);
    280 }
    281 
    282 static int
    283 getfield(p, endp, flags)
    284 	char *p, **endp;
    285 	int *flags;
    286 {
    287 	int val;
    288 	char *start, savech;
    289 
    290 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
    291     !isalpha((unsigned char)*p) && *p != '*')
    292 
    293 	for (; FLDCHAR(*p); ++p)
    294 		continue;
    295 	if (*p == '*') {			/* `*' is current month */
    296 		*flags |= F_ISMONTH;
    297 		*endp = p+1;
    298 		return (tp->tm_mon + 1);
    299 	}
    300 	if (isdigit((unsigned char)*p)) {
    301 		val = strtol(p, &p, 10);	/* if 0, it's failure */
    302 		for (; FLDCHAR(*p); ++p)
    303 			continue;
    304 		*endp = p;
    305 		return (val);
    306 	}
    307 	for (start = p; *p != '\0' && isalpha((unsigned char)*++p);)
    308 		continue;
    309 	savech = *p;
    310 	*p = '\0';
    311 	if ((val = getmonth(start)) != 0) {
    312 		*flags |= F_ISMONTH;
    313 	} else if ((val = getday(start)) != 0) {
    314 		*flags |= F_ISDAY;
    315 	} else {
    316 		*p = savech;
    317 		return (0);
    318 	}
    319 	for (*p = savech; FLDCHAR(*p); ++p)
    320 		continue;
    321 	*endp = p;
    322 	return (val);
    323 }
    324 
    325 static FILE *
    326 opencal(void)
    327 {
    328 	int fd, pdes[2];
    329 	char **name;
    330 
    331 	/* open up calendar file as stdin */
    332 	if (fname == NULL) {
    333 		for (name = defaultnames; *name != NULL; name++) {
    334 			if (!freopen(*name, "rf", stdin))
    335 				continue;
    336 			else
    337 				break;
    338 		}
    339 		if (*name == NULL) {
    340 			if (doall)
    341 				return (NULL);
    342 			err(1, "Cannot open calendar file");
    343 		}
    344 	} else if (!freopen(fname, "rf", stdin)) {
    345 		if (doall)
    346 			return (NULL);
    347 		err(1, "Cannot open `%s'", fname);
    348 	}
    349 
    350 	if (pipe(pdes) < 0) {
    351 		warn("Cannot open pipe");
    352 		return (NULL);
    353 	}
    354 
    355 	switch (fork()) {
    356 	case -1:			/* error */
    357 		(void)close(pdes[0]);
    358 		(void)close(pdes[1]);
    359 		return (NULL);
    360 	case 0:
    361 		/* child -- stdin already setup, set stdout to pipe input */
    362 		if (pdes[1] != STDOUT_FILENO) {
    363 			(void)dup2(pdes[1], STDOUT_FILENO);
    364 			(void)close(pdes[1]);
    365 		}
    366 		(void)close(pdes[0]);
    367 		(void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
    368 		    "-I" _PATH_CALENDARS, NULL);
    369 		err(1, "Cannot exec `%s'", _PATH_CPP);
    370 		/*NOTREACHED*/
    371 	}
    372 
    373 	/* parent -- set stdin to pipe output */
    374 	(void)dup2(pdes[0], STDIN_FILENO);
    375 	(void)close(pdes[0]);
    376 	(void)close(pdes[1]);
    377 
    378 	/* not reading all calendar files, just set output to stdout */
    379 	if (!doall)
    380 		return (stdout);
    381 
    382 	/* set output to a temporary file, so if no output don't send mail */
    383 	(void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
    384 	if ((fd = mkstemp(path)) < 0) {
    385 		warn("Cannot create temporary file");
    386 		return (NULL);
    387 	}
    388 	return (fdopen(fd, "w+"));
    389 }
    390 
    391 static void
    392 closecal(fp)
    393 	FILE *fp;
    394 {
    395 	struct stat sbuf;
    396 	int nread, pdes[2], status;
    397 	char buf[1024];
    398 
    399 	if (!doall)
    400 		return;
    401 
    402 	(void)rewind(fp);
    403 	if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
    404 		goto done;
    405 	if (pipe(pdes) < 0)
    406 		goto done;
    407 	switch (fork()) {
    408 	case -1:			/* error */
    409 		(void)close(pdes[0]);
    410 		(void)close(pdes[1]);
    411 		goto done;
    412 	case 0:
    413 		/* child -- set stdin to pipe output */
    414 		if (pdes[0] != STDIN_FILENO) {
    415 			(void)dup2(pdes[0], STDIN_FILENO);
    416 			(void)close(pdes[0]);
    417 		}
    418 		(void)close(pdes[1]);
    419 		(void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
    420 		    "\"Reminder Service\"", "-f", "root", NULL);
    421 		err(1, "Cannot exec `%s'", _PATH_SENDMAIL);
    422 		/*NOTREACHED*/
    423 	}
    424 	/* parent -- write to pipe input */
    425 	(void)close(pdes[0]);
    426 
    427 	header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
    428 	header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
    429 	writev(pdes[1], header, 7);
    430 	while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
    431 		(void)write(pdes[1], buf, nread);
    432 	(void)close(pdes[1]);
    433 
    434 done:	(void)fclose(fp);
    435 	(void)unlink(path);
    436 	while (wait(&status) >= 0)
    437 		continue;
    438 }
    439 
    440 static int
    441 getmonth(s)
    442 	char *s;
    443 {
    444 	char **p;
    445 
    446 	for (p = months; *p; ++p)
    447 		if (!strncasecmp(s, *p, 3))
    448 			return ((p - months) + 1);
    449 	return (0);
    450 }
    451 
    452 static int
    453 getday(s)
    454 	char *s;
    455 {
    456 	char **p;
    457 
    458 	for (p = days; *p; ++p)
    459 		if (!strncasecmp(s, *p, 3))
    460 			return ((p - days) + 1);
    461 	return (0);
    462 }
    463 
    464 static void
    465 atodays(int ch, char *optarg, unsigned short *days)
    466 {
    467 	int u;
    468 
    469 	u = atoi(optarg);
    470 	if ((u < 0) || (u > 366)) {
    471 		warnx("-%c %d out of range 0-366, ignored.", ch, u);
    472 	} else {
    473 		*days = u;
    474 	}
    475 }
    476 
    477 #define todigit(x) ((x) - '0')
    478 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
    479 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
    480 
    481 static void
    482 getmmdd(struct tm *tp, char *ds)
    483 {
    484 	int ok = FALSE;
    485 	struct tm ttm;
    486 
    487 	ttm = *tp;
    488 	ttm.tm_isdst = -1;
    489 
    490 	if (ISDIG2(ds)) {
    491 		ttm.tm_mon = ATOI2(ds) - 1;
    492 		ds += 2;
    493 	}
    494 
    495 	if (ISDIG2(ds)) {
    496 		ttm.tm_mday = ATOI2(ds);
    497 		ds += 2;
    498 
    499 		ok = TRUE;
    500 	}
    501 
    502 	if (ok) {
    503 		if (ISDIG2(ds) && ISDIG2(ds + 2)) {
    504 			ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
    505 			ds += 2;
    506 			ttm.tm_year += ATOI2(ds);
    507 		} else if (ISDIG2(ds)) {
    508 			ttm.tm_year = ATOI2(ds);
    509 			if (ttm.tm_year < 69)
    510 				ttm.tm_year += 2000 - TM_YEAR_BASE;
    511 			else
    512 				ttm.tm_year += 1900 - TM_YEAR_BASE;
    513 		}
    514 	}
    515 
    516 	if (ok && (mktime(&ttm) < 0)) {
    517 		ok = FALSE;
    518 	}
    519 
    520 	if (ok) {
    521 		*tp = ttm;
    522 	} else {
    523 		warnx("Can't convert `%s' to date, ignored.", ds);
    524 		usage();
    525 	}
    526 }
    527 
    528 static void
    529 usage(void)
    530 {
    531 	(void)fprintf(stderr, "usage: %s [-a] [-d MMDD[[YY]YY]"
    532 	    " [-f fname] [-l days] [-w days]\n", getprogname());
    533 	exit(1);
    534 }
    535