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