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