Patrick Welche <prlw1@cam.ac.uk>
[netbsd-mini2440.git] / usr.bin / calendar / calendar.c
bloba7756da441fb16e312f584666c267c4a2ac39299
1 /* $NetBSD: calendar.c,v 1.47 2008/09/30 05:51:41 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.47 2008/09/30 05:51:41 dholland 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 /* flags used by calendar file parser */
67 #define F_ISMONTH 0x01
68 #define F_ISDAY 0x02
69 #define F_ISDOW 0x04
70 #define F_WILDMONTH 0x10
71 #define F_WILDDAY 0x20
73 static unsigned short lookahead = 1;
74 static unsigned short weekend = 2;
75 static char *fname = NULL;
76 static char *datestr = NULL;
77 static const char *defaultnames[] = {"calendar", ".calendar", _PATH_SYSTEM_CALENDAR, NULL};
78 static struct passwd *pw;
79 static char path[MAXPATHLEN + 1];
80 static bool doall = false;
81 static bool cpp_restricted = false;
83 /* 1-based month, 0-based days, cumulative */
84 static const int daytab[][14] = {
85 { 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
86 { 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
88 static struct tm *tp;
89 static const int *cumdays;
90 static int offset, yrdays;
91 static char dayname[10];
93 static struct iovec header[] = {
94 { __UNCONST("From: "), 6 },
95 { NULL, 0 },
96 { __UNCONST(" (Reminder Service)\nTo: "), 24 },
97 { NULL, 0 },
98 { __UNCONST("\nSubject: "), 10 },
99 { NULL, 0 },
100 { __UNCONST("'s Calendar\nPrecedence: bulk\n\n"), 30 },
103 static const char *days[] = {
104 "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
107 static const char *months[] = {
108 "jan", "feb", "mar", "apr", "may", "jun",
109 "jul", "aug", "sep", "oct", "nov", "dec", NULL,
112 static void atodays(int, char *, unsigned short *);
113 static void cal(void);
114 static void closecal(FILE *);
115 static int getday(char *);
116 static int getfield(char *, char **, int *);
117 static void getmmdd(struct tm *, char *);
118 static int getmonth(char *);
119 static bool isnow(char *);
120 static FILE *opencal(void);
121 static void settime(void);
122 static void usage(void) __dead;
125 main(int argc, char **argv)
127 int ch;
128 const char *caldir;
130 (void)setprogname(argv[0]); /* for portability */
132 while ((ch = getopt(argc, argv, "-ad:f:l:w:x")) != -1) {
133 switch (ch) {
134 case '-': /* backward contemptible */
135 case 'a':
136 if (getuid()) {
137 errno = EPERM;
138 err(EXIT_FAILURE, NULL);
140 doall = true;
141 break;
142 case 'd':
143 datestr = optarg;
144 break;
145 case 'f':
146 fname = optarg;
147 break;
148 case 'l':
149 atodays(ch, optarg, &lookahead);
150 break;
151 case 'w':
152 atodays(ch, optarg, &weekend);
153 break;
154 case 'x':
155 cpp_restricted = true;
156 break;
157 case '?':
158 default:
159 usage();
162 argc -= optind;
163 argv += optind;
165 if (argc)
166 usage();
168 settime();
169 if (doall) {
171 * XXX - This ignores the user's CALENDAR_DIR variable.
172 * Run under user's login shell?
174 while ((pw = getpwent()) != NULL) {
175 (void)setegid(pw->pw_gid);
176 (void)seteuid(pw->pw_uid);
177 if (chdir(pw->pw_dir) != -1)
178 cal();
179 (void)seteuid(0);
181 } else if ((caldir = getenv("CALENDAR_DIR")) != NULL) {
182 if (chdir(caldir) != -1)
183 cal();
184 } else if ((pw = getpwuid(geteuid())) != NULL) {
185 if (chdir(pw->pw_dir) != -1)
186 cal();
188 return 0;
191 static void
192 cal(void)
194 bool printing;
195 FILE *fp;
196 char *line;
198 if ((fp = opencal()) == NULL)
199 return;
200 printing = false;
201 while ((line = fparseln(stdin,
202 NULL, NULL, NULL, FPARSELN_UNESCCOMM)) != NULL) {
203 if (line[0] == '\0')
204 continue;
205 if (line[0] != '\t')
206 printing = isnow(line);
207 if (printing)
208 (void)fprintf(fp, "%s\n", line);
209 free(line);
212 closecal(fp);
215 static void
216 settime(void)
218 time_t now;
220 (void)time(&now);
221 tp = localtime(&now);
222 if (datestr)
223 getmmdd(tp, datestr);
225 if (isleap(tp->tm_year + TM_YEAR_BASE)) {
226 yrdays = DAYSPERLYEAR;
227 cumdays = daytab[1];
228 } else {
229 yrdays = DAYSPERNYEAR;
230 cumdays = daytab[0];
232 /* Friday displays Monday's events */
233 offset = tp->tm_wday == 5 ? lookahead + weekend : lookahead;
234 header[5].iov_base = dayname;
235 header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
239 * Possible date formats include any combination of:
240 * 3-charmonth (January, Jan, Jan)
241 * 3-charweekday (Friday, Monday, mon.)
242 * numeric month or day (1, 2, 04)
244 * Any character may separate them, or they may not be separated. Any line,
245 * following a line that is matched, that starts with "whitespace", is shown
246 * along with the matched line.
248 static bool
249 isnow(char *endp)
251 int day;
252 int flags;
253 int month;
254 int v1;
255 int v2;
257 flags = 0;
259 /* didn't recognize anything, skip it */
260 if (!(v1 = getfield(endp, &endp, &flags)))
261 return false;
263 if ((flags & (F_ISDAY|F_ISDOW)) || v1 > 12) {
264 /* found a day */
265 day = v1;
266 /* if no recognizable month, assume wildcard ('*') month */
267 if ((month = getfield(endp, &endp, &flags)) == 0) {
268 flags |= F_ISMONTH | F_WILDMONTH;
269 month = tp->tm_mon + 1;
271 } else if (flags & F_ISMONTH) {
272 month = v1;
273 /* if no recognizable day, assume the first */
274 if ((day = getfield(endp, &endp, &flags)) == 0)
275 day = 1;
276 } else {
277 v2 = getfield(endp, &endp, &flags);
278 if (flags & F_ISMONTH) {
279 day = v1;
280 month = v2;
281 } else {
282 /* F_ISDAY set, v2 > 12, or no way to tell */
283 month = v1;
284 /* if no recognizable day, assume the first */
285 day = v2 ? v2 : 1;
288 /* if month is out of range, treat it as '*' */
289 if (month < 1 || month > 12) {
290 flags |= F_ISMONTH | F_WILDMONTH;
291 month = tp->tm_mon + 1;
294 if (flags & F_WILDMONTH && flags & F_WILDDAY)
295 return true;
297 if (flags & F_WILDMONTH && flags & F_ISDAY && day == tp->tm_mday)
298 return true;
300 if (flags & F_WILDMONTH && flags & F_ISDOW && day == tp->tm_wday + 1)
301 return true;
303 if (flags & F_ISMONTH && flags & F_WILDDAY && month == tp->tm_mon + 1)
304 return true;
306 if (flags & F_ISMONTH && flags & F_ISDOW && month == tp->tm_mon + 1 &&
307 day == tp->tm_wday + 1)
308 return true;
310 if (flags & F_ISDOW)
311 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
312 day = cumdays[month] + day;
314 /* if today or today + offset days */
315 if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
316 return true;
318 /* if number of days left in this year + days to event in next year */
319 if (yrdays - tp->tm_yday + day <= offset)
320 return true;
322 return false;
325 static int
326 getfield(char *p, char **endp, int *flags)
328 int val;
329 char *start;
330 char savech;
333 * note this macro has an arg that isn't used ... it is retained
334 * (it is believed) to make the macro call look more "natural"
335 * and suggest at the call site what is happening.
337 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
338 !isalpha((unsigned char)*p) && *p != '*')
340 val = 0;
341 for (/*EMPTY*/; FLDCHAR(*p); ++p)
342 continue;
343 if (*p == '*') { /* `*' is current month */
344 if (!(*flags & F_ISMONTH)) {
345 *flags |= F_ISMONTH | F_WILDMONTH;
346 *endp = p + 1;
347 return tp->tm_mon + 1;
348 } else {
349 *flags |= F_ISDAY | F_WILDDAY;
350 *endp = p + 1;
351 return 1;
354 if (isdigit((unsigned char)*p)) {
355 val = (int)strtol(p, &p, 10); /* if 0, it's failure */
356 for (/*EMPTY*/; FLDCHAR(*p); ++p)
357 continue;
358 *endp = p;
359 return val;
361 for (start = p; *p != '\0' && isalpha((unsigned char)*p); p++)
362 continue;
364 savech = *p;
365 if (p != start) {
366 *p = '\0';
367 if ((val = getmonth(start)) != 0)
368 *flags |= F_ISMONTH;
369 else if ((val = getday(start)) != 0)
370 *flags |= F_ISDOW;
371 else {
372 *p = savech;
373 *endp = start;
374 return 0;
377 for (*p = savech; FLDCHAR(*p); ++p)
378 continue;
379 *endp = p;
380 return val;
383 static FILE *
384 opencal(void)
386 int fd;
387 int pdes[2];
388 const char **name;
390 /* open up calendar file as stdin */
391 if (fname == NULL) {
392 for (name = defaultnames; *name != NULL; name++) {
393 if (freopen(*name, "rf", stdin) == NULL)
394 continue;
395 else
396 break;
398 if (*name == NULL) {
399 if (doall)
400 return NULL;
401 err(EXIT_FAILURE, "Cannot open calendar file");
403 } else if (freopen(fname, "rf", stdin) == NULL) {
404 if (doall)
405 return NULL;
406 err(EXIT_FAILURE, "Cannot open `%s'", fname);
409 if (pipe(pdes) == -1) {
410 warn("Cannot open pipe");
411 return NULL;
414 switch (fork()) {
415 case -1:
416 /* error */
417 (void)close(pdes[0]);
418 (void)close(pdes[1]);
419 return NULL;
420 case 0:
421 /* child -- stdin already setup, set stdout to pipe input */
422 if (pdes[1] != STDOUT_FILENO) {
423 (void)dup2(pdes[1], STDOUT_FILENO);
424 (void)close(pdes[1]);
426 (void)close(pdes[0]);
427 /* tell CPP to only open regular files */
428 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1) == -1)
429 err(EXIT_FAILURE, "Cannot restrict cpp");
430 cpp_restricted = true;
432 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
433 "-I" _PATH_CALENDARS, NULL);
434 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_CPP);
435 /*NOTREACHED*/
436 default:
437 /* parent -- set stdin to pipe output */
438 (void)dup2(pdes[0], STDIN_FILENO);
439 (void)close(pdes[0]);
440 (void)close(pdes[1]);
442 /* not reading all calendar files, just set output to stdout */
443 if (!doall)
444 return stdout;
447 * Set output to a temporary file, so if no output
448 * don't send mail.
450 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
451 if ((fd = mkstemp(path)) == -1) {
452 warn("Cannot create temporary file");
453 return NULL;
455 return fdopen(fd, "w+");
457 /*NOTREACHED*/
460 static void
461 closecal(FILE *fp)
463 struct stat sbuf;
464 ssize_t nread;
465 int pdes[2];
466 int status;
467 char buf[1024];
469 if (!doall)
470 return;
472 (void)rewind(fp);
473 if (fstat(fileno(fp), &sbuf) == -1 || sbuf.st_size == 0)
474 goto done;
475 if (pipe(pdes) == -1)
476 goto done;
478 switch (fork()) {
479 case -1:
480 /* error */
481 (void)close(pdes[0]);
482 (void)close(pdes[1]);
483 break;
484 case 0:
485 /* child -- set stdin to pipe output */
486 if (pdes[0] != STDIN_FILENO) {
487 (void)dup2(pdes[0], STDIN_FILENO);
488 (void)close(pdes[0]);
490 (void)close(pdes[1]);
491 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
492 "\"Reminder Service\"", "-f", "root", NULL);
493 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_SENDMAIL);
494 /*NOTREACHED*/
495 default:
496 /* parent -- write to pipe input */
497 (void)close(pdes[0]);
499 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
500 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
501 (void)writev(pdes[1], header, 7);
502 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
503 (void)write(pdes[1], buf, (size_t)nread);
504 (void)close(pdes[1]);
505 break;
508 done: (void)fclose(fp);
509 (void)unlink(path);
510 while (wait(&status) != -1)
511 continue;
514 static int
515 getmonth(char *s)
517 const char **p;
519 for (p = months; *p; ++p)
520 if (strncasecmp(s, *p, 3) == 0)
521 return (int)(p - months) + 1;
522 return 0;
525 static int
526 getday(char *s)
528 const char **p;
530 for (p = days; *p; ++p)
531 if (strncasecmp(s, *p, 3) == 0)
532 return (int)(p - days) + 1;
533 return 0;
536 static void
537 atodays(int ch, char *arg, unsigned short *rvp)
539 int u;
541 u = atoi(arg);
542 if (u < 0 || u > 366)
543 warnx("-%c %d out of range 0-366, ignored.", ch, u);
544 else
545 *rvp = u;
548 #define todigit(x) ((x) - '0')
549 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
550 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
552 static void
553 getmmdd(struct tm *ptm, char *ds)
555 bool ok = false;
556 struct tm ttm;
558 ttm = *ptm;
559 ttm.tm_isdst = -1;
561 if (ISDIG2(ds)) {
562 ttm.tm_mon = ATOI2(ds) - 1;
563 ds += 2;
565 if (ISDIG2(ds)) {
566 ttm.tm_mday = ATOI2(ds);
567 ds += 2;
568 ok = true;
570 if (ok) {
571 if (ISDIG2(ds) && ISDIG2(ds + 2)) {
572 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
573 ds += 2;
574 ttm.tm_year += ATOI2(ds);
575 } else if (ISDIG2(ds)) {
576 ttm.tm_year = ATOI2(ds);
577 if (ttm.tm_year < 69)
578 ttm.tm_year += 2000 - TM_YEAR_BASE;
579 else
580 ttm.tm_year += 1900 - TM_YEAR_BASE;
583 if (ok && mktime(&ttm) == -1)
584 ok = false;
586 if (ok)
587 *ptm = ttm;
588 else {
589 warnx("Can't convert `%s' to date, ignored.", ds);
590 usage();
594 __dead
595 static void
596 usage(void)
598 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
599 " [-f fname] [-l days] [-w days]\n", getprogname());
600 exit(1);