Home | History | Annotate | Line # | Download | only in calendar
calendar.c revision 1.42
      1 /*	$NetBSD: calendar.c,v 1.42 2007/12/15 19:44:49 perry 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.42 2007/12/15 19:44:49 perry 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", _PATH_SYSTEM_CALENDAR, NULL};
     75 static struct passwd *pw;
     76 static int doall;
     77 static char path[MAXPATHLEN + 1];
     78 static int cpp_restricted = 0;
     79 
     80 /* 1-based month, 0-based days, cumulative */
     81 static int daytab[][14] = {
     82 	{ 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
     83 	{ 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
     84 };
     85 static struct tm *tp;
     86 static int *cumdays, offset, yrdays;
     87 static char dayname[10];
     88 
     89 static struct iovec header[] = {
     90 	{ "From: ", 6 },
     91 	{ NULL, 0 },
     92 	{ " (Reminder Service)\nTo: ", 24 },
     93 	{ NULL, 0 },
     94 	{ "\nSubject: ", 10 },
     95 	{ NULL, 0 },
     96 	{ "'s Calendar\nPrecedence: bulk\n\n",  30 },
     97 };
     98 
     99 static char *days[] = {
    100 	"sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
    101 };
    102 
    103 static char *months[] = {
    104 	"jan", "feb", "mar", "apr", "may", "jun",
    105 	"jul", "aug", "sep", "oct", "nov", "dec", NULL,
    106 };
    107 
    108 int	 main(int, char **);
    109 
    110 static void	 atodays(int, char *, unsigned short *);
    111 static void	 cal(void);
    112 static void	 closecal(FILE *);
    113 static int	 getday(char *);
    114 static int	 getfield(char *, char **, int *);
    115 static void	 getmmdd(struct tm *, char *);
    116 static int	 getmonth(char *);
    117 static int	 isnow(char *);
    118 static FILE	*opencal(void);
    119 static void	 settime(void);
    120 static void	 usage(void) __dead;
    121 
    122 int
    123 main(argc, argv)
    124 	int argc;
    125 	char *argv[];
    126 {
    127 	int ch;
    128 	const char *caldir;
    129 
    130 	while ((ch = getopt(argc, argv, "-ad:f:l:w:x")) != -1)
    131 		switch (ch) {
    132 		case '-':		/* backward contemptible */
    133 		case 'a':
    134 			if (getuid()) {
    135 				errno = EPERM;
    136 				err(1, NULL);
    137 			}
    138 			doall = 1;
    139 			break;
    140 		case 'd':
    141 			datestr = optarg;
    142 			break;
    143 		case 'f':
    144 			fname = optarg;
    145 			break;
    146 		case 'l':
    147 			atodays(ch, optarg, &lookahead);
    148 			break;
    149 		case 'w':
    150 			atodays(ch, optarg, &weekend);
    151 			break;
    152 		case 'x':
    153 			cpp_restricted = 1;
    154 			break;
    155 		case '?':
    156 		default:
    157 			usage();
    158 		}
    159 	argc -= optind;
    160 	argv += optind;
    161 
    162 	if (argc)
    163 		usage();
    164 
    165 	settime();
    166 	if (doall) {
    167 		while ((pw = getpwent()) != NULL) {
    168 			(void)setegid(pw->pw_gid);
    169 			(void)seteuid(pw->pw_uid);
    170 			if (!chdir(pw->pw_dir))
    171 				cal();
    172 			(void)seteuid(0);
    173 		}
    174 	} else if ((caldir = getenv("CALENDAR_DIR")) != NULL) {
    175 		if(!chdir(caldir))
    176 			cal();
    177 	} else {
    178 		if (((pw = getpwuid(geteuid())) != NULL) && !chdir(pw->pw_dir))
    179 			cal();
    180 	}
    181 	exit(0);
    182 }
    183 
    184 static void
    185 cal(void)
    186 {
    187 	int printing = 0;
    188 	FILE *fp;
    189 	char *line;
    190 
    191 	if ((fp = opencal()) == NULL)
    192 		return;
    193 	while ((line = fparseln(stdin, NULL, NULL, NULL, FPARSELN_UNESCCOMM))
    194 	    != NULL) {
    195 		if (line[0] == '\0')
    196 			continue;
    197 		if (line[0] != '\t')
    198 			printing = isnow(line) ? 1 : 0;
    199 		if (printing)
    200 			(void)fprintf(fp, "%s\n", line);
    201 		free(line);
    202 
    203 	}
    204 	closecal(fp);
    205 }
    206 
    207 
    208 static void
    209 settime(void)
    210 {
    211 	time_t now;
    212 
    213 	(void)time(&now);
    214 	tp = localtime(&now);
    215 	if (datestr) {
    216 		getmmdd(tp, datestr);
    217 	}
    218 	if (isleap(tp->tm_year + TM_YEAR_BASE)) {
    219 		yrdays = DAYSPERLYEAR;
    220 		cumdays = daytab[1];
    221 	} else {
    222 		yrdays = DAYSPERNYEAR;
    223 		cumdays = daytab[0];
    224 	}
    225 	/* Friday displays Monday's events */
    226 	offset = tp->tm_wday == 5 ? lookahead + weekend : lookahead;
    227 	header[5].iov_base = dayname;
    228 	header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
    229 }
    230 
    231 /*
    232  * Possible date formats include any combination of:
    233  *	3-charmonth			(January, Jan, Jan)
    234  *	3-charweekday			(Friday, Monday, mon.)
    235  *	numeric month or day		(1, 2, 04)
    236  *
    237  * Any character may separate them, or they may not be separated.  Any line,
    238  * following a line that is matched, that starts with "whitespace", is shown
    239  * along with the matched line.
    240  */
    241 static int
    242 isnow(endp)
    243 	char *endp;
    244 {
    245 	int day, flags, month, v1, v2;
    246 
    247 #define	F_ISMONTH	0x01
    248 #define	F_ISDAY		0x02
    249 #define F_WILDMONTH	0x04
    250 #define F_WILDDAY	0x08
    251 
    252 	flags = 0;
    253 
    254 	/* didn't recognize anything, skip it */
    255 	if (!(v1 = getfield(endp, &endp, &flags)))
    256 		return (0);
    257 	if (flags & F_ISDAY || v1 > 12) {
    258 		/* found a day */
    259 		day = v1;
    260 		v2 = getfield(endp, &endp, &flags);
    261 		month = v2;
    262 	} else if (flags & F_ISMONTH) {
    263 		month = v1;
    264 		/* if no recognizable day, assume the first */
    265 		if (!(day = getfield(endp, &endp, &flags)))
    266 			day = 1;
    267 	} else {
    268 		v2 = getfield(endp, &endp, &flags);
    269 		if (flags & F_ISMONTH) {
    270 			day = v1;
    271 			month = v2;
    272 		} else {
    273 			/* F_ISDAY set, v2 > 12, or no way to tell */
    274 			month = v1;
    275 			/* if no recognizable day, assume the first */
    276 			day = v2 ? v2 : 1;
    277 		}
    278 	}
    279 
    280 	if ((flags & F_WILDMONTH) && (flags & F_WILDDAY))
    281 		return (1);
    282 
    283 	if ((flags & F_WILDMONTH) && (flags & F_ISDAY) && (day == tp->tm_mday))
    284 		return (1);
    285 
    286 	if (((flags & F_ISMONTH) && (flags & F_WILDDAY)) && (month == tp->tm_mon + 1))
    287 		return (1);
    288 
    289 	if (flags & F_ISDAY)
    290 		day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
    291 	day = cumdays[month] + day;
    292 
    293 	/* if today or today + offset days */
    294 	if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
    295 		return (1);
    296 	/* if number of days left in this year + days to event in next year */
    297 	if (yrdays - tp->tm_yday + day <= offset)
    298 		return (1);
    299 	return (0);
    300 }
    301 
    302 static int
    303 getfield(p, endp, flags)
    304 	char *p, **endp;
    305 	int *flags;
    306 {
    307 	int val;
    308 	char *start, savech;
    309 
    310 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
    311     !isalpha((unsigned char)*p) && *p != '*')
    312 
    313 	for (; FLDCHAR(*p); ++p)
    314 		continue;
    315 	if (*p == '*') {			/* `*' is current month */
    316 		if (!(*flags & F_ISMONTH)) {
    317 			*flags |= F_ISMONTH|F_WILDMONTH;
    318 			*endp = p+1;
    319 			return (tp->tm_mon + 1);
    320 		} else {
    321 			*flags |= F_ISDAY|F_WILDDAY;
    322 			*endp = p+1;
    323 			return (1);
    324 		}
    325 	}
    326 	if (isdigit((unsigned char)*p)) {
    327 		val = strtol(p, &p, 10);	/* if 0, it's failure */
    328 		for (; FLDCHAR(*p); ++p)
    329 			continue;
    330 		*endp = p;
    331 		return (val);
    332 	}
    333 	for (start = p; *p != '\0' && isalpha((unsigned char)*++p);)
    334 		continue;
    335 	savech = *p;
    336 	*p = '\0';
    337 	if ((val = getmonth(start)) != 0) {
    338 		*flags |= F_ISMONTH;
    339 	} else if ((val = getday(start)) != 0) {
    340 		*flags |= F_ISDAY;
    341 	} else {
    342 		*p = savech;
    343 		return (0);
    344 	}
    345 	for (*p = savech; FLDCHAR(*p); ++p)
    346 		continue;
    347 	*endp = p;
    348 	return (val);
    349 }
    350 
    351 static FILE *
    352 opencal(void)
    353 {
    354 	int fd, pdes[2];
    355 	char **name;
    356 
    357 	/* open up calendar file as stdin */
    358 	if (fname == NULL) {
    359 		for (name = defaultnames; *name != NULL; name++) {
    360 			if (!freopen(*name, "rf", stdin))
    361 				continue;
    362 			else
    363 				break;
    364 		}
    365 		if (*name == NULL) {
    366 			if (doall)
    367 				return (NULL);
    368 			err(1, "Cannot open calendar file");
    369 		}
    370 	} else if (!freopen(fname, "rf", stdin)) {
    371 		if (doall)
    372 			return (NULL);
    373 		err(1, "Cannot open `%s'", fname);
    374 	}
    375 
    376 	if (pipe(pdes) < 0) {
    377 		warn("Cannot open pipe");
    378 		return (NULL);
    379 	}
    380 
    381 	switch (fork()) {
    382 	case -1:			/* error */
    383 		(void)close(pdes[0]);
    384 		(void)close(pdes[1]);
    385 		return (NULL);
    386 	case 0:
    387 		/* child -- stdin already setup, set stdout to pipe input */
    388 		if (pdes[1] != STDOUT_FILENO) {
    389 			(void)dup2(pdes[1], STDOUT_FILENO);
    390 			(void)close(pdes[1]);
    391 		}
    392 		(void)close(pdes[0]);
    393 		/* tell CPP to only open regular files */
    394 		if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1))
    395 			err(1, "Cannot restrict cpp");
    396 		cpp_restricted = 1;
    397 
    398 		(void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
    399 		    "-I" _PATH_CALENDARS, NULL);
    400 		err(1, "Cannot exec `%s'", _PATH_CPP);
    401 		/*NOTREACHED*/
    402 	}
    403 
    404 	/* parent -- set stdin to pipe output */
    405 	(void)dup2(pdes[0], STDIN_FILENO);
    406 	(void)close(pdes[0]);
    407 	(void)close(pdes[1]);
    408 
    409 	/* not reading all calendar files, just set output to stdout */
    410 	if (!doall)
    411 		return (stdout);
    412 
    413 	/* set output to a temporary file, so if no output don't send mail */
    414 	(void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
    415 	if ((fd = mkstemp(path)) < 0) {
    416 		warn("Cannot create temporary file");
    417 		return (NULL);
    418 	}
    419 	return (fdopen(fd, "w+"));
    420 }
    421 
    422 static void
    423 closecal(fp)
    424 	FILE *fp;
    425 {
    426 	struct stat sbuf;
    427 	int nread, pdes[2], status;
    428 	char buf[1024];
    429 
    430 	if (!doall)
    431 		return;
    432 
    433 	(void)rewind(fp);
    434 	if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
    435 		goto done;
    436 	if (pipe(pdes) < 0)
    437 		goto done;
    438 	switch (fork()) {
    439 	case -1:			/* error */
    440 		(void)close(pdes[0]);
    441 		(void)close(pdes[1]);
    442 		goto done;
    443 	case 0:
    444 		/* child -- set stdin to pipe output */
    445 		if (pdes[0] != STDIN_FILENO) {
    446 			(void)dup2(pdes[0], STDIN_FILENO);
    447 			(void)close(pdes[0]);
    448 		}
    449 		(void)close(pdes[1]);
    450 		(void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
    451 		    "\"Reminder Service\"", "-f", "root", NULL);
    452 		err(1, "Cannot exec `%s'", _PATH_SENDMAIL);
    453 		/*NOTREACHED*/
    454 	}
    455 	/* parent -- write to pipe input */
    456 	(void)close(pdes[0]);
    457 
    458 	header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
    459 	header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
    460 	writev(pdes[1], header, 7);
    461 	while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
    462 		(void)write(pdes[1], buf, nread);
    463 	(void)close(pdes[1]);
    464 
    465 done:	(void)fclose(fp);
    466 	(void)unlink(path);
    467 	while (wait(&status) >= 0)
    468 		continue;
    469 }
    470 
    471 static int
    472 getmonth(s)
    473 	char *s;
    474 {
    475 	char **p;
    476 
    477 	for (p = months; *p; ++p)
    478 		if (!strncasecmp(s, *p, 3))
    479 			return ((p - months) + 1);
    480 	return (0);
    481 }
    482 
    483 static int
    484 getday(s)
    485 	char *s;
    486 {
    487 	char **p;
    488 
    489 	for (p = days; *p; ++p)
    490 		if (!strncasecmp(s, *p, 3))
    491 			return ((p - days) + 1);
    492 	return (0);
    493 }
    494 
    495 static void
    496 atodays(int ch, char *optarg, unsigned short *days)
    497 {
    498 	int u;
    499 
    500 	u = atoi(optarg);
    501 	if ((u < 0) || (u > 366)) {
    502 		warnx("-%c %d out of range 0-366, ignored.", ch, u);
    503 	} else {
    504 		*days = u;
    505 	}
    506 }
    507 
    508 #define todigit(x) ((x) - '0')
    509 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
    510 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
    511 
    512 static void
    513 getmmdd(struct tm *tp, char *ds)
    514 {
    515 	int ok = FALSE;
    516 	struct tm ttm;
    517 
    518 	ttm = *tp;
    519 	ttm.tm_isdst = -1;
    520 
    521 	if (ISDIG2(ds)) {
    522 		ttm.tm_mon = ATOI2(ds) - 1;
    523 		ds += 2;
    524 	}
    525 
    526 	if (ISDIG2(ds)) {
    527 		ttm.tm_mday = ATOI2(ds);
    528 		ds += 2;
    529 
    530 		ok = TRUE;
    531 	}
    532 
    533 	if (ok) {
    534 		if (ISDIG2(ds) && ISDIG2(ds + 2)) {
    535 			ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
    536 			ds += 2;
    537 			ttm.tm_year += ATOI2(ds);
    538 		} else if (ISDIG2(ds)) {
    539 			ttm.tm_year = ATOI2(ds);
    540 			if (ttm.tm_year < 69)
    541 				ttm.tm_year += 2000 - TM_YEAR_BASE;
    542 			else
    543 				ttm.tm_year += 1900 - TM_YEAR_BASE;
    544 		}
    545 	}
    546 
    547 	if (ok && (mktime(&ttm) < 0)) {
    548 		ok = FALSE;
    549 	}
    550 
    551 	if (ok) {
    552 		*tp = ttm;
    553 	} else {
    554 		warnx("Can't convert `%s' to date, ignored.", ds);
    555 		usage();
    556 	}
    557 }
    558 
    559 static void
    560 usage(void)
    561 {
    562 	(void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
    563 	    " [-f fname] [-l days] [-w days]\n", getprogname());
    564 	exit(1);
    565 }
    566