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