io.c revision 175002
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
35static const char copyright[] =
36"@(#) Copyright (c) 1989, 1993\n\
37	The Regents of the University of California.  All rights reserved.\n";
38#endif
39
40#if 0
41#ifndef lint
42static char sccsid[] = "@(#)calendar.c  8.3 (Berkeley) 3/25/94";
43#endif
44#endif
45
46#include <sys/cdefs.h>
47__FBSDID("$FreeBSD: head/usr.bin/calendar/io.c 175002 2007-12-30 22:02:50Z grog $");
48
49#include <sys/types.h>
50#include <sys/param.h>
51#include <sys/stat.h>
52#include <sys/time.h>
53#include <sys/uio.h>
54#include <sys/wait.h>
55#include <ctype.h>
56#include <err.h>
57#include <errno.h>
58#include <langinfo.h>
59#include <locale.h>
60#include <pwd.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
65
66#include "pathnames.h"
67#include "calendar.h"
68
69
70const char *calendarFile = "calendar";  /* default calendar file */
71const char *calendarHomes[] = { ".calendar", _PATH_INCLUDE }; /* HOME */
72const char *calendarNoMail = "nomail";  /* don't sent mail if this file exist */
73
74struct fixs neaster, npaskha;
75
76struct iovec header[] = {
77	{"From: ", 6},
78	{NULL, 0},
79	{" (Reminder Service)\nTo: ", 24},
80	{NULL, 0},
81	{"\nSubject: ", 10},
82	{NULL, 0},
83	{"'s Calendar\nPrecedence: bulk\n\n",  30},
84};
85
86
87void
88cal(void)
89{
90	int printing;
91	char *p;
92	FILE *fp;
93	int ch, l;
94	int month;
95	int day;
96	int var;
97	static int d_first = -1;
98	char buf[2048 + 1];
99	struct event *events = NULL;
100
101	if ((fp = opencal()) == NULL)
102		return;
103	for (printing = 0; fgets(buf, sizeof(buf), stdin) != NULL;) {
104		if ((p = strchr(buf, '\n')) != NULL)
105			*p = '\0';
106		else
107			while ((ch = getchar()) != '\n' && ch != EOF);
108		for (l = strlen(buf);
109		     l > 0 && isspace((unsigned char)buf[l - 1]);
110		     l--)
111			;
112		buf[l] = '\0';
113		if (buf[0] == '\0')
114			continue;
115		if (strncmp(buf, "LANG=", 5) == 0) {
116			(void) setlocale(LC_ALL, buf + 5);
117			d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
118			setnnames();
119			continue;
120		}
121		if (strncasecmp(buf, "Easter=", 7) == 0 && buf[7]) {
122			if (neaster.name != NULL)
123				free(neaster.name);
124			if ((neaster.name = strdup(buf + 7)) == NULL)
125				errx(1, "cannot allocate memory");
126			neaster.len = strlen(buf + 7);
127			continue;
128		}
129		if (strncasecmp(buf, "Paskha=", 7) == 0 && buf[7]) {
130			if (npaskha.name != NULL)
131				free(npaskha.name);
132			if ((npaskha.name = strdup(buf + 7)) == NULL)
133				errx(1, "cannot allocate memory");
134			npaskha.len = strlen(buf + 7);
135			continue;
136		}
137		if (buf[0] != '\t') {
138			printing = isnow(buf, &month, &day, &var) ? 1 : 0;
139			if ((p = strchr(buf, '\t')) == NULL)
140				continue;
141			if (p > buf && p[-1] == '*')
142				var = 1;
143			if (printing) {
144				struct tm tm;
145				char dbuf[80];
146
147				if (d_first < 0)
148					d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
149				tm.tm_sec = 0;  /* unused */
150				tm.tm_min = 0;  /* unused */
151				tm.tm_hour = 0; /* unused */
152				tm.tm_wday = 0; /* unused */
153				tm.tm_mon = month - 1;
154				tm.tm_mday = day;
155				tm.tm_year = tp->tm_year; /* unused */
156				(void)strftime(dbuf, sizeof(dbuf),
157					       d_first ? "%e %b" : "%b %e",
158					       &tm);
159				events = event_add(events, month, day, dbuf, var, p);
160			}
161		}
162		else if (printing)
163			event_continue(events, buf);
164	}
165
166	event_print_all(fp, events);
167	closecal(fp);
168}
169
170/*
171 * Functions to handle buffered calendar events.
172 */
173struct event *
174event_add(struct event *events, int month, int day, char *date, int var, char *txt)
175{
176	struct event *e;
177
178	e = (struct event *)calloc(1, sizeof(struct event));
179	if (e == NULL)
180		errx(1, "event_add: cannot allocate memory");
181	e->month = month;
182	e->day = day;
183	e->var = var;
184	e->date = strdup(date);
185	if (e->date == NULL)
186		errx(1, "event_add: cannot allocate memory");
187	e->text = strdup(txt);
188	if (e->text == NULL)
189		errx(1, "event_add: cannot allocate memory");
190	e->next = events;
191
192	return e;
193}
194
195void
196event_continue(struct event *e, char *txt)
197{
198	char *text;
199
200	text = strdup(e->text);
201	if (text == NULL)
202		errx(1, "event_continue: cannot allocate memory");
203
204	free(e->text);
205	e->text = (char *)malloc(strlen(text) + strlen(txt) + 3);
206	if (e->text == NULL)
207		errx(1, "event_continue: cannot allocate memory");
208	strcpy(e->text, text);
209	strcat(e->text, "\n");
210	strcat(e->text, txt);
211	free(text);
212
213	return;
214}
215
216void
217event_print_all(FILE *fp, struct event *events)
218{
219	struct event *e, *e_next;
220	int daycount = f_dayAfter + f_dayBefore;
221	int daycounter;
222	int day, month;
223
224	for (daycounter = 0; daycounter <= daycount; daycounter++) {
225		day = tp->tm_yday - f_dayBefore + daycounter;
226		if (day < 0) day += yrdays;
227		if (day >= yrdays) day -= yrdays;
228
229		month = 1;
230		while (month <= 12) {
231			if (day <= cumdays[month])
232				break;
233			month++;
234		}
235		month--;
236		day -= cumdays[month];
237
238#ifdef DEBUG
239		fprintf(stderr,"event_print_allmonth: %d, day: %d\n",month,day);
240#endif
241
242		for (e = events; e != NULL; e = e_next ) {
243			e_next = e->next;
244
245			if (month != e->month || day != e->day)
246				continue;
247
248			(void)fprintf(fp, "%s%c%s\n", e->date,
249			    e->var ? '*' : ' ', e->text);
250		}
251	}
252}
253
254int
255getfield(char *p, char **endp, int *flags)
256{
257	int val, var;
258	char *start, savech;
259
260	for (; !isdigit((unsigned char)*p) && !isalpha((unsigned char)*p)
261               && *p != '*'; ++p);
262	if (*p == '*') {			/* `*' is current month */
263		*flags |= F_ISMONTH;
264		*endp = p+1;
265		return (tp->tm_mon + 1);
266	}
267	if (isdigit((unsigned char)*p)) {
268		val = strtol(p, &p, 10);	/* if 0, it's failure */
269		for (; !isdigit((unsigned char)*p)
270                       && !isalpha((unsigned char)*p) && *p != '*'; ++p);
271		*endp = p;
272		return (val);
273	}
274	for (start = p; isalpha((unsigned char)*++p););
275
276	/* Sunday-1 */
277	if (*p == '+' || *p == '-')
278	    for(; isdigit((unsigned char)*++p););
279
280	savech = *p;
281	*p = '\0';
282
283	/* Month */
284	if ((val = getmonth(start)) != 0)
285		*flags |= F_ISMONTH;
286
287	/* Day */
288	else if ((val = getday(start)) != 0) {
289	    *flags |= F_ISDAY;
290
291	    /* variable weekday */
292	    if ((var = getdayvar(start)) != 0) {
293		if (var <=5 && var >= -4)
294		    val += var * 10;
295#ifdef DEBUG
296		printf("var: %d\n", var);
297#endif
298	    }
299	}
300
301	/* Easter */
302	else if ((val = geteaster(start, tp->tm_year + 1900)) != 0)
303	    *flags |= F_EASTER;
304
305	/* Paskha */
306	else if ((val = getpaskha(start, tp->tm_year + 1900)) != 0)
307	    *flags |= F_EASTER;
308
309	/* undefined rest */
310	else {
311		*p = savech;
312		return (0);
313	}
314	for (*p = savech; !isdigit((unsigned char)*p)
315               && !isalpha((unsigned char)*p) && *p != '*'; ++p);
316	*endp = p;
317	return (val);
318}
319
320char path[MAXPATHLEN];
321
322FILE *
323opencal(void)
324{
325	uid_t uid;
326	size_t i;
327	int fd, found, pdes[2];
328	struct stat sbuf;
329
330	/* open up calendar file as stdin */
331	if (!freopen(calendarFile, "r", stdin)) {
332		if (doall) {
333		    if (chdir(calendarHomes[0]) != 0)
334			return (NULL);
335		    if (stat(calendarNoMail, &sbuf) == 0)
336		        return (NULL);
337		    if (!freopen(calendarFile, "r", stdin))
338		        return (NULL);
339		} else {
340			char *home = getenv("HOME");
341			if (home == NULL || *home == '\0')
342				errx(1, "cannot get home directory");
343			chdir(home);
344			for (found = i = 0; i < sizeof(calendarHomes) /
345			    sizeof(calendarHomes[0]); i++)
346			    if (chdir(calendarHomes[i]) == 0 &&
347			          freopen(calendarFile, "r", stdin)) {
348				    found = 1;
349				    break;
350			    }
351			if (!found)
352			    errx(1, "can't open calendar file \"%s\": %s (%d)",
353                                 calendarFile, strerror (errno), errno);
354		}
355	}
356	if (pipe(pdes) < 0)
357		return (NULL);
358	switch (fork()) {
359	case -1:			/* error */
360		(void)close(pdes[0]);
361		(void)close(pdes[1]);
362		return (NULL);
363	case 0:
364		/* child -- stdin already setup, set stdout to pipe input */
365		if (pdes[1] != STDOUT_FILENO) {
366			(void)dup2(pdes[1], STDOUT_FILENO);
367			(void)close(pdes[1]);
368		}
369		(void)close(pdes[0]);
370		uid = geteuid();
371		if (setuid(getuid()) < 0) {
372			warnx("first setuid failed");
373			_exit(1);
374		};
375		if (setgid(getegid()) < 0) {
376			warnx("setgid failed");
377			_exit(1);
378		}
379		if (setuid(uid) < 0) {
380			warnx("setuid failed");
381			_exit(1);
382		}
383		execl(_PATH_CPP, "cpp", "-P",
384		    "-traditional", "-nostdinc",	/* GCC specific opts */
385		    "-I.", "-I", _PATH_INCLUDE, (char *)NULL);
386		warn(_PATH_CPP);
387		_exit(1);
388	}
389	/* parent -- set stdin to pipe output */
390	(void)dup2(pdes[0], STDIN_FILENO);
391	(void)close(pdes[0]);
392	(void)close(pdes[1]);
393
394	/* not reading all calendar files, just set output to stdout */
395	if (!doall)
396		return (stdout);
397
398	/* set output to a temporary file, so if no output don't send mail */
399	(void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
400	if ((fd = mkstemp(path)) < 0)
401		return (NULL);
402	return (fdopen(fd, "w+"));
403}
404
405void
406closecal(FILE *fp)
407{
408	uid_t uid;
409	struct stat sbuf;
410	int nread, pdes[2], status;
411	char buf[1024];
412
413	if (!doall)
414		return;
415
416	(void)rewind(fp);
417	if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
418		goto done;
419	if (pipe(pdes) < 0)
420		goto done;
421	switch (fork()) {
422	case -1:			/* error */
423		(void)close(pdes[0]);
424		(void)close(pdes[1]);
425		goto done;
426	case 0:
427		/* child -- set stdin to pipe output */
428		if (pdes[0] != STDIN_FILENO) {
429			(void)dup2(pdes[0], STDIN_FILENO);
430			(void)close(pdes[0]);
431		}
432		(void)close(pdes[1]);
433		uid = geteuid();
434		if (setuid(getuid()) < 0) {
435			warnx("setuid failed");
436			_exit(1);
437		};
438		if (setgid(getegid()) < 0) {
439			warnx("setgid failed");
440			_exit(1);
441		}
442		if (setuid(uid) < 0) {
443			warnx("setuid failed");
444			_exit(1);
445		}
446		execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
447		    "\"Reminder Service\"", (char *)NULL);
448		warn(_PATH_SENDMAIL);
449		_exit(1);
450	}
451	/* parent -- write to pipe input */
452	(void)close(pdes[0]);
453
454	header[1].iov_base = header[3].iov_base = pw->pw_name;
455	header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
456	writev(pdes[1], header, 7);
457	while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
458		(void)write(pdes[1], buf, nread);
459	(void)close(pdes[1]);
460done:	(void)fclose(fp);
461	(void)unlink(path);
462	while (wait(&status) >= 0);
463}
464