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