calendar.c revision 1.35 1 /* $NetBSD: calendar.c,v 1.35 2004/12/06 20:38:43 jwise Exp $ */
2
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 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\n\
35 The Regents of the University of California. All rights reserved.\n");
36 #endif /* not lint */
37
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.35 2004/12/06 20:38:43 jwise Exp $");
43 #endif /* not lint */
44
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>
50
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <pwd.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <time.h>
60 #include <tzfile.h>
61 #include <unistd.h>
62
63 #include "pathnames.h"
64
65 #ifndef TRUE
66 #define TRUE 1
67 #endif
68 #ifndef FALSE
69 #define FALSE 0
70 #endif
71
72 static unsigned short lookahead = 1, weekend = 2;
73 static char *fname = NULL, *datestr = NULL;
74 static char *defaultnames[] = {"calendar", ".calendar", "/etc/calendar", NULL};
75 static struct passwd *pw;
76 static int doall;
77 static char path[MAXPATHLEN + 1];
78 static int cpp_restricted = 0;
79
80 /* 1-based month, 0-based days, cumulative */
81 static int daytab[][14] = {
82 { 0, -1, 30, 58, 89, 119, 150, 180, 211, 242, 272, 303, 333, 364 },
83 { 0, -1, 30, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
84 };
85 static struct tm *tp;
86 static int *cumdays, offset, yrdays;
87 static char dayname[10];
88
89 static struct iovec header[] = {
90 { "From: ", 6 },
91 { NULL, 0 },
92 { " (Reminder Service)\nTo: ", 24 },
93 { NULL, 0 },
94 { "\nSubject: ", 10 },
95 { NULL, 0 },
96 { "'s Calendar\nPrecedence: bulk\n\n", 30 },
97 };
98
99 static char *days[] = {
100 "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
101 };
102
103 static char *months[] = {
104 "jan", "feb", "mar", "apr", "may", "jun",
105 "jul", "aug", "sep", "oct", "nov", "dec", NULL,
106 };
107
108 int main(int, char **);
109
110 static void atodays(int, char *, unsigned short *);
111 static void cal(void);
112 static void closecal(FILE *);
113 static int getday(char *);
114 static int getfield(char *, char **, int *);
115 static void getmmdd(struct tm *, char *);
116 static int getmonth(char *);
117 static int isnow(char *);
118 static FILE *opencal(void);
119 static void settime(void);
120 static void usage(void) __attribute__((__noreturn__));
121
122 int
123 main(argc, argv)
124 int argc;
125 char *argv[];
126 {
127 int ch;
128 const char *caldir;
129
130 while ((ch = getopt(argc, argv, "-ad:f:l:w:x")) != -1)
131 switch (ch) {
132 case '-': /* backward contemptible */
133 case 'a':
134 if (getuid()) {
135 errno = EPERM;
136 err(1, NULL);
137 }
138 doall = 1;
139 break;
140 case 'd':
141 datestr = optarg;
142 break;
143 case 'f':
144 fname = optarg;
145 break;
146 case 'l':
147 atodays(ch, optarg, &lookahead);
148 break;
149 case 'w':
150 atodays(ch, optarg, &weekend);
151 break;
152 case 'x':
153 cpp_restricted = 1;
154 case '?':
155 default:
156 usage();
157 }
158 argc -= optind;
159 argv += optind;
160
161 if (argc)
162 usage();
163
164 settime();
165 if (doall) {
166 while ((pw = getpwent()) != NULL) {
167 (void)setegid(pw->pw_gid);
168 (void)seteuid(pw->pw_uid);
169 if (!chdir(pw->pw_dir))
170 cal();
171 (void)seteuid(0);
172 }
173 } else if ((caldir = getenv("CALENDAR_DIR")) != NULL) {
174 if(!chdir(caldir))
175 cal();
176 } else {
177 if (((pw = getpwuid(geteuid())) != NULL) && !chdir(pw->pw_dir))
178 cal();
179 }
180 exit(0);
181 }
182
183 static void
184 cal(void)
185 {
186 int printing;
187 FILE *fp;
188 char *line;
189
190 if ((fp = opencal()) == NULL)
191 return;
192 while ((line = fparseln(stdin, NULL, NULL, NULL, FPARSELN_UNESCCOMM))
193 != NULL) {
194 if (line[0] == '\0')
195 continue;
196 if (line[0] != '\t')
197 printing = isnow(line) ? 1 : 0;
198 if (printing)
199 (void)fprintf(fp, "%s\n", line);
200 free(line);
201
202 }
203 closecal(fp);
204 }
205
206
207 static void
208 settime(void)
209 {
210 time_t now;
211
212 (void)time(&now);
213 tp = localtime(&now);
214 if (datestr) {
215 getmmdd(tp, datestr);
216 }
217 if (isleap(tp->tm_year + TM_YEAR_BASE)) {
218 yrdays = DAYSPERLYEAR;
219 cumdays = daytab[1];
220 } else {
221 yrdays = DAYSPERNYEAR;
222 cumdays = daytab[0];
223 }
224 /* Friday displays Monday's events */
225 offset = tp->tm_wday == 5 ? lookahead + weekend : lookahead;
226 header[5].iov_base = dayname;
227 header[5].iov_len = strftime(dayname, sizeof(dayname), "%A", tp);
228 }
229
230 /*
231 * Possible date formats include any combination of:
232 * 3-charmonth (January, Jan, Jan)
233 * 3-charweekday (Friday, Monday, mon.)
234 * numeric month or day (1, 2, 04)
235 *
236 * Any character may separate them, or they may not be separated. Any line,
237 * following a line that is matched, that starts with "whitespace", is shown
238 * along with the matched line.
239 */
240 static int
241 isnow(endp)
242 char *endp;
243 {
244 int day, flags, month, v1, v2;
245
246 #define F_ISMONTH 0x01
247 #define F_ISDAY 0x02
248 #define F_WILDMONTH 0x04
249 #define F_WILDDAY 0x08
250
251 flags = 0;
252
253 /* didn't recognize anything, skip it */
254 if (!(v1 = getfield(endp, &endp, &flags)))
255 return (0);
256 if (flags & F_ISDAY || v1 > 12) {
257 /* found a day */
258 day = v1;
259 month = tp->tm_mon + 1;
260 } else if (flags & F_ISMONTH) {
261 month = v1;
262 /* if no recognizable day, assume the first */
263 if (!(day = getfield(endp, &endp, &flags)))
264 day = 1;
265 } else {
266 v2 = getfield(endp, &endp, &flags);
267 if (flags & F_ISMONTH) {
268 day = v1;
269 month = v2;
270 } else {
271 /* F_ISDAY set, v2 > 12, or no way to tell */
272 month = v1;
273 /* if no recognizable day, assume the first */
274 day = v2 ? v2 : 1;
275 }
276 }
277
278 if (flags & (F_WILDMONTH|F_WILDDAY))
279 return (1);
280
281 if ((flags & (F_WILDMONTH|F_ISDAY)) && (day == tp->tm_mday))
282 return (1);
283
284 if ((flags & (F_ISMONTH|F_WILDDAY)) && (month == tp->tm_mon + 1))
285 return (1);
286
287 if (flags & F_ISDAY)
288 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
289 day = cumdays[month] + day;
290
291 /* if today or today + offset days */
292 if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
293 return (1);
294 /* if number of days left in this year + days to event in next year */
295 if (yrdays - tp->tm_yday + day <= offset)
296 return (1);
297 return (0);
298 }
299
300 static int
301 getfield(p, endp, flags)
302 char *p, **endp;
303 int *flags;
304 {
305 int val;
306 char *start, savech;
307
308 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
309 !isalpha((unsigned char)*p) && *p != '*')
310
311 for (; FLDCHAR(*p); ++p)
312 continue;
313 if (*p == '*') { /* `*' is current month */
314 if (!(*flags & F_ISMONTH)) {
315 *flags |= F_ISMONTH|F_WILDMONTH;
316 *endp = p+1;
317 return (tp->tm_mon + 1);
318 } else {
319 *flags |= F_ISDAY|F_WILDDAY;
320 *endp = p+1;
321 return (1);
322 }
323 }
324 if (isdigit((unsigned char)*p)) {
325 val = strtol(p, &p, 10); /* if 0, it's failure */
326 for (; FLDCHAR(*p); ++p)
327 continue;
328 *endp = p;
329 return (val);
330 }
331 for (start = p; *p != '\0' && isalpha((unsigned char)*++p);)
332 continue;
333 savech = *p;
334 *p = '\0';
335 if ((val = getmonth(start)) != 0) {
336 *flags |= F_ISMONTH;
337 } else if ((val = getday(start)) != 0) {
338 *flags |= F_ISDAY;
339 } else {
340 *p = savech;
341 return (0);
342 }
343 for (*p = savech; FLDCHAR(*p); ++p)
344 continue;
345 *endp = p;
346 return (val);
347 }
348
349 static FILE *
350 opencal(void)
351 {
352 int fd, pdes[2];
353 char **name;
354
355 /* open up calendar file as stdin */
356 if (fname == NULL) {
357 for (name = defaultnames; *name != NULL; name++) {
358 if (!freopen(*name, "rf", stdin))
359 continue;
360 else
361 break;
362 }
363 if (*name == NULL) {
364 if (doall)
365 return (NULL);
366 err(1, "Cannot open calendar file");
367 }
368 } else if (!freopen(fname, "rf", stdin)) {
369 if (doall)
370 return (NULL);
371 err(1, "Cannot open `%s'", fname);
372 }
373
374 if (pipe(pdes) < 0) {
375 warn("Cannot open pipe");
376 return (NULL);
377 }
378
379 switch (fork()) {
380 case -1: /* error */
381 (void)close(pdes[0]);
382 (void)close(pdes[1]);
383 return (NULL);
384 case 0:
385 /* child -- stdin already setup, set stdout to pipe input */
386 if (pdes[1] != STDOUT_FILENO) {
387 (void)dup2(pdes[1], STDOUT_FILENO);
388 (void)close(pdes[1]);
389 }
390 (void)close(pdes[0]);
391 /* tell CPP to only open regular files */
392 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1))
393 err(1, "Cannot restrict cpp");
394 cpp_restricted = 1;
395
396 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
397 "-I" _PATH_CALENDARS, NULL);
398 err(1, "Cannot exec `%s'", _PATH_CPP);
399 /*NOTREACHED*/
400 }
401
402 /* parent -- set stdin to pipe output */
403 (void)dup2(pdes[0], STDIN_FILENO);
404 (void)close(pdes[0]);
405 (void)close(pdes[1]);
406
407 /* not reading all calendar files, just set output to stdout */
408 if (!doall)
409 return (stdout);
410
411 /* set output to a temporary file, so if no output don't send mail */
412 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
413 if ((fd = mkstemp(path)) < 0) {
414 warn("Cannot create temporary file");
415 return (NULL);
416 }
417 return (fdopen(fd, "w+"));
418 }
419
420 static void
421 closecal(fp)
422 FILE *fp;
423 {
424 struct stat sbuf;
425 int nread, pdes[2], status;
426 char buf[1024];
427
428 if (!doall)
429 return;
430
431 (void)rewind(fp);
432 if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
433 goto done;
434 if (pipe(pdes) < 0)
435 goto done;
436 switch (fork()) {
437 case -1: /* error */
438 (void)close(pdes[0]);
439 (void)close(pdes[1]);
440 goto done;
441 case 0:
442 /* child -- set stdin to pipe output */
443 if (pdes[0] != STDIN_FILENO) {
444 (void)dup2(pdes[0], STDIN_FILENO);
445 (void)close(pdes[0]);
446 }
447 (void)close(pdes[1]);
448 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
449 "\"Reminder Service\"", "-f", "root", NULL);
450 err(1, "Cannot exec `%s'", _PATH_SENDMAIL);
451 /*NOTREACHED*/
452 }
453 /* parent -- write to pipe input */
454 (void)close(pdes[0]);
455
456 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
457 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
458 writev(pdes[1], header, 7);
459 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
460 (void)write(pdes[1], buf, nread);
461 (void)close(pdes[1]);
462
463 done: (void)fclose(fp);
464 (void)unlink(path);
465 while (wait(&status) >= 0)
466 continue;
467 }
468
469 static int
470 getmonth(s)
471 char *s;
472 {
473 char **p;
474
475 for (p = months; *p; ++p)
476 if (!strncasecmp(s, *p, 3))
477 return ((p - months) + 1);
478 return (0);
479 }
480
481 static int
482 getday(s)
483 char *s;
484 {
485 char **p;
486
487 for (p = days; *p; ++p)
488 if (!strncasecmp(s, *p, 3))
489 return ((p - days) + 1);
490 return (0);
491 }
492
493 static void
494 atodays(int ch, char *optarg, unsigned short *days)
495 {
496 int u;
497
498 u = atoi(optarg);
499 if ((u < 0) || (u > 366)) {
500 warnx("-%c %d out of range 0-366, ignored.", ch, u);
501 } else {
502 *days = u;
503 }
504 }
505
506 #define todigit(x) ((x) - '0')
507 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
508 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
509
510 static void
511 getmmdd(struct tm *tp, char *ds)
512 {
513 int ok = FALSE;
514 struct tm ttm;
515
516 ttm = *tp;
517 ttm.tm_isdst = -1;
518
519 if (ISDIG2(ds)) {
520 ttm.tm_mon = ATOI2(ds) - 1;
521 ds += 2;
522 }
523
524 if (ISDIG2(ds)) {
525 ttm.tm_mday = ATOI2(ds);
526 ds += 2;
527
528 ok = TRUE;
529 }
530
531 if (ok) {
532 if (ISDIG2(ds) && ISDIG2(ds + 2)) {
533 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
534 ds += 2;
535 ttm.tm_year += ATOI2(ds);
536 } else if (ISDIG2(ds)) {
537 ttm.tm_year = ATOI2(ds);
538 if (ttm.tm_year < 69)
539 ttm.tm_year += 2000 - TM_YEAR_BASE;
540 else
541 ttm.tm_year += 1900 - TM_YEAR_BASE;
542 }
543 }
544
545 if (ok && (mktime(&ttm) < 0)) {
546 ok = FALSE;
547 }
548
549 if (ok) {
550 *tp = ttm;
551 } else {
552 warnx("Can't convert `%s' to date, ignored.", ds);
553 usage();
554 }
555 }
556
557 static void
558 usage(void)
559 {
560 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
561 " [-f fname] [-l days] [-w days]\n", getprogname());
562 exit(1);
563 }
564