calendar.c revision 1.49 1 /* $NetBSD: calendar.c,v 1.49 2012/04/03 12:03:04 matthias 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\
35 The Regents of the University of California. All rights reserved.");
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.49 2012/04/03 12:03:04 matthias 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 <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>
63
64 #include "pathnames.h"
65
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
72
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;
82
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 },
87 };
88 static struct tm *tp;
89 static const int *cumdays;
90 static int offset, yrdays;
91 static char dayname[10];
92
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 },
101 };
102
103 static const char *days[] = {
104 "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
105 };
106
107 static const char *months[] = {
108 "jan", "feb", "mar", "apr", "may", "jun",
109 "jul", "aug", "sep", "oct", "nov", "dec", NULL,
110 };
111
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(FILE **);
121 static void settime(void);
122 static void usage(void) __dead;
123
124 int
125 main(int argc, char **argv)
126 {
127 int ch;
128 const char *caldir;
129
130 (void)setprogname(argv[0]); /* for portability */
131
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);
139 }
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();
160 }
161 }
162 argc -= optind;
163 argv += optind;
164
165 if (argc)
166 usage();
167
168 settime();
169 if (doall) {
170 /*
171 * XXX - This ignores the user's CALENDAR_DIR variable.
172 * Run under user's login shell?
173 */
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);
180 }
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();
187 }
188 return 0;
189 }
190
191 static void
192 cal(void)
193 {
194 bool printing;
195 FILE *fp, *in = NULL;
196 char *line;
197
198 if ((fp = opencal(&in)) == NULL || in == NULL)
199 return;
200 printing = false;
201 while ((line = fparseln(in,
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);
210
211 }
212 closecal(fp);
213 }
214
215 static void
216 settime(void)
217 {
218 time_t now;
219
220 (void)time(&now);
221 tp = localtime(&now);
222 if (datestr)
223 getmmdd(tp, datestr);
224
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];
231 }
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);
236 }
237
238 /*
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)
243 *
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.
247 */
248 static bool
249 isnow(char *endp)
250 {
251 int day;
252 int flags;
253 int month;
254 int v1;
255 int v2;
256
257 flags = 0;
258
259 /* didn't recognize anything, skip it */
260 if (!(v1 = getfield(endp, &endp, &flags)))
261 return false;
262
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;
270 }
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;
286 }
287 }
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;
292 }
293
294 if (flags & F_WILDMONTH && flags & F_WILDDAY)
295 return true;
296
297 if (flags & F_WILDMONTH && flags & F_ISDAY && day == tp->tm_mday)
298 return true;
299
300 if (flags & F_WILDMONTH && flags & F_ISDOW && day == tp->tm_wday + 1)
301 return true;
302
303 if (flags & F_ISMONTH && flags & F_WILDDAY && month == tp->tm_mon + 1)
304 return true;
305
306 if (flags & F_ISMONTH && flags & F_ISDOW && month == tp->tm_mon + 1 &&
307 day == tp->tm_wday + 1)
308 return true;
309
310 if (flags & F_ISDOW)
311 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
312 day = cumdays[month] + day;
313
314 /* if today or today + offset days */
315 if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
316 return true;
317
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;
321
322 return false;
323 }
324
325 static int
326 getfield(char *p, char **endp, int *flags)
327 {
328 int val;
329 char *start;
330 char savech;
331
332 /*
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.
336 */
337 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
338 !isalpha((unsigned char)*p) && *p != '*')
339
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;
352 }
353 }
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;
360 }
361 for (start = p; *p != '\0' && isalpha((unsigned char)*p); p++)
362 continue;
363
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;
375 }
376 }
377 for (*p = savech; FLDCHAR(*p); ++p)
378 continue;
379 *endp = p;
380 return val;
381 }
382
383 static FILE *
384 opencal(FILE **in)
385 {
386 int fd;
387 int pdes[2];
388 const char **name;
389
390 /* open up calendar file as stdin */
391 if (fname == NULL) {
392 for (name = defaultnames; *name != NULL; name++) {
393 if ((fd = open(*name, O_RDONLY)) < 0)
394 continue;
395 else
396 break;
397 }
398 if (*name == NULL) {
399 if (doall)
400 return NULL;
401 err(EXIT_FAILURE, "Cannot open calendar file");
402 }
403 } else if ((fd = open(fname, O_RDONLY)) < 0) {
404 if (doall)
405 return NULL;
406 err(EXIT_FAILURE, "Cannot open `%s'", fname);
407 }
408
409 if (pipe(pdes) == -1) {
410 warn("Cannot open pipe");
411 return NULL;
412 }
413
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 */
422 /* set stdin to calendar file */
423 if (fd != STDIN_FILENO) {
424 (void)dup2(fd, STDIN_FILENO);
425 (void)close(fd);
426 }
427 /* set stdout to pipe input */
428 if (pdes[1] != STDOUT_FILENO) {
429 (void)dup2(pdes[1], STDOUT_FILENO);
430 (void)close(pdes[1]);
431 }
432 (void)close(pdes[0]);
433 /* tell CPP to only open regular files */
434 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1) == -1)
435 err(EXIT_FAILURE, "Cannot restrict cpp");
436 cpp_restricted = true;
437
438 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
439 "-I" _PATH_CALENDARS, NULL);
440 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_CPP);
441 /*NOTREACHED*/
442 default:
443 /* parent -- fdopen *in to pipe output */
444 *in = fdopen(pdes[0], "r");
445 (void)close(pdes[1]);
446
447 /* close calendar file */
448 close(fd);
449
450 /* not reading all calendar files, just set output to stdout */
451 if (!doall)
452 return stdout;
453
454 /*
455 * Set output to a temporary file, so if no output
456 * don't send mail.
457 */
458 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
459 if ((fd = mkstemp(path)) == -1) {
460 warn("Cannot create temporary file");
461 return NULL;
462 }
463 return fdopen(fd, "w+");
464 }
465 /*NOTREACHED*/
466 }
467
468 static void
469 closecal(FILE *fp)
470 {
471 struct stat sbuf;
472 ssize_t nread;
473 int pdes[2];
474 int status;
475 char buf[1024];
476
477 if (!doall)
478 return;
479
480 (void)rewind(fp);
481 if (fstat(fileno(fp), &sbuf) == -1 || sbuf.st_size == 0)
482 goto done;
483 if (pipe(pdes) == -1)
484 goto done;
485
486 switch (fork()) {
487 case -1:
488 /* error */
489 (void)close(pdes[0]);
490 (void)close(pdes[1]);
491 break;
492 case 0:
493 /* child -- set stdin to pipe output */
494 if (pdes[0] != STDIN_FILENO) {
495 (void)dup2(pdes[0], STDIN_FILENO);
496 (void)close(pdes[0]);
497 }
498 (void)close(pdes[1]);
499 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
500 "\"Reminder Service\"", "-f", "root", NULL);
501 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_SENDMAIL);
502 /*NOTREACHED*/
503 default:
504 /* parent -- write to pipe input */
505 (void)close(pdes[0]);
506
507 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
508 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
509 (void)writev(pdes[1], header, 7);
510 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
511 (void)write(pdes[1], buf, (size_t)nread);
512 (void)close(pdes[1]);
513 break;
514 }
515
516 done: (void)fclose(fp);
517 (void)unlink(path);
518 while (wait(&status) != -1)
519 continue;
520 }
521
522 static int
523 getmonth(char *s)
524 {
525 const char **p;
526
527 for (p = months; *p; ++p)
528 if (strncasecmp(s, *p, 3) == 0)
529 return (int)(p - months) + 1;
530 return 0;
531 }
532
533 static int
534 getday(char *s)
535 {
536 const char **p;
537
538 for (p = days; *p; ++p)
539 if (strncasecmp(s, *p, 3) == 0)
540 return (int)(p - days) + 1;
541 return 0;
542 }
543
544 static void
545 atodays(int ch, char *arg, unsigned short *rvp)
546 {
547 int u;
548
549 u = atoi(arg);
550 if (u < 0 || u > 366)
551 warnx("-%c %d out of range 0-366, ignored.", ch, u);
552 else
553 *rvp = u;
554 }
555
556 #define todigit(x) ((x) - '0')
557 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
558 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
559
560 static void
561 getmmdd(struct tm *ptm, char *ds)
562 {
563 bool ok = false;
564 struct tm ttm;
565
566 ttm = *ptm;
567 ttm.tm_isdst = -1;
568
569 if (ISDIG2(ds)) {
570 ttm.tm_mon = ATOI2(ds) - 1;
571 ds += 2;
572 }
573 if (ISDIG2(ds)) {
574 ttm.tm_mday = ATOI2(ds);
575 ds += 2;
576 ok = true;
577 }
578 if (ok) {
579 if (ISDIG2(ds) && ISDIG2(ds + 2)) {
580 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
581 ds += 2;
582 ttm.tm_year += ATOI2(ds);
583 } else if (ISDIG2(ds)) {
584 ttm.tm_year = ATOI2(ds);
585 if (ttm.tm_year < 69)
586 ttm.tm_year += 2000 - TM_YEAR_BASE;
587 else
588 ttm.tm_year += 1900 - TM_YEAR_BASE;
589 }
590 }
591 if (ok && mktime(&ttm) == -1)
592 ok = false;
593
594 if (ok)
595 *ptm = ttm;
596 else {
597 warnx("Can't convert `%s' to date, ignored.", ds);
598 usage();
599 }
600 }
601
602 __dead
603 static void
604 usage(void)
605 {
606 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
607 " [-f fname] [-l days] [-w days]\n", getprogname());
608 exit(1);
609 }
610