calendar.c revision 1.45 1 /* $NetBSD: calendar.c,v 1.45 2008/04/09 17:47:53 christos 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.45 2008/04/09 17:47:53 christos 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 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;
75
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 },
80 };
81 static struct tm *tp;
82 static const int *cumdays;
83 static int offset, yrdays;
84 static char dayname[10];
85
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 },
94 };
95
96 static const char *days[] = {
97 "sun", "mon", "tue", "wed", "thu", "fri", "sat", NULL,
98 };
99
100 static const char *months[] = {
101 "jan", "feb", "mar", "apr", "may", "jun",
102 "jul", "aug", "sep", "oct", "nov", "dec", NULL,
103 };
104
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;
116
117 int
118 main(int argc, char **argv)
119 {
120 int ch;
121 const char *caldir;
122
123 (void)setprogname(argv[0]); /* for portability */
124
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);
132 }
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();
153 }
154 }
155 argc -= optind;
156 argv += optind;
157
158 if (argc)
159 usage();
160
161 settime();
162 if (doall) {
163 /*
164 * XXX - This ignores the user's CALENDAR_DIR variable.
165 * Run under user's login shell?
166 */
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);
173 }
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();
180 }
181 return 0;
182 }
183
184 static void
185 cal(void)
186 {
187 bool printing;
188 FILE *fp;
189 char *line;
190
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);
203
204 }
205 closecal(fp);
206 }
207
208 static void
209 settime(void)
210 {
211 time_t now;
212
213 (void)time(&now);
214 tp = localtime(&now);
215 if (datestr)
216 getmmdd(tp, datestr);
217
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];
224 }
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);
229 }
230
231 /*
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)
236 *
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.
240 */
241 static bool
242 isnow(char *endp)
243 {
244 int day;
245 int flags;
246 int month;
247 int v1;
248 int v2;
249
250 #define F_ISMONTH 0x01
251 #define F_ISDAY 0x02
252 #define F_WILDMONTH 0x04
253 #define F_WILDDAY 0x08
254
255 flags = 0;
256
257 /* didn't recognize anything, skip it */
258 if (!(v1 = getfield(endp, &endp, &flags)))
259 return false;
260
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;
268 }
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;
284 }
285 }
286 if (flags & F_WILDMONTH && flags & F_WILDDAY)
287 return true;
288
289 if (flags & F_WILDMONTH && flags & F_ISDAY && day == tp->tm_mday)
290 return true;
291
292 if (flags & F_ISMONTH && flags & F_WILDDAY && month == tp->tm_mon + 1)
293 return true;
294
295 if (flags & F_ISDAY)
296 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
297 day = cumdays[month] + day;
298
299 /* if today or today + offset days */
300 if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
301 return true;
302
303 /* if number of days left in this year + days to event in next year */
304 if (yrdays - tp->tm_yday + day <= offset)
305 return true;
306
307 return false;
308 }
309
310 static int
311 getfield(char *p, char **endp, int *flags)
312 {
313 int val;
314 char *start;
315 char savech;
316
317 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
318 !isalpha((unsigned char)*p) && *p != '*')
319
320 for (/*EMPTY*/; FLDCHAR(*p); ++p)
321 continue;
322 if (*p == '*') { /* `*' is current month */
323 if (!(*flags & F_ISMONTH)) {
324 *flags |= F_ISMONTH | F_WILDMONTH;
325 *endp = p + 1;
326 return tp->tm_mon + 1;
327 } else {
328 *flags |= F_ISDAY | F_WILDDAY;
329 *endp = p + 1;
330 return 1;
331 }
332 }
333 if (isdigit((unsigned char)*p)) {
334 val = (int)strtol(p, &p, 10); /* if 0, it's failure */
335 for (/*EMPTY*/; FLDCHAR(*p); ++p)
336 continue;
337 *endp = p;
338 return val;
339 }
340 for (start = p; *p != '\0' && isalpha((unsigned char)*++p); /*EMPTY*/)
341 continue;
342 savech = *p;
343 *p = '\0';
344 if ((val = getmonth(start)) != 0)
345 *flags |= F_ISMONTH;
346 else if ((val = getday(start)) != 0)
347 *flags |= F_ISDAY;
348 else {
349 *p = savech;
350 return 0;
351 }
352 for (*p = savech; FLDCHAR(*p); ++p)
353 continue;
354 *endp = p;
355 return val;
356 }
357
358 static FILE *
359 opencal(void)
360 {
361 int fd;
362 int pdes[2];
363 const char **name;
364
365 /* open up calendar file as stdin */
366 if (fname == NULL) {
367 for (name = defaultnames; *name != NULL; name++) {
368 if (freopen(*name, "rf", stdin) == NULL)
369 continue;
370 else
371 break;
372 }
373 if (*name == NULL) {
374 if (doall)
375 return NULL;
376 err(EXIT_FAILURE, "Cannot open calendar file");
377 }
378 } else if (freopen(fname, "rf", stdin) == NULL) {
379 if (doall)
380 return NULL;
381 err(EXIT_FAILURE, "Cannot open `%s'", fname);
382 }
383
384 if (pipe(pdes) == -1) {
385 warn("Cannot open pipe");
386 return NULL;
387 }
388
389 switch (fork()) {
390 case -1:
391 /* error */
392 (void)close(pdes[0]);
393 (void)close(pdes[1]);
394 return NULL;
395 case 0:
396 /* child -- stdin already setup, set stdout to pipe input */
397 if (pdes[1] != STDOUT_FILENO) {
398 (void)dup2(pdes[1], STDOUT_FILENO);
399 (void)close(pdes[1]);
400 }
401 (void)close(pdes[0]);
402 /* tell CPP to only open regular files */
403 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1) == -1)
404 err(EXIT_FAILURE, "Cannot restrict cpp");
405 cpp_restricted = true;
406
407 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
408 "-I" _PATH_CALENDARS, NULL);
409 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_CPP);
410 /*NOTREACHED*/
411 default:
412 /* parent -- set stdin to pipe output */
413 (void)dup2(pdes[0], STDIN_FILENO);
414 (void)close(pdes[0]);
415 (void)close(pdes[1]);
416
417 /* not reading all calendar files, just set output to stdout */
418 if (!doall)
419 return stdout;
420
421 /*
422 * Set output to a temporary file, so if no output
423 * don't send mail.
424 */
425 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
426 if ((fd = mkstemp(path)) == -1) {
427 warn("Cannot create temporary file");
428 return NULL;
429 }
430 return fdopen(fd, "w+");
431 }
432 /*NOTREACHED*/
433 }
434
435 static void
436 closecal(FILE *fp)
437 {
438 struct stat sbuf;
439 ssize_t nread;
440 int pdes[2];
441 int status;
442 char buf[1024];
443
444 if (!doall)
445 return;
446
447 (void)rewind(fp);
448 if (fstat(fileno(fp), &sbuf) == -1 || sbuf.st_size == 0)
449 goto done;
450 if (pipe(pdes) == -1)
451 goto done;
452
453 switch (fork()) {
454 case -1:
455 /* error */
456 (void)close(pdes[0]);
457 (void)close(pdes[1]);
458 break;
459 case 0:
460 /* child -- set stdin to pipe output */
461 if (pdes[0] != STDIN_FILENO) {
462 (void)dup2(pdes[0], STDIN_FILENO);
463 (void)close(pdes[0]);
464 }
465 (void)close(pdes[1]);
466 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
467 "\"Reminder Service\"", "-f", "root", NULL);
468 err(EXIT_FAILURE, "Cannot exec `%s'", _PATH_SENDMAIL);
469 /*NOTREACHED*/
470 default:
471 /* parent -- write to pipe input */
472 (void)close(pdes[0]);
473
474 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
475 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
476 (void)writev(pdes[1], header, 7);
477 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
478 (void)write(pdes[1], buf, (size_t)nread);
479 (void)close(pdes[1]);
480 break;
481 }
482
483 done: (void)fclose(fp);
484 (void)unlink(path);
485 while (wait(&status) != -1)
486 continue;
487 }
488
489 static int
490 getmonth(char *s)
491 {
492 const char **p;
493
494 for (p = months; *p; ++p)
495 if (strncasecmp(s, *p, 3) == 0)
496 return (int)(p - months) + 1;
497 return 0;
498 }
499
500 static int
501 getday(char *s)
502 {
503 const char **p;
504
505 for (p = days; *p; ++p)
506 if (strncasecmp(s, *p, 3) == 0)
507 return (int)(p - days) + 1;
508 return 0;
509 }
510
511 static void
512 atodays(int ch, char *arg, unsigned short *rvp)
513 {
514 int u;
515
516 u = atoi(arg);
517 if (u < 0 || u > 366)
518 warnx("-%c %d out of range 0-366, ignored.", ch, u);
519 else
520 *rvp = u;
521 }
522
523 #define todigit(x) ((x) - '0')
524 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
525 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
526
527 static void
528 getmmdd(struct tm *ptm, char *ds)
529 {
530 bool ok = false;
531 struct tm ttm;
532
533 ttm = *ptm;
534 ttm.tm_isdst = -1;
535
536 if (ISDIG2(ds)) {
537 ttm.tm_mon = ATOI2(ds) - 1;
538 ds += 2;
539 }
540 if (ISDIG2(ds)) {
541 ttm.tm_mday = ATOI2(ds);
542 ds += 2;
543 ok = true;
544 }
545 if (ok) {
546 if (ISDIG2(ds) && ISDIG2(ds + 2)) {
547 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
548 ds += 2;
549 ttm.tm_year += ATOI2(ds);
550 } else if (ISDIG2(ds)) {
551 ttm.tm_year = ATOI2(ds);
552 if (ttm.tm_year < 69)
553 ttm.tm_year += 2000 - TM_YEAR_BASE;
554 else
555 ttm.tm_year += 1900 - TM_YEAR_BASE;
556 }
557 }
558 if (ok && mktime(&ttm) == -1)
559 ok = false;
560
561 if (ok)
562 *ptm = ttm;
563 else {
564 warnx("Can't convert `%s' to date, ignored.", ds);
565 usage();
566 }
567 }
568
569 __dead
570 static void
571 usage(void)
572 {
573 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
574 " [-f fname] [-l days] [-w days]\n", getprogname());
575 exit(1);
576 }
577