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