Restrict ncdcs.debug and man pages to MKBINUTILS=yes builds.
[netbsd-mini2440.git] / usr.bin / calendar / calendar.c
blob195911c99a729957f0a0eb14e4d02046fefc482a
1 /* $NetBSD: calendar.c,v 1.46 2008/07/21 14:19:21 lukem 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.46 2008/07/21 14:19:21 lukem Exp $");
43 #endif /* not lint */
45 #include <sys/param.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/uio.h>
49 #include <sys/wait.h>
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <pwd.h>
56 #include <stdbool.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <time.h>
61 #include <tzfile.h>
62 #include <unistd.h>
64 #include "pathnames.h"
66 static unsigned short lookahead = 1;
67 static unsigned short weekend = 2;
68 static char *fname = NULL;
69 static char *datestr = NULL;
70 static const char *defaultnames[] = {"calendar", ".calendar", _PATH_SYSTEM_CALENDAR, NULL};
71 static struct passwd *pw;
72 static char path[MAXPATHLEN + 1];
73 static bool doall = false;
74 static bool cpp_restricted = false;
76 /* 1-based month, 0-based days, cumulative */
77 static const int daytab[][14] = {
78 { 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
79 { 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
81 static struct tm *tp;
82 static const int *cumdays;
83 static int offset, yrdays;
84 static char dayname[10];
86 static struct iovec header[] = {
87 { __UNCONST("From: "), 6 },
88 { NULL, 0 },
89 { __UNCONST(" (Reminder Service)\nTo: "), 24 },
90 { NULL, 0 },
91 { __UNCONST("\nSubject: "), 10 },
92 { NULL, 0 },
93 { __UNCONST("'s Calendar\nPrecedence: bulk\n\n"), 30 },
96 static const char *days[] = {
97 "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
100 static const char *months[] = {
101 "jan", "feb", "mar", "apr", "may", "jun",
102 "jul", "aug", "sep", "oct", "nov", "dec", NULL,
105 static void atodays(int, char *, unsigned short *);
106 static void cal(void);
107 static void closecal(FILE *);
108 static int getday(char *);
109 static int getfield(char *, char **, int *);
110 static void getmmdd(struct tm *, char *);
111 static int getmonth(char *);
112 static bool isnow(char *);
113 static FILE *opencal(void);
114 static void settime(void);
115 static void usage(void) __dead;
118 main(int argc, char **argv)
120 int ch;
121 const char *caldir;
123 (void)setprogname(argv[0]); /* for portability */
125 while ((ch = getopt(argc, argv, "-ad:f:l:w:x")) != -1) {
126 switch (ch) {
127 case '-': /* backward contemptible */
128 case 'a':
129 if (getuid()) {
130 errno = EPERM;
131 err(EXIT_FAILURE, NULL);
133 doall = true;
134 break;
135 case 'd':
136 datestr = optarg;
137 break;
138 case 'f':
139 fname = optarg;
140 break;
141 case 'l':
142 atodays(ch, optarg, &lookahead);
143 break;
144 case 'w':
145 atodays(ch, optarg, &weekend);
146 break;
147 case 'x':
148 cpp_restricted = true;
149 break;
150 case '?':
151 default:
152 usage();
155 argc -= optind;
156 argv += optind;
158 if (argc)
159 usage();
161 settime();
162 if (doall) {
164 * XXX - This ignores the user's CALENDAR_DIR variable.
165 * Run under user's login shell?
167 while ((pw = getpwent()) != NULL) {
168 (void)setegid(pw->pw_gid);
169 (void)seteuid(pw->pw_uid);
170 if (chdir(pw->pw_dir) != -1)
171 cal();
172 (void)seteuid(0);
174 } else if ((caldir = getenv("CALENDAR_DIR")) != NULL) {
175 if (chdir(caldir) != -1)
176 cal();
177 } else if ((pw = getpwuid(geteuid())) != NULL) {
178 if (chdir(pw->pw_dir) != -1)
179 cal();
181 return 0;
184 static void
185 cal(void)
187 bool printing;
188 FILE *fp;
189 char *line;
191 if ((fp = opencal()) == NULL)
192 return;
193 printing = false;
194 while ((line = fparseln(stdin,
195 NULL, NULL, NULL, FPARSELN_UNESCCOMM)) != NULL) {
196 if (line[0] == '\0')
197 continue;
198 if (line[0] != '\t')
199 printing = isnow(line);
200 if (printing)
201 (void)fprintf(fp, "%s\n", line);
202 free(line);
205 closecal(fp);
208 static void
209 settime(void)
211 time_t now;
213 (void)time(&now);
214 tp = localtime(&now);
215 if (datestr)
216 getmmdd(tp, datestr);
218 if (isleap(tp->tm_year + TM_YEAR_BASE)) {
219 yrdays = DAYSPERLYEAR;
220 cumdays = daytab[1];
221 } else {
222 yrdays = DAYSPERNYEAR;
223 cumdays = daytab[0];
225 /* Friday displays Monday's events */
226 offset = tp->tm_wday == 5 ? lookahead + weekend : lookahead;
227 header[5].iov_base = dayname;
228 header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
232 * Possible date formats include any combination of:
233 * 3-charmonth (January, Jan, Jan)
234 * 3-charweekday (Friday, Monday, mon.)
235 * numeric month or day (1, 2, 04)
237 * Any character may separate them, or they may not be separated. Any line,
238 * following a line that is matched, that starts with "whitespace", is shown
239 * along with the matched line.
241 static bool
242 isnow(char *endp)
244 int day;
245 int flags;
246 int month;
247 int v1;
248 int v2;
250 #define F_ISMONTH 0x01
251 #define F_ISDAY 0x02
252 #define F_WILDMONTH 0x04
253 #define F_WILDDAY 0x08
255 flags = 0;
257 /* didn't recognize anything, skip it */
258 if (!(v1 = getfield(endp, &endp, &flags)))
259 return false;
261 if (flags & F_ISDAY || v1 > 12) {
262 /* found a day */
263 day = v1;
264 /* if no recognizable month, assume wildcard ('*') month */
265 if ((month = getfield(endp, &endp, &flags)) == 0) {
266 flags |= F_ISMONTH | F_WILDMONTH;
267 month = tp->tm_mon + 1;
269 } else if (flags & F_ISMONTH) {
270 month = v1;
271 /* if no recognizable day, assume the first */
272 if ((day = getfield(endp, &endp, &flags)) == 0)
273 day = 1;
274 } else {
275 v2 = getfield(endp, &endp, &flags);
276 if (flags & F_ISMONTH) {
277 day = v1;
278 month = v2;
279 } else {
280 /* F_ISDAY set, v2 > 12, or no way to tell */
281 month = v1;
282 /* if no recognizable day, assume the first */
283 day = v2 ? v2 : 1;
286 /* if month is out of range, treat it as '*' */
287 if (month < 1 || month > 12) {
288 flags |= F_ISMONTH | F_WILDMONTH;
289 month = tp->tm_mon + 1;
292 if (flags & F_WILDMONTH && flags & F_WILDDAY)
293 return true;
295 if (flags & F_WILDMONTH && flags & F_ISDAY && day == tp->tm_mday)
296 return true;
298 if (flags & F_ISMONTH && flags & F_WILDDAY && month == tp->tm_mon + 1)
299 return true;
301 if (flags & F_ISDAY)
302 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
303 day = cumdays[month] + day;
305 /* if today or today + offset days */
306 if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
307 return true;
309 /* if number of days left in this year + days to event in next year */
310 if (yrdays - tp->tm_yday + day <= offset)
311 return true;
313 return false;
316 static int
317 getfield(char *p, char **endp, int *flags)
319 int val;
320 char *start;
321 char savech;
323 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
324 !isalpha((unsigned char)*p) && *p != '*')
326 for (/*EMPTY*/; FLDCHAR(*p); ++p)
327 continue;
328 if (*p == '*') { /* `*' is current month */
329 if (!(*flags & F_ISMONTH)) {
330 *flags |= F_ISMONTH | F_WILDMONTH;
331 *endp = p + 1;
332 return tp->tm_mon + 1;
333 } else {
334 *flags |= F_ISDAY | F_WILDDAY;
335 *endp = p + 1;
336 return 1;
339 if (isdigit((unsigned char)*p)) {
340 val = (int)strtol(p, &p, 10); /* if 0, it's failure */
341 for (/*EMPTY*/; FLDCHAR(*p); ++p)
342 continue;
343 *endp = p;
344 return val;
346 for (start = p; *p != '\0' && isalpha((unsigned char)*++p); /*EMPTY*/)
347 continue;
348 savech = *p;
349 *p = '\0';
350 if ((val = getmonth(start)) != 0)
351 *flags |= F_ISMONTH;
352 else if ((val = getday(start)) != 0)
353 *flags |= F_ISDAY;
354 else {
355 *p = savech;
356 return 0;
358 for (*p = savech; FLDCHAR(*p); ++p)
359 continue;
360 *endp = p;
361 return val;
364 static FILE *
365 opencal(void)
367 int fd;
368 int pdes[2];
369 const char **name;
371 /* open up calendar file as stdin */
372 if (fname == NULL) {
373 for (name = defaultnames; *name != NULL; name++) {
374 if (freopen(*name, "rf", stdin) == NULL)
375 continue;
376 else
377 break;
379 if (*name == NULL) {
380 if (doall)
381 return NULL;
382 err(EXIT_FAILURE, "Cannot open calendar file");
384 } else if (freopen(fname, "rf", stdin) == NULL) {
385 if (doall)
386 return NULL;
387 err(EXIT_FAILURE, "Cannot open `%s'", fname);
390 if (pipe(pdes) == -1) {
391 warn("Cannot open pipe");
392 return NULL;
395 switch (fork()) {
396 case -1:
397 /* error */
398 (void)close(pdes[0]);
399 (void)close(pdes[1]);
400 return NULL;
401 case 0:
402 /* child -- stdin already setup, set stdout to pipe input */
403 if (pdes[1] != STDOUT_FILENO) {
404 (void)dup2(pdes[1], STDOUT_FILENO);
405 (void)close(pdes[1]);
407 (void)close(pdes[0]);
408 /* tell CPP to only open regular files */
409 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1) == -1)
410 err(EXIT_FAILURE, "Cannot restrict cpp");
411 cpp_restricted = true;
413 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
414 "-I" _PATH_CALENDARS, NULL);
415 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_CPP);
416 /*NOTREACHED*/
417 default:
418 /* parent -- set stdin to pipe output */
419 (void)dup2(pdes[0], STDIN_FILENO);
420 (void)close(pdes[0]);
421 (void)close(pdes[1]);
423 /* not reading all calendar files, just set output to stdout */
424 if (!doall)
425 return stdout;
428 * Set output to a temporary file, so if no output
429 * don't send mail.
431 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
432 if ((fd = mkstemp(path)) == -1) {
433 warn("Cannot create temporary file");
434 return NULL;
436 return fdopen(fd, "w+");
438 /*NOTREACHED*/
441 static void
442 closecal(FILE *fp)
444 struct stat sbuf;
445 ssize_t nread;
446 int pdes[2];
447 int status;
448 char buf[1024];
450 if (!doall)
451 return;
453 (void)rewind(fp);
454 if (fstat(fileno(fp), &sbuf) == -1 || sbuf.st_size == 0)
455 goto done;
456 if (pipe(pdes) == -1)
457 goto done;
459 switch (fork()) {
460 case -1:
461 /* error */
462 (void)close(pdes[0]);
463 (void)close(pdes[1]);
464 break;
465 case 0:
466 /* child -- set stdin to pipe output */
467 if (pdes[0] != STDIN_FILENO) {
468 (void)dup2(pdes[0], STDIN_FILENO);
469 (void)close(pdes[0]);
471 (void)close(pdes[1]);
472 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
473 "\"Reminder Service\"", "-f", "root", NULL);
474 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_SENDMAIL);
475 /*NOTREACHED*/
476 default:
477 /* parent -- write to pipe input */
478 (void)close(pdes[0]);
480 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
481 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
482 (void)writev(pdes[1], header, 7);
483 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
484 (void)write(pdes[1], buf, (size_t)nread);
485 (void)close(pdes[1]);
486 break;
489 done: (void)fclose(fp);
490 (void)unlink(path);
491 while (wait(&status) != -1)
492 continue;
495 static int
496 getmonth(char *s)
498 const char **p;
500 for (p = months; *p; ++p)
501 if (strncasecmp(s, *p, 3) == 0)
502 return (int)(p - months) + 1;
503 return 0;
506 static int
507 getday(char *s)
509 const char **p;
511 for (p = days; *p; ++p)
512 if (strncasecmp(s, *p, 3) == 0)
513 return (int)(p - days) + 1;
514 return 0;
517 static void
518 atodays(int ch, char *arg, unsigned short *rvp)
520 int u;
522 u = atoi(arg);
523 if (u < 0 || u > 366)
524 warnx("-%c %d out of range 0-366, ignored.", ch, u);
525 else
526 *rvp = u;
529 #define todigit(x) ((x) - '0')
530 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
531 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
533 static void
534 getmmdd(struct tm *ptm, char *ds)
536 bool ok = false;
537 struct tm ttm;
539 ttm = *ptm;
540 ttm.tm_isdst = -1;
542 if (ISDIG2(ds)) {
543 ttm.tm_mon = ATOI2(ds) - 1;
544 ds += 2;
546 if (ISDIG2(ds)) {
547 ttm.tm_mday = ATOI2(ds);
548 ds += 2;
549 ok = true;
551 if (ok) {
552 if (ISDIG2(ds) && ISDIG2(ds + 2)) {
553 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
554 ds += 2;
555 ttm.tm_year += ATOI2(ds);
556 } else if (ISDIG2(ds)) {
557 ttm.tm_year = ATOI2(ds);
558 if (ttm.tm_year < 69)
559 ttm.tm_year += 2000 - TM_YEAR_BASE;
560 else
561 ttm.tm_year += 1900 - TM_YEAR_BASE;
564 if (ok && mktime(&ttm) == -1)
565 ok = false;
567 if (ok)
568 *ptm = ttm;
569 else {
570 warnx("Can't convert `%s' to date, ignored.", ds);
571 usage();
575 __dead
576 static void
577 usage(void)
579 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
580 " [-f fname] [-l days] [-w days]\n", getprogname());
581 exit(1);