xref: /freebsd/usr.bin/calendar/calendar.c (revision afe61c15161c324a7af299a9b8457aba5afc92db)
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static char copyright[] =
36 "@(#) Copyright (c) 1989, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 static char sccsid[] = "@(#)calendar.c	8.3 (Berkeley) 3/25/94";
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #include <sys/stat.h>
47 #include <sys/uio.h>
48 #include <sys/wait.h>
49 
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <pwd.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <tzfile.h>
59 #include <unistd.h>
60 
61 #include "pathnames.h"
62 
63 struct passwd *pw;
64 int doall;
65 
66 void	 cal __P((void));
67 void	 closecal __P((FILE *));
68 int	 getday __P((char *));
69 int	 getfield __P((char *, char **, int *));
70 int	 getmonth __P((char *));
71 int	 isnow __P((char *));
72 FILE	*opencal __P((void));
73 void	 settime __P((void));
74 void	 usage __P((void));
75 
76 int
77 main(argc, argv)
78 	int argc;
79 	char *argv[];
80 {
81 	extern int optind;
82 	int ch;
83 
84 	while ((ch = getopt(argc, argv, "-a")) != EOF)
85 		switch (ch) {
86 		case '-':		/* backward contemptible */
87 		case 'a':
88 			if (getuid()) {
89 				errno = EPERM;
90 				err(1, NULL);
91 			}
92 			doall = 1;
93 			break;
94 		case '?':
95 		default:
96 			usage();
97 		}
98 	argc -= optind;
99 	argv += optind;
100 
101 	if (argc)
102 		usage();
103 
104 	settime();
105 	if (doall)
106 		while ((pw = getpwent()) != NULL) {
107 			(void)setegid(pw->pw_gid);
108 			(void)seteuid(pw->pw_uid);
109 			if (!chdir(pw->pw_dir))
110 				cal();
111 			(void)seteuid(0);
112 		}
113 	else
114 		cal();
115 	exit(0);
116 }
117 
118 void
119 cal()
120 {
121 	register int printing;
122 	register char *p;
123 	FILE *fp;
124 	int ch;
125 	char buf[2048 + 1];
126 
127 	if ((fp = opencal()) == NULL)
128 		return;
129 	for (printing = 0; fgets(buf, sizeof(buf), stdin) != NULL;) {
130 		if ((p = strchr(buf, '\n')) != NULL)
131 			*p = '\0';
132 		else
133 			while ((ch = getchar()) != '\n' && ch != EOF);
134 		if (buf[0] == '\0')
135 			continue;
136 		if (buf[0] != '\t')
137 			printing = isnow(buf) ? 1 : 0;
138 		if (printing)
139 			(void)fprintf(fp, "%s\n", buf);
140 	}
141 	closecal(fp);
142 }
143 
144 struct iovec header[] = {
145 	"From: ", 6,
146 	NULL, 0,
147 	" (Reminder Service)\nTo: ", 24,
148 	NULL, 0,
149 	"\nSubject: ", 10,
150 	NULL, 0,
151 	"'s Calendar\nPrecedence: bulk\n\n",  30,
152 };
153 
154 /* 1-based month, 0-based days, cumulative */
155 int daytab[][14] = {
156 	0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364,
157 	0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365,
158 };
159 struct tm *tp;
160 int *cumdays, offset, yrdays;
161 char dayname[10];
162 
163 void
164 settime()
165 {
166 	time_t now;
167 
168 	(void)time(&now);
169 	tp = localtime(&now);
170 	if (isleap(tp->tm_year + 1900)) {
171 		yrdays = DAYSPERLYEAR;
172 		cumdays = daytab[1];
173 	} else {
174 		yrdays = DAYSPERNYEAR;
175 		cumdays = daytab[0];
176 	}
177 	/* Friday displays Monday's events */
178 	offset = tp->tm_wday == 5 ? 3 : 1;
179 	header[5].iov_base = dayname;
180 	header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
181 }
182 
183 /*
184  * Possible date formats include any combination of:
185  *	3-charmonth			(January, Jan, Jan)
186  *	3-charweekday			(Friday, Monday, mon.)
187  *	numeric month or day		(1, 2, 04)
188  *
189  * Any character may separate them, or they may not be separated.  Any line,
190  * following a line that is matched, that starts with "whitespace", is shown
191  * along with the matched line.
192  */
193 int
194 isnow(endp)
195 	char *endp;
196 {
197 	int day, flags, month, v1, v2;
198 
199 #define	F_ISMONTH	0x01
200 #define	F_ISDAY		0x02
201 	flags = 0;
202 	/* didn't recognize anything, skip it */
203 	if (!(v1 = getfield(endp, &endp, &flags)))
204 		return (0);
205 	if (flags & F_ISDAY || v1 > 12) {
206 		/* found a day */
207 		day = v1;
208 		/* if no recognizable month, assume just a day alone */
209 		if (!(month = getfield(endp, &endp, &flags)))
210 			month = tp->tm_mon + 1;
211 	} else if (flags & F_ISMONTH) {
212 		month = v1;
213 		/* if no recognizable day, assume the first */
214 		if (!(day = getfield(endp, &endp, &flags)))
215 			day = 1;
216 	} else {
217 		v2 = getfield(endp, &endp, &flags);
218 		if (flags & F_ISMONTH) {
219 			day = v1;
220 			month = v2;
221 		} else {
222 			/* F_ISDAY set, v2 > 12, or no way to tell */
223 			month = v1;
224 			/* if no recognizable day, assume the first */
225 			day = v2 ? v2 : 1;
226 		}
227 	}
228 	if (flags & F_ISDAY)
229 		day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
230 	day = cumdays[month] + day;
231 
232 	/* if today or today + offset days */
233 	if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
234 		return (1);
235 	/* if number of days left in this year + days to event in next year */
236 	if (yrdays - tp->tm_yday + day <= offset)
237 		return (1);
238 	return (0);
239 }
240 
241 int
242 getfield(p, endp, flags)
243 	char *p, **endp;
244 	int *flags;
245 {
246 	int val;
247 	char *start, savech;
248 
249 	for (; !isdigit(*p) && !isalpha(*p) && *p != '*'; ++p);
250 	if (*p == '*') {			/* `*' is current month */
251 		*flags |= F_ISMONTH;
252 		*endp = p+1;
253 		return (tp->tm_mon + 1);
254 	}
255 	if (isdigit(*p)) {
256 		val = strtol(p, &p, 10);	/* if 0, it's failure */
257 		for (; !isdigit(*p) && !isalpha(*p) && *p != '*'; ++p);
258 		*endp = p;
259 		return (val);
260 	}
261 	for (start = p; isalpha(*++p););
262 	savech = *p;
263 	*p = '\0';
264 	if ((val = getmonth(start)) != 0)
265 		*flags |= F_ISMONTH;
266 	else if ((val = getday(start)) != 0)
267 		*flags |= F_ISDAY;
268 	else {
269 		*p = savech;
270 		return (0);
271 	}
272 	for (*p = savech; !isdigit(*p) && !isalpha(*p) && *p != '*'; ++p);
273 	*endp = p;
274 	return (val);
275 }
276 
277 char path[MAXPATHLEN + 1];
278 
279 FILE *
280 opencal()
281 {
282 	int fd, pdes[2];
283 
284 	/* open up calendar file as stdin */
285 	if (!freopen("calendar", "r", stdin)) {
286 		if (doall)
287 			return (NULL);
288 		errx(1, "no calendar file.");
289 	}
290 	if (pipe(pdes) < 0)
291 		return (NULL);
292 	switch (vfork()) {
293 	case -1:			/* error */
294 		(void)close(pdes[0]);
295 		(void)close(pdes[1]);
296 		return (NULL);
297 	case 0:
298 		/* child -- stdin already setup, set stdout to pipe input */
299 		if (pdes[1] != STDOUT_FILENO) {
300 			(void)dup2(pdes[1], STDOUT_FILENO);
301 			(void)close(pdes[1]);
302 		}
303 		(void)close(pdes[0]);
304 		execl(_PATH_CPP, "cpp", "-I.", _PATH_INCLUDE, NULL);
305 		(void)fprintf(stderr,
306 		    "calendar: execl: %s: %s.\n", _PATH_CPP, strerror(errno));
307 		_exit(1);
308 	}
309 	/* parent -- set stdin to pipe output */
310 	(void)dup2(pdes[0], STDIN_FILENO);
311 	(void)close(pdes[0]);
312 	(void)close(pdes[1]);
313 
314 	/* not reading all calendar files, just set output to stdout */
315 	if (!doall)
316 		return (stdout);
317 
318 	/* set output to a temporary file, so if no output don't send mail */
319 	(void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
320 	if ((fd = mkstemp(path)) < 0)
321 		return (NULL);
322 	return (fdopen(fd, "w+"));
323 }
324 
325 void
326 closecal(fp)
327 	FILE *fp;
328 {
329 	struct stat sbuf;
330 	int nread, pdes[2], status;
331 	char buf[1024];
332 
333 	if (!doall)
334 		return;
335 
336 	(void)rewind(fp);
337 	if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
338 		goto done;
339 	if (pipe(pdes) < 0)
340 		goto done;
341 	switch (vfork()) {
342 	case -1:			/* error */
343 		(void)close(pdes[0]);
344 		(void)close(pdes[1]);
345 		goto done;
346 	case 0:
347 		/* child -- set stdin to pipe output */
348 		if (pdes[0] != STDIN_FILENO) {
349 			(void)dup2(pdes[0], STDIN_FILENO);
350 			(void)close(pdes[0]);
351 		}
352 		(void)close(pdes[1]);
353 		execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
354 		    "\"Reminder Service\"", "-f", "root", NULL);
355 		(void)fprintf(stderr,
356 		    "calendar: %s: %s.\n", _PATH_SENDMAIL, strerror(errno));
357 		_exit(1);
358 	}
359 	/* parent -- write to pipe input */
360 	(void)close(pdes[0]);
361 
362 	header[1].iov_base = header[3].iov_base = pw->pw_name;
363 	header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
364 	writev(pdes[1], header, 7);
365 	while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
366 		(void)write(pdes[1], buf, nread);
367 	(void)close(pdes[1]);
368 done:	(void)fclose(fp);
369 	(void)unlink(path);
370 	while (wait(&status) >= 0);
371 }
372 
373 static char *months[] = {
374 	"jan", "feb", "mar", "apr", "may", "jun",
375 	"jul", "aug", "sep", "oct", "nov", "dec", NULL,
376 };
377 
378 int
379 getmonth(s)
380 	register char *s;
381 {
382 	register char **p;
383 
384 	for (p = months; *p; ++p)
385 		if (!strncasecmp(s, *p, 3))
386 			return ((p - months) + 1);
387 	return (0);
388 }
389 
390 static char *days[] = {
391 	"sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
392 };
393 
394 int
395 getday(s)
396 	register char *s;
397 {
398 	register char **p;
399 
400 	for (p = days; *p; ++p)
401 		if (!strncasecmp(s, *p, 3))
402 			return ((p - days) + 1);
403 	return (0);
404 }
405 
406 void
407 usage()
408 {
409 	(void)fprintf(stderr, "usage: calendar [-a]\n");
410 	exit(1);
411 }
412