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