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