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