calendar.c revision 1.38 1 /* $NetBSD: calendar.c,v 1.38 2005/07/15 09:45:04 wiz 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.38 2005/07/15 09:45:04 wiz 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", _PATH_SYSTEM_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 break;
155 case '?':
156 default:
157 usage();
158 }
159 argc -= optind;
160 argv += optind;
161
162 if (argc)
163 usage();
164
165 settime();
166 if (doall) {
167 while ((pw = getpwent()) != NULL) {
168 (void)setegid(pw->pw_gid);
169 (void)seteuid(pw->pw_uid);
170 if (!chdir(pw->pw_dir))
171 cal();
172 (void)seteuid(0);
173 }
174 } else if ((caldir = getenv("CALENDAR_DIR")) != NULL) {
175 if(!chdir(caldir))
176 cal();
177 } else {
178 if (((pw = getpwuid(geteuid())) != NULL) && !chdir(pw->pw_dir))
179 cal();
180 }
181 exit(0);
182 }
183
184 static void
185 cal(void)
186 {
187 int printing = 0;
188 FILE *fp;
189 char *line;
190
191 if ((fp = opencal()) == NULL)
192 return;
193 while ((line = fparseln(stdin, NULL, NULL, NULL, FPARSELN_UNESCCOMM))
194 != NULL) {
195 if (line[0] == '\0')
196 continue;
197 if (line[0] != '\t')
198 printing = isnow(line) ? 1 : 0;
199 if (printing)
200 (void)fprintf(fp, "%s\n", line);
201 free(line);
202
203 }
204 closecal(fp);
205 }
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 int
242 isnow(endp)
243 char *endp;
244 {
245 int day, flags, month, v1, v2;
246
247 #define F_ISMONTH 0x01
248 #define F_ISDAY 0x02
249 #define F_WILDMONTH 0x04
250 #define F_WILDDAY 0x08
251
252 flags = 0;
253
254 /* didn't recognize anything, skip it */
255 if (!(v1 = getfield(endp, &endp, &flags)))
256 return (0);
257 if (flags & F_ISDAY || v1 > 12) {
258 /* found a day */
259 day = v1;
260 month = tp->tm_mon + 1;
261 } else if (flags & F_ISMONTH) {
262 month = v1;
263 /* if no recognizable day, assume the first */
264 if (!(day = getfield(endp, &endp, &flags)))
265 day = 1;
266 } else {
267 v2 = getfield(endp, &endp, &flags);
268 if (flags & F_ISMONTH) {
269 day = v1;
270 month = v2;
271 } else {
272 /* F_ISDAY set, v2 > 12, or no way to tell */
273 month = v1;
274 /* if no recognizable day, assume the first */
275 day = v2 ? v2 : 1;
276 }
277 }
278
279 if (flags & (F_WILDMONTH|F_WILDDAY))
280 return (1);
281
282 if ((flags & (F_WILDMONTH|F_ISDAY)) && (day == tp->tm_mday))
283 return (1);
284
285 if ((flags & (F_ISMONTH|F_WILDDAY)) && (month == tp->tm_mon + 1))
286 return (1);
287
288 if (flags & F_ISDAY)
289 day = tp->tm_mday + (((day - 1) - tp->tm_wday + 7) % 7);
290 day = cumdays[month] + day;
291
292 /* if today or today + offset days */
293 if (day >= tp->tm_yday && day <= tp->tm_yday + offset)
294 return (1);
295 /* if number of days left in this year + days to event in next year */
296 if (yrdays - tp->tm_yday + day <= offset)
297 return (1);
298 return (0);
299 }
300
301 static int
302 getfield(p, endp, flags)
303 char *p, **endp;
304 int *flags;
305 {
306 int val;
307 char *start, savech;
308
309 #define FLDCHAR(a) (*p != '\0' && !isdigit((unsigned char)*p) && \
310 !isalpha((unsigned char)*p) && *p != '*')
311
312 for (; FLDCHAR(*p); ++p)
313 continue;
314 if (*p == '*') { /* `*' is current month */
315 if (!(*flags & F_ISMONTH)) {
316 *flags |= F_ISMONTH|F_WILDMONTH;
317 *endp = p+1;
318 return (tp->tm_mon + 1);
319 } else {
320 *flags |= F_ISDAY|F_WILDDAY;
321 *endp = p+1;
322 return (1);
323 }
324 }
325 if (isdigit((unsigned char)*p)) {
326 val = strtol(p, &p, 10); /* if 0, it's failure */
327 for (; FLDCHAR(*p); ++p)
328 continue;
329 *endp = p;
330 return (val);
331 }
332 for (start = p; *p != '\0' && isalpha((unsigned char)*++p);)
333 continue;
334 savech = *p;
335 *p = '\0';
336 if ((val = getmonth(start)) != 0) {
337 *flags |= F_ISMONTH;
338 } else if ((val = getday(start)) != 0) {
339 *flags |= F_ISDAY;
340 } else {
341 *p = savech;
342 return (0);
343 }
344 for (*p = savech; FLDCHAR(*p); ++p)
345 continue;
346 *endp = p;
347 return (val);
348 }
349
350 static FILE *
351 opencal(void)
352 {
353 int fd, pdes[2];
354 char **name;
355
356 /* open up calendar file as stdin */
357 if (fname == NULL) {
358 for (name = defaultnames; *name != NULL; name++) {
359 if (!freopen(*name, "rf", stdin))
360 continue;
361 else
362 break;
363 }
364 if (*name == NULL) {
365 if (doall)
366 return (NULL);
367 err(1, "Cannot open calendar file");
368 }
369 } else if (!freopen(fname, "rf", stdin)) {
370 if (doall)
371 return (NULL);
372 err(1, "Cannot open `%s'", fname);
373 }
374
375 if (pipe(pdes) < 0) {
376 warn("Cannot open pipe");
377 return (NULL);
378 }
379
380 switch (fork()) {
381 case -1: /* error */
382 (void)close(pdes[0]);
383 (void)close(pdes[1]);
384 return (NULL);
385 case 0:
386 /* child -- stdin already setup, set stdout to pipe input */
387 if (pdes[1] != STDOUT_FILENO) {
388 (void)dup2(pdes[1], STDOUT_FILENO);
389 (void)close(pdes[1]);
390 }
391 (void)close(pdes[0]);
392 /* tell CPP to only open regular files */
393 if(!cpp_restricted && setenv("CPP_RESTRICTED", "", 1))
394 err(1, "Cannot restrict cpp");
395 cpp_restricted = 1;
396
397 (void)execl(_PATH_CPP, "cpp", "-traditional", "-P", "-I.",
398 "-I" _PATH_CALENDARS, NULL);
399 err(1, "Cannot exec `%s'", _PATH_CPP);
400 /*NOTREACHED*/
401 }
402
403 /* parent -- set stdin to pipe output */
404 (void)dup2(pdes[0], STDIN_FILENO);
405 (void)close(pdes[0]);
406 (void)close(pdes[1]);
407
408 /* not reading all calendar files, just set output to stdout */
409 if (!doall)
410 return (stdout);
411
412 /* set output to a temporary file, so if no output don't send mail */
413 (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
414 if ((fd = mkstemp(path)) < 0) {
415 warn("Cannot create temporary file");
416 return (NULL);
417 }
418 return (fdopen(fd, "w+"));
419 }
420
421 static void
422 closecal(fp)
423 FILE *fp;
424 {
425 struct stat sbuf;
426 int nread, pdes[2], status;
427 char buf[1024];
428
429 if (!doall)
430 return;
431
432 (void)rewind(fp);
433 if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
434 goto done;
435 if (pipe(pdes) < 0)
436 goto done;
437 switch (fork()) {
438 case -1: /* error */
439 (void)close(pdes[0]);
440 (void)close(pdes[1]);
441 goto done;
442 case 0:
443 /* child -- set stdin to pipe output */
444 if (pdes[0] != STDIN_FILENO) {
445 (void)dup2(pdes[0], STDIN_FILENO);
446 (void)close(pdes[0]);
447 }
448 (void)close(pdes[1]);
449 (void)execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
450 "\"Reminder Service\"", "-f", "root", NULL);
451 err(1, "Cannot exec `%s'", _PATH_SENDMAIL);
452 /*NOTREACHED*/
453 }
454 /* parent -- write to pipe input */
455 (void)close(pdes[0]);
456
457 header[1].iov_base = header[3].iov_base = (void *)pw->pw_name;
458 header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
459 writev(pdes[1], header, 7);
460 while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
461 (void)write(pdes[1], buf, nread);
462 (void)close(pdes[1]);
463
464 done: (void)fclose(fp);
465 (void)unlink(path);
466 while (wait(&status) >= 0)
467 continue;
468 }
469
470 static int
471 getmonth(s)
472 char *s;
473 {
474 char **p;
475
476 for (p = months; *p; ++p)
477 if (!strncasecmp(s, *p, 3))
478 return ((p - months) + 1);
479 return (0);
480 }
481
482 static int
483 getday(s)
484 char *s;
485 {
486 char **p;
487
488 for (p = days; *p; ++p)
489 if (!strncasecmp(s, *p, 3))
490 return ((p - days) + 1);
491 return (0);
492 }
493
494 static void
495 atodays(int ch, char *optarg, unsigned short *days)
496 {
497 int u;
498
499 u = atoi(optarg);
500 if ((u < 0) || (u > 366)) {
501 warnx("-%c %d out of range 0-366, ignored.", ch, u);
502 } else {
503 *days = u;
504 }
505 }
506
507 #define todigit(x) ((x) - '0')
508 #define ATOI2(x) (todigit((x)[0]) * 10 + todigit((x)[1]))
509 #define ISDIG2(x) (isdigit((unsigned char)(x)[0]) && isdigit((unsigned char)(x)[1]))
510
511 static void
512 getmmdd(struct tm *tp, char *ds)
513 {
514 int ok = FALSE;
515 struct tm ttm;
516
517 ttm = *tp;
518 ttm.tm_isdst = -1;
519
520 if (ISDIG2(ds)) {
521 ttm.tm_mon = ATOI2(ds) - 1;
522 ds += 2;
523 }
524
525 if (ISDIG2(ds)) {
526 ttm.tm_mday = ATOI2(ds);
527 ds += 2;
528
529 ok = TRUE;
530 }
531
532 if (ok) {
533 if (ISDIG2(ds) && ISDIG2(ds + 2)) {
534 ttm.tm_year = ATOI2(ds) * 100 - TM_YEAR_BASE;
535 ds += 2;
536 ttm.tm_year += ATOI2(ds);
537 } else if (ISDIG2(ds)) {
538 ttm.tm_year = ATOI2(ds);
539 if (ttm.tm_year < 69)
540 ttm.tm_year += 2000 - TM_YEAR_BASE;
541 else
542 ttm.tm_year += 1900 - TM_YEAR_BASE;
543 }
544 }
545
546 if (ok && (mktime(&ttm) < 0)) {
547 ok = FALSE;
548 }
549
550 if (ok) {
551 *tp = ttm;
552 } else {
553 warnx("Can't convert `%s' to date, ignored.", ds);
554 usage();
555 }
556 }
557
558 static void
559 usage(void)
560 {
561 (void)fprintf(stderr, "usage: %s [-ax] [-d MMDD[[YY]YY]"
562 " [-f fname] [-l days] [-w days]\n", getprogname());
563 exit(1);
564 }
565