Remove building with NOCRYPTO option
[minix3.git] / usr.bin / calendar / calendar.c
blobcddcb1fef5a62f6fb71067f542597118f4a71d34
1 /* $NetBSD: calendar.c,v 1.52 2015/07/01 06:48:25 dholland Exp $ */
3 /*
4 * Copyright (c) 1989, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
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.
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.
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
35 The Regents of the University of California. All rights reserved.");
36 #endif /* not lint */
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)calendar.c 8.4 (Berkeley) 1/7/95";
41 #endif
42 __RCSID("$NetBSD: calendar.c,v 1.52 2015/07/01 06:48:25 dholland Exp $");
43 #endif /* not lint */
45 #include <sys/param.h>
46 #include <sys/ioctl.h>
47 #include <sys/time.h>
48 #include <sys/stat.h>
49 #include <sys/uio.h>
50 #include <sys/wait.h>
52 #include <assert.h>
53 #include <ctype.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <pwd.h>
58 #include <stdbool.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <time.h>
63 #include <tzfile.h>
64 #include <unistd.h>
66 #include "pathnames.h"
68 /* flags used by calendar file parser */
69 #define F_ISMONTH 0x01
70 #define F_ISDAY 0x02
71 #define F_ISDOW 0x04
72 #define F_WILDMONTH 0x10
73 #define F_WILDDAY 0x20
75 static unsigned short lookahead = 1;
76 static unsigned short weekend = 2;
77 static char *fname = NULL;
78 static char *datestr = NULL;
79 static const char *defaultnames[] = {"calendar", ".calendar", _PATH_SYSTEM_CALENDAR, NULL};
80 static struct passwd *pw;
81 static char path[MAXPATHLEN + 1];
82 static bool doall = false;
83 static bool cpp_restricted = false;
85 /* 1-based month, 0-based days, cumulative */
86 static const int daytab[][14] = {
87 { 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
88 { 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
90 static struct tm *tp;
91 static const int *cumdays;
92 static int offset, yrdays;
93 static char dayname[10];
95 static struct iovec header[] = {
96 { __UNCONST("From: "), 6 },
97 { NULL, 0 },
98 { __UNCONST(" (Reminder Service)\nTo: "), 24 },
99 { NULL, 0 },
100 { __UNCONST("\nSubject: "), 10 },
101 { NULL, 0 },
102 { __UNCONST("'s Calendar\nPrecedence: bulk\n\n"), 30 },
105 static const char *days[] = {
106 "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
109 static const char *months[] = {
110 "jan", "feb", "mar", "apr", "may", "jun",
111 "jul", "aug", "sep", "oct", "nov", "dec", NULL,
114 static void atodays(int, char *, unsigned short *);
115 static void cal(void);
116 static void closecal(FILE *);
117 static void changeuser(void);
118 static int getday(char *);
119 static int getfield(char *, char **, int *);
120 static void getmmdd(struct tm *, char *);
121 static int getmonth(char *);
122 static bool isnow(char *);
123 static FILE *opencal(FILE **);
124 static int tryopen(const char *, int);
125 static void settime(void);
126 static void usage(void) __dead;
129 main(int argc, char **argv)
131 int ch;
132 const char *caldir;
134 (void)setprogname(argv[0]); /* for portability */
136 while ((ch = getopt(argc, argv, "-ad:f:l:w:x")) != -1) {
137 switch (ch) {
138 case '-': /* backward contemptible */
139 case 'a':
140 if (getuid()) {
141 errno = EPERM;
142 err(EXIT_FAILURE, NULL);
144 doall = true;
145 break;
146 case 'd':
147 datestr = optarg;
148 break;
149 case 'f':
150 fname = optarg;
151 break;
152 case 'l':
153 atodays(ch, optarg, &lookahead);
154 break;
155 case 'w':
156 atodays(ch, optarg, &weekend);
157 break;
158 case 'x':
159 cpp_restricted = true;
160 break;
161 case '?':
162 default:
163 usage();
166 argc -= optind;
167 argv += optind;
169 if (argc)
170 usage();
172 settime();
173 if (doall) {
175 * XXX - This ignores the user's CALENDAR_DIR variable.
176 * Run under user's login shell?
178 if (setgroups(0, NULL) == -1) {
179 err(EXIT_FAILURE, "setgroups");
181 while ((pw = getpwent()) != NULL) {
182 if (setegid(pw->pw_gid) == -1) {
183 warn("%s: setegid", pw->pw_name);
184 continue;
186 if (seteuid(pw->pw_uid) == -1) {
187 warn("%s: seteuid", pw->pw_name);
188 continue;
190 if (chdir(pw->pw_dir) != -1) {
191 cal();
193 if (seteuid(0) == -1) {
194 warn("%s: seteuid back to 0", pw->pw_name);
197 } else if ((caldir = getenv("CALENDAR_DIR")) != NULL) {
198 if (chdir(caldir) != -1)
199 cal();
200 } else if ((pw = getpwuid(geteuid())) != NULL) {
201 if (chdir(pw->pw_dir) != -1)
202 cal();
204 return 0;
207 static void
208 cal(void)
210 bool printing;
211 FILE *fp, *in = NULL;
212 char *line;
214 if ((fp = opencal(&in)) == NULL || in == NULL)
215 return;
216 printing = false;
217 while ((line = fparseln(in,
218 NULL, NULL, NULL, FPARSELN_UNESCCOMM)) != NULL) {
219 if (line[0] == '\0')
220 continue;
221 if (line[0] != '\t')
222 printing = isnow(line);
223 if (printing)
224 (void)fprintf(fp, "%s\n", line);
225 free(line);
228 closecal(fp);
231 static void
232 settime(void)
234 time_t now;
236 (void)time(&now);
237 tp = localtime(&now);
238 if (datestr)
239 getmmdd(tp, datestr);
241 if (isleap(tp->tm_year + TM_YEAR_BASE)) {
242 yrdays = DAYSPERLYEAR;
243 cumdays = daytab[1];
244 } else {
245 yrdays = DAYSPERNYEAR;
246 cumdays = daytab[0];
248 /* Friday displays Monday's events */
249 offset = tp->tm_wday == 5 ? lookahead + weekend : lookahead;
250 header[5].iov_base = dayname;
251 header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
255 * Possible date formats include any combination of:
256 * 3-charmonth (January, Jan, Jan)
257 * 3-charweekday (Friday, Monday, mon.)
258 * numeric month or day (1, 2, 04)
260 * Any character may separate them, or they may not be separated. Any line,
261 * following a line that is matched, that starts with "whitespace", is shown
262 * along with the matched line.
264 static bool
265 isnow(char *endp)
267 int day;
268 int flags;
269 int month;
270 int v1;
271 int v2;
273 flags = 0;
275 /* didn't recognize anything, skip it */
276 if (!(v1 = getfield(endp, &endp, &flags)))
277 return false;
279 if ((flags & (F_ISDAY|F_ISDOW)) || v1 > 12) {
280 /* found a day */
281 day = v1;
282 /* if no recognizable month, assume wildcard ('*') month */
283 if ((month = getfield(endp, &endp, &flags)) == 0) {
284 flags |= F_ISMONTH | F_WILDMONTH;
285 month = tp->tm_mon + 1;
287 } else if (flags & F_ISMONTH) {
288 month = v1;
289 /* if no recognizable day, assume the first */
290 if ((day = getfield(endp, &endp, &flags)) == 0)
291 day = 1;
292 } else {
293 v2 = getfield(endp, &endp, &flags);
294 if (flags & F_ISMONTH) {
295 day = v1;
296 month = v2;
297 } else {
298 /* F_ISDAY set, v2 > 12, or no way to tell */
299 month = v1;
300 /* if no recognizable day, assume the first */
301 day = v2 ? v2 : 1;
304 /* if month is out of range, treat it as '*' */
305 if (month < 1 || month > 12) {
306 flags |= F_ISMONTH | F_WILDMONTH;
307 month = tp->tm_mon + 1;
310 if (flags & F_WILDMONTH && flags & F_WILDDAY)
311 return true;
313 if (flags & F_WILDMONTH && flags & F_ISDAY && day == tp->tm_mday)
314 return true;
316 if (flags & F_WILDMONTH && flags & F_ISDOW && day == tp->tm_wday + 1)
317 return true;
319 if (flags & F_ISMONTH && flags & F_WILDDAY && month == tp->tm_mon + 1)
320 return true;
322 if (flags & F_ISMONTH && flags & F_ISDOW && month == tp->tm_mon + 1 &&
323 day == tp->tm_wday + 1)
324 return true;
326 if (flags & F_ISDOW)
327 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
328 day = cumdays[month] + day;
330 /* if today or today + offset days */
331 if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
332 return true;
334 /* if number of days left in this year + days to event in next year */
335 if (yrdays - tp->tm_yday + day <= offset)
336 return true;
338 return false;
341 static int
342 getfield(char *p, char **endp, int *flags)
344 int val;
345 char *start;
346 char savech;
349 * note this macro has an arg that isn't used ... it is retained
350 * (it is believed) to make the macro call look more "natural"
351 * and suggest at the call site what is happening.
353 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
354 !isalpha((unsigned char)*p) && *p != '*')
356 val = 0;
357 for (/*EMPTY*/; FLDCHAR(*p); ++p)
358 continue;
359 if (*p == '*') { /* `*' is current month */
360 if (!(*flags & F_ISMONTH)) {
361 *flags |= F_ISMONTH | F_WILDMONTH;
362 *endp = p + 1;
363 return tp->tm_mon + 1;
364 } else {
365 *flags |= F_ISDAY | F_WILDDAY;
366 *endp = p + 1;
367 return 1;
370 if (isdigit((unsigned char)*p)) {
371 val = (int)strtol(p, &p, 10); /* if 0, it's failure */
372 for (/*EMPTY*/; FLDCHAR(*p); ++p)
373 continue;
374 *endp = p;
375 return val;
377 for (start = p; *p != '\0' && isalpha((unsigned char)*p); p++)
378 continue;
380 savech = *p;
381 if (p != start) {
382 *p = '\0';
383 if ((val = getmonth(start)) != 0)
384 *flags |= F_ISMONTH;
385 else if ((val = getday(start)) != 0)
386 *flags |= F_ISDOW;
387 else {
388 *p = savech;
389 *endp = start;
390 return 0;
393 for (*p = savech; FLDCHAR(*p); ++p)
394 continue;
395 *endp = p;
396 return val;
399 static FILE *
400 opencal(FILE **in)
402 int fd = -1;
403 int pdes[2];
405 /* open up calendar file as stdin */
406 if (fname == NULL) {
407 for (const char **name = defaultnames; *name != NULL; name++) {
408 if ((fd = tryopen(*name, O_RDONLY)) == -1)
409 continue;
410 else
411 break;
413 if (fd == -1) {
414 if (doall)
415 return NULL;
416 err(EXIT_FAILURE, "Cannot open calendar file");
418 } else if ((fd = tryopen(fname, O_RDONLY)) == -1) {
419 if (doall)
420 return NULL;
421 err(EXIT_FAILURE, "Cannot open `%s'", fname);
424 if (pipe(pdes) == -1) {
425 warn("Cannot open pipe");
426 return NULL;
429 switch (fork()) {
430 case -1:
431 /* error */
432 (void)close(pdes[0]);
433 (void)close(pdes[1]);
434 return NULL;
435 case 0:
436 /* child */
437 /* set stdin to calendar file */
438 if (fd != STDIN_FILENO) {
439 (void)dup2(fd, STDIN_FILENO);
440 (void)close(fd);
442 /* set stdout to pipe input */
443 if (pdes[1] != STDOUT_FILENO) {
444 (void)dup2(pdes[1], STDOUT_FILENO);
445 (void)close(pdes[1]);
447 (void)close(pdes[0]);
448 if (doall) {
449 /* become the user properly */
450 changeuser();
452 /* tell CPP to only open regular files */
453 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1) == -1)
454 err(EXIT_FAILURE, "Cannot restrict cpp");
455 cpp_restricted = true;
457 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
458 "-I" _PATH_CALENDARS, NULL);
459 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_CPP);
460 /*NOTREACHED*/
461 default:
462 /* parent -- fdopen *in to pipe output */
463 *in = fdopen(pdes[0], "r");
464 (void)close(pdes[1]);
466 /* close calendar file */
467 close(fd);
469 /* not reading all calendar files, just set output to stdout */
470 if (!doall)
471 return stdout;
474 * Set output to a temporary file, so if no output
475 * don't send mail.
477 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
478 if ((fd = mkstemp(path)) == -1) {
479 warn("Cannot create temporary file");
480 return NULL;
482 return fdopen(fd, "w+");
484 /*NOTREACHED*/
487 static int
488 tryopen(const char *pathname, int flags)
490 int fd, serrno, zero;
491 struct stat st;
494 * XXX: cpp_restricted has inverted sense; it is false by default,
495 * and -x sets it to true. CPP_RESTRICTED is set in the environment
496 * if cpp_restricted is false... go figure. This should be fixed
497 * later.
499 if (doall && cpp_restricted == false) {
501 * We are running with the user's euid, so they can't
502 * cause any mayhem (e.g. opening rewinding tape
503 * devices) that they couldn't do easily enough on
504 * their own. All we really need to worry about is opens
505 * that hang, because that would DoS the calendar run.
507 fd = open(pathname, flags | O_NONBLOCK);
508 if (fd == -1) {
509 return -1;
511 if (fstat(fd, &st) == -1) {
512 serrno = errno;
513 close(fd);
514 errno = serrno;
515 return -1;
517 if (S_ISCHR(st.st_mode) ||
518 S_ISBLK(st.st_mode) ||
519 S_ISFIFO(st.st_mode)) {
520 close(fd);
522 /* Call shenanigans in the daily output */
523 errno = EPERM;
524 warn("%s: %s", pw->pw_name, pathname);
526 errno = EPERM;
527 return -1;
529 if (S_ISDIR(st.st_mode)) {
530 /* Don't warn about this */
531 close(fd);
532 errno = EISDIR;
533 return -1;
535 if (!S_ISREG(st.st_mode)) {
536 /* There shouldn't be other cases to go here */
537 close(fd);
538 errno = EINVAL;
539 return -1;
541 zero = 0;
542 if (ioctl(fd, FIONBIO, &zero) == -1) {
543 serrno = errno;
544 warn("%s: %s: FIONBIO", pw->pw_name, pathname);
545 close(fd);
546 errno = serrno;
547 return -1;
549 return fd;
550 } else {
551 return open(pathname, flags);
555 static void
556 closecal(FILE *fp)
558 struct stat sbuf;
559 ssize_t nread;
560 int pdes[2];
561 int status;
562 char buf[1024];
564 if (!doall)
565 return;
567 (void)rewind(fp);
568 if (fstat(fileno(fp), &sbuf) == -1 || sbuf.st_size == 0)
569 goto done;
570 if (pipe(pdes) == -1)
571 goto done;
573 switch (fork()) {
574 case -1:
575 /* error */
576 (void)close(pdes[0]);
577 (void)close(pdes[1]);
578 break;
579 case 0:
580 /* child -- set stdin to pipe output */
581 if (pdes[0] != STDIN_FILENO) {
582 (void)dup2(pdes[0], STDIN_FILENO);
583 (void)close(pdes[0]);
585 (void)close(pdes[1]);
586 if (doall) {
587 /* become the user properly */
588 changeuser();
590 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
591 "\"Reminder Service\"", "-f", "root", NULL);
592 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_SENDMAIL);
593 /*NOTREACHED*/
594 default:
595 /* parent -- write to pipe input */
596 (void)close(pdes[0]);
598 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
599 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
600 (void)writev(pdes[1], header, 7);
601 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
602 (void)write(pdes[1], buf, (size_t)nread);
603 (void)close(pdes[1]);
604 break;
607 done: (void)fclose(fp);
608 (void)unlink(path);
609 while (wait(&status) != -1)
610 continue;
613 static void
614 changeuser(void)
616 uid_t uid;
617 gid_t gid;
619 uid = geteuid();
620 gid = getegid();
621 assert(uid == pw->pw_uid);
622 assert(gid == pw->pw_gid);
624 if (seteuid(0) == -1) {
625 err(EXIT_FAILURE, "%s: changing user: cannot reassert uid 0",
626 pw->pw_name);
628 if (setgid(gid) == -1) {
629 err(EXIT_FAILURE, "%s: cannot assume gid %d",
630 pw->pw_name, (int)gid);
632 if (initgroups(pw->pw_name, gid) == -1) {
633 err(EXIT_FAILURE, "%s: cannot initgroups", pw->pw_name);
635 if (setuid(uid) == -1) {
636 err(EXIT_FAILURE, "%s: cannot assume uid %d",
637 pw->pw_name, (int)uid);
641 static int
642 getmonth(char *s)
644 const char **p;
646 for (p = months; *p; ++p)
647 if (strncasecmp(s, *p, 3) == 0)
648 return (int)(p - months) + 1;
649 return 0;
652 static int
653 getday(char *s)
655 const char **p;
657 for (p = days; *p; ++p)
658 if (strncasecmp(s, *p, 3) == 0)
659 return (int)(p - days) + 1;
660 return 0;
663 static void
664 atodays(int ch, char *arg, unsigned short *rvp)
666 int u;
668 u = atoi(arg);
669 if (u < 0 || u > 366)
670 warnx("-%c %d out of range 0-366, ignored.", ch, u);
671 else
672 *rvp = u;
675 #define todigit(x) ((x) - '0')
676 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
677 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
679 static void
680 getmmdd(struct tm *ptm, char *ds)
682 bool ok = false;
683 struct tm ttm;
685 ttm = *ptm;
686 ttm.tm_isdst = -1;
688 if (ISDIG2(ds)) {
689 ttm.tm_mon = ATOI2(ds) - 1;
690 ds += 2;
692 if (ISDIG2(ds)) {
693 ttm.tm_mday = ATOI2(ds);
694 ds += 2;
695 ok = true;
697 if (ok) {
698 if (ISDIG2(ds) && ISDIG2(ds + 2)) {
699 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
700 ds += 2;
701 ttm.tm_year += ATOI2(ds);
702 } else if (ISDIG2(ds)) {
703 ttm.tm_year = ATOI2(ds);
704 if (ttm.tm_year < 69)
705 ttm.tm_year += 2000 - TM_YEAR_BASE;
706 else
707 ttm.tm_year += 1900 - TM_YEAR_BASE;
710 if (ok && mktime(&ttm) == -1)
711 ok = false;
713 if (ok)
714 *ptm = ttm;
715 else {
716 warnx("Can't convert `%s' to date, ignored.", ds);
717 usage();
721 __dead
722 static void
723 usage(void)
725 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
726 " [-f fname] [-l days] [-w days]\n", getprogname());
727 exit(1);