xref: /freebsd/usr.bin/calendar/io.c (revision aebc96831f152a9da5f2c919103d571e80d3fade)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1989, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif
37 
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)calendar.c  8.3 (Berkeley) 3/25/94";
41 #endif
42 #endif
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include <sys/param.h>
48 #include <sys/stat.h>
49 #include <sys/wait.h>
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <locale.h>
54 #include <pwd.h>
55 #include <stdbool.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <stringlist.h>
60 #include <time.h>
61 #include <unistd.h>
62 
63 #include "pathnames.h"
64 #include "calendar.h"
65 
66 enum {
67 	T_OK = 0,
68 	T_ERR,
69 	T_PROCESS,
70 };
71 
72 const char *calendarFile = "calendar";	/* default calendar file */
73 static const char *calendarHomes[] = {".calendar", _PATH_INCLUDE_LOCAL, _PATH_INCLUDE}; /* HOME */
74 static const char *calendarNoMail = "nomail";/* don't sent mail if file exist */
75 
76 static char path[MAXPATHLEN];
77 static const char *cal_home;
78 static const char *cal_dir;
79 static const char *cal_file;
80 static int cal_line;
81 
82 struct fixs neaster, npaskha, ncny, nfullmoon, nnewmoon;
83 struct fixs nmarequinox, nsepequinox, njunsolstice, ndecsolstice;
84 
85 static int cal_parse(FILE *in, FILE *out);
86 
87 static StringList *definitions = NULL;
88 static struct event *events[MAXCOUNT];
89 static char *extradata[MAXCOUNT];
90 
91 static char *
92 trimlr(char **buf)
93 {
94 	char *walk = *buf;
95 	char *sep;
96 	char *last;
97 
98 	while (isspace(*walk))
99 		walk++;
100 	*buf = walk;
101 
102 	sep = walk;
103 	while (*sep != '\0' && !isspace(*sep))
104 		sep++;
105 
106 	if (*sep != '\0') {
107 		last = sep + strlen(sep) - 1;
108 		while (last > walk && isspace(*last))
109 			last--;
110 		*(last+1) = 0;
111 	}
112 
113 	return (sep);
114 }
115 
116 static FILE *
117 cal_fopen(const char *file)
118 {
119 	FILE *fp;
120 	char *home = getenv("HOME");
121 	unsigned int i;
122 	struct stat sb;
123 	static bool warned = false;
124 
125 	if (home == NULL || *home == '\0') {
126 		warnx("Cannot get home directory");
127 		return (NULL);
128 	}
129 
130 	if (chdir(home) != 0) {
131 		warnx("Cannot enter home directory \"%s\"", home);
132 		return (NULL);
133 	}
134 
135 	for (i = 0; i < nitems(calendarHomes); i++) {
136 		if (chdir(calendarHomes[i]) != 0)
137 			continue;
138 
139 		if ((fp = fopen(file, "r")) != NULL) {
140 			cal_home = home;
141 			cal_dir = calendarHomes[i];
142 			cal_file = file;
143 			return (fp);
144 		}
145 	}
146 
147 	warnx("can't open calendar file \"%s\"", file);
148 	if (!warned && stat(_PATH_INCLUDE_LOCAL, &sb) != 0) {
149 		warnx("calendar data files now provided by calendar-data pkg.");
150 		warned = true;
151 	}
152 
153 	return (NULL);
154 }
155 
156 static char*
157 cal_path(void)
158 {
159 	static char buffer[MAXPATHLEN + 10];
160 
161 	if (cal_dir == NULL)
162 		snprintf(buffer, sizeof(buffer), "%s", cal_file);
163 	else if (cal_dir[0] == '/')
164 		snprintf(buffer, sizeof(buffer), "%s/%s", cal_dir, cal_file);
165 	else
166 		snprintf(buffer, sizeof(buffer), "%s/%s/%s", cal_home, cal_dir, cal_file);
167 	return (buffer);
168 }
169 
170 #define	WARN0(format)		   \
171 	warnx(format " in %s line %d", cal_path(), cal_line)
172 #define	WARN1(format, arg1)		   \
173 	warnx(format " in %s line %d", arg1, cal_path(), cal_line)
174 
175 static int
176 token(char *line, FILE *out, int *skip, int *unskip)
177 {
178 	char *walk, *sep, a, c;
179 	const char *this_cal_home;
180 	const char *this_cal_dir;
181 	const char *this_cal_file;
182 	int this_cal_line;
183 
184 	if (strncmp(line, "endif", 5) == 0) {
185 		if (*skip + *unskip == 0) {
186 			WARN0("#endif without prior #ifdef or #ifndef");
187 			return (T_ERR);
188 		}
189 		if (*skip > 0)
190 			--*skip;
191 		else
192 			--*unskip;
193 
194 		return (T_OK);
195 	}
196 
197 	if (strncmp(line, "ifdef", 5) == 0) {
198 		walk = line + 5;
199 		sep = trimlr(&walk);
200 
201 		if (*walk == '\0') {
202 			WARN0("Expecting arguments after #ifdef");
203 			return (T_ERR);
204 		}
205 		if (*sep != '\0') {
206 			WARN1("Expecting a single word after #ifdef "
207 			    "but got \"%s\"", walk);
208 			return (T_ERR);
209 		}
210 
211 		if (*skip != 0 ||
212 		    definitions == NULL || sl_find(definitions, walk) == NULL)
213 			++*skip;
214 		else
215 			++*unskip;
216 
217 		return (T_OK);
218 	}
219 
220 	if (strncmp(line, "ifndef", 6) == 0) {
221 		walk = line + 6;
222 		sep = trimlr(&walk);
223 
224 		if (*walk == '\0') {
225 			WARN0("Expecting arguments after #ifndef");
226 			return (T_ERR);
227 		}
228 		if (*sep != '\0') {
229 			WARN1("Expecting a single word after #ifndef "
230 			    "but got \"%s\"", walk);
231 			return (T_ERR);
232 		}
233 
234 		if (*skip != 0 ||
235 		    (definitions != NULL && sl_find(definitions, walk) != NULL))
236 			++*skip;
237 		else
238 			++*unskip;
239 
240 		return (T_OK);
241 	}
242 
243 	if (strncmp(line, "else", 4) == 0) {
244 		walk = line + 4;
245 		(void)trimlr(&walk);
246 
247 		if (*walk != '\0') {
248 			WARN0("Expecting no arguments after #else");
249 			return (T_ERR);
250 		}
251 		if (*skip + *unskip == 0) {
252 			WARN0("#else without prior #ifdef or #ifndef");
253 			return (T_ERR);
254 		}
255 
256 		if (*skip == 0) {
257 			++*skip;
258 			--*unskip;
259 		} else if (*skip == 1) {
260 			--*skip;
261 			++*unskip;
262 		}
263 
264 		return (T_OK);
265 	}
266 
267 	if (*skip != 0)
268 		return (T_OK);
269 
270 	if (strncmp(line, "include", 7) == 0) {
271 		walk = line + 7;
272 
273 		(void)trimlr(&walk);
274 
275 		if (*walk == '\0') {
276 			WARN0("Expecting arguments after #include");
277 			return (T_ERR);
278 		}
279 
280 		if (*walk != '<' && *walk != '\"') {
281 			WARN0("Excecting '<' or '\"' after #include");
282 			return (T_ERR);
283 		}
284 
285 		a = *walk == '<' ? '>' : '\"';
286 		walk++;
287 		c = walk[strlen(walk) - 1];
288 
289 		if (a != c) {
290 			WARN1("Unterminated include expecting '%c'", a);
291 			return (T_ERR);
292 		}
293 		walk[strlen(walk) - 1] = '\0';
294 
295 		this_cal_home = cal_home;
296 		this_cal_dir = cal_dir;
297 		this_cal_file = cal_file;
298 		this_cal_line = cal_line;
299 		if (cal_parse(cal_fopen(walk), out))
300 			return (T_ERR);
301 		cal_home = this_cal_home;
302 		cal_dir = this_cal_dir;
303 		cal_file = this_cal_file;
304 		cal_line = this_cal_line;
305 
306 		return (T_OK);
307 	}
308 
309 	if (strncmp(line, "define", 6) == 0) {
310 		if (definitions == NULL)
311 			definitions = sl_init();
312 		walk = line + 6;
313 		sep = trimlr(&walk);
314 		*sep = '\0';
315 
316 		if (*walk == '\0') {
317 			WARN0("Expecting arguments after #define");
318 			return (T_ERR);
319 		}
320 
321 		if (sl_find(definitions, walk) == NULL)
322 			sl_add(definitions, strdup(walk));
323 		return (T_OK);
324 	}
325 
326 	if (strncmp(line, "undef", 5) == 0) {
327 		if (definitions != NULL) {
328 			walk = line + 5;
329 			sep = trimlr(&walk);
330 
331 			if (*walk == '\0') {
332 				WARN0("Expecting arguments after #undef");
333 				return (T_ERR);
334 			}
335 			if (*sep != '\0') {
336 				WARN1("Expecting a single word after #undef "
337 				    "but got \"%s\"", walk);
338 				return (T_ERR);
339 			}
340 
341 			walk = sl_find(definitions, walk);
342 			if (walk != NULL)
343 				walk[0] = '\0';
344 		}
345 		return (T_OK);
346 	}
347 
348 	return (T_PROCESS);
349 
350 }
351 
352 #define	REPLACE(string, slen, struct_) \
353 		if (strncasecmp(buf, (string), (slen)) == 0 && buf[(slen)]) { \
354 			if (struct_.name != NULL)			      \
355 				free(struct_.name);			      \
356 			if ((struct_.name = strdup(buf + (slen))) == NULL)    \
357 				errx(1, "cannot allocate memory");	      \
358 			struct_.len = strlen(buf + (slen));		      \
359 			continue;					      \
360 		}
361 static int
362 cal_parse(FILE *in, FILE *out)
363 {
364 	char *line = NULL;
365 	char *buf;
366 	size_t linecap = 0;
367 	ssize_t linelen;
368 	ssize_t l;
369 	static int count = 0;
370 	int i;
371 	int month[MAXCOUNT];
372 	int day[MAXCOUNT];
373 	int year[MAXCOUNT];
374 	int skip = 0;
375 	int unskip = 0;
376 	char *pp, p;
377 	int flags;
378 	char *c, *cc;
379 	bool incomment = false;
380 
381 	if (in == NULL)
382 		return (1);
383 
384 	cal_line = 0;
385 	while ((linelen = getline(&line, &linecap, in)) > 0) {
386 		cal_line++;
387 		buf = line;
388 		if (buf[linelen - 1] == '\n')
389 			buf[--linelen] = '\0';
390 
391 		if (incomment) {
392 			c = strstr(buf, "*/");
393 			if (c) {
394 				c += 2;
395 				linelen -= c - buf;
396 				buf = c;
397 				incomment = false;
398 			} else {
399 				continue;
400 			}
401 		}
402 		if (!incomment) {
403 			do {
404 				c = strstr(buf, "//");
405 				cc = strstr(buf, "/*");
406 				if (c != NULL && (cc == NULL || c - cc < 0)) {
407 					/* single line comment */
408 					*c = '\0';
409 					linelen = c - buf;
410 					break;
411 				} else if (cc != NULL) {
412 					c = strstr(cc + 2, "*/");
413 					if (c != NULL) {
414 						/* multi-line comment ending on same line */
415 						c += 2;
416 						memmove(cc, c, buf + linelen + 1 - c);
417 						linelen -= c - cc;
418 					} else {
419 						/* multi-line comment */
420 						*cc = '\0';
421 						linelen = cc - buf;
422 						incomment = true;
423 						break;
424 					}
425 				}
426 			} while (c != NULL || cc != NULL);
427 		}
428 
429 		for (l = linelen;
430 		     l > 0 && isspace((unsigned char)buf[l - 1]);
431 		     l--)
432 			;
433 		buf[l] = '\0';
434 		if (buf[0] == '\0')
435 			continue;
436 
437 		if (buf == line && *buf == '#') {
438 			switch (token(buf+1, out, &skip, &unskip)) {
439 			case T_ERR:
440 				free(line);
441 				return (1);
442 			case T_OK:
443 				continue;
444 			case T_PROCESS:
445 				break;
446 			default:
447 				break;
448 			}
449 		}
450 
451 		if (skip != 0)
452 			continue;
453 
454 		/*
455 		 * Setting LANG in user's calendar was an old workaround
456 		 * for 'calendar -a' being run with C locale to properly
457 		 * print user's calendars in their native languages.
458 		 * Now that 'calendar -a' does fork with setusercontext(),
459 		 * and does not run iconv(), this variable has little use.
460 		 */
461 		if (strncmp(buf, "LANG=", 5) == 0) {
462 			(void)setlocale(LC_ALL, buf + 5);
463 #ifdef WITH_ICONV
464 			if (!doall)
465 				set_new_encoding();
466 #endif
467 			setnnames();
468 			continue;
469 		}
470 		/* Parse special definitions: Easter, Paskha etc */
471 		REPLACE("Easter=", 7, neaster);
472 		REPLACE("Paskha=", 7, npaskha);
473 		REPLACE("ChineseNewYear=", 15, ncny);
474 		REPLACE("NewMoon=", 8, nnewmoon);
475 		REPLACE("FullMoon=", 9, nfullmoon);
476 		REPLACE("MarEquinox=", 11, nmarequinox);
477 		REPLACE("SepEquinox=", 11, nsepequinox);
478 		REPLACE("JunSolstice=", 12, njunsolstice);
479 		REPLACE("DecSolstice=", 12, ndecsolstice);
480 		if (strncmp(buf, "SEQUENCE=", 9) == 0) {
481 			setnsequences(buf + 9);
482 			continue;
483 		}
484 
485 		/*
486 		 * If the line starts with a tab, the data has to be
487 		 * added to the previous line
488 		 */
489 		if (buf[0] == '\t') {
490 			for (i = 0; i < count; i++)
491 				event_continue(events[i], buf);
492 			continue;
493 		}
494 
495 		/* Get rid of leading spaces (non-standard) */
496 		while (isspace((unsigned char)buf[0]))
497 			memcpy(buf, buf + 1, strlen(buf));
498 
499 		/* No tab in the line, then not a valid line */
500 		if ((pp = strchr(buf, '\t')) == NULL)
501 			continue;
502 
503 		/* Trim spaces in front of the tab */
504 		while (isspace((unsigned char)pp[-1]))
505 			pp--;
506 
507 		p = *pp;
508 		*pp = '\0';
509 		if ((count = parsedaymonth(buf, year, month, day, &flags,
510 		    extradata)) == 0)
511 			continue;
512 		*pp = p;
513 		if (count < 0) {
514 			/* Show error status based on return value */
515 			if (debug)
516 				WARN1("Ignored: \"%s\"", buf);
517 			if (count == -1)
518 				continue;
519 			count = -count + 1;
520 		}
521 
522 		/* Find the last tab */
523 		while (pp[1] == '\t')
524 			pp++;
525 
526 		for (i = 0; i < count; i++) {
527 			if (debug)
528 				WARN1("got \"%s\"", pp);
529 			events[i] = event_add(year[i], month[i], day[i],
530 			    ((flags &= F_VARIABLE) != 0) ? 1 : 0, pp,
531 			    extradata[i]);
532 		}
533 	}
534 	while (skip-- > 0 || unskip-- > 0) {
535 		cal_line++;
536 		WARN0("Missing #endif assumed");
537 	}
538 
539 	free(line);
540 	fclose(in);
541 
542 	return (0);
543 }
544 
545 void
546 cal(void)
547 {
548 	FILE *fpin;
549 	FILE *fpout;
550 	int i;
551 
552 	for (i = 0; i < MAXCOUNT; i++)
553 		extradata[i] = (char *)calloc(1, 20);
554 
555 
556 	if ((fpin = opencalin()) == NULL)
557 		return;
558 
559 	if ((fpout = opencalout()) == NULL) {
560 		fclose(fpin);
561 		return;
562 	}
563 
564 	if (cal_parse(fpin, fpout))
565 		return;
566 
567 	event_print_all(fpout);
568 	closecal(fpout);
569 }
570 
571 FILE *
572 opencalin(void)
573 {
574 	struct stat sbuf;
575 	FILE *fpin;
576 
577 	/* open up calendar file */
578 	cal_file = calendarFile;
579 	if ((fpin = fopen(calendarFile, "r")) == NULL) {
580 		if (doall) {
581 			if (chdir(calendarHomes[0]) != 0)
582 				return (NULL);
583 			if (stat(calendarNoMail, &sbuf) == 0)
584 				return (NULL);
585 			if ((fpin = fopen(calendarFile, "r")) == NULL)
586 				return (NULL);
587 		} else {
588 			fpin = cal_fopen(calendarFile);
589 		}
590 	}
591 	return (fpin);
592 }
593 
594 FILE *
595 opencalout(void)
596 {
597 	int fd;
598 
599 	/* not reading all calendar files, just set output to stdout */
600 	if (!doall)
601 		return (stdout);
602 
603 	/* set output to a temporary file, so if no output don't send mail */
604 	snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
605 	if ((fd = mkstemp(path)) < 0)
606 		return (NULL);
607 	return (fdopen(fd, "w+"));
608 }
609 
610 void
611 closecal(FILE *fp)
612 {
613 	struct stat sbuf;
614 	int nread, pdes[2], status;
615 	char buf[1024];
616 
617 	if (!doall)
618 		return;
619 
620 	rewind(fp);
621 	if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
622 		goto done;
623 	if (pipe(pdes) < 0)
624 		goto done;
625 	switch (fork()) {
626 	case -1:			/* error */
627 		(void)close(pdes[0]);
628 		(void)close(pdes[1]);
629 		goto done;
630 	case 0:
631 		/* child -- set stdin to pipe output */
632 		if (pdes[0] != STDIN_FILENO) {
633 			(void)dup2(pdes[0], STDIN_FILENO);
634 			(void)close(pdes[0]);
635 		}
636 		(void)close(pdes[1]);
637 		execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
638 		    "\"Reminder Service\"", (char *)NULL);
639 		warn(_PATH_SENDMAIL);
640 		_exit(1);
641 	}
642 	/* parent -- write to pipe input */
643 	(void)close(pdes[0]);
644 
645 	write(pdes[1], "From: \"Reminder Service\" <", 26);
646 	write(pdes[1], pw->pw_name, strlen(pw->pw_name));
647 	write(pdes[1], ">\nTo: <", 7);
648 	write(pdes[1], pw->pw_name, strlen(pw->pw_name));
649 	write(pdes[1], ">\nSubject: ", 11);
650 	write(pdes[1], dayname, strlen(dayname));
651 	write(pdes[1], "'s Calendar\nPrecedence: bulk\n\n", 30);
652 
653 	while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
654 		(void)write(pdes[1], buf, nread);
655 	(void)close(pdes[1]);
656 done:	(void)fclose(fp);
657 	(void)unlink(path);
658 	while (wait(&status) >= 0);
659 }
660