af6424e3be1946d02895fbf765e3ecf546894262
[dragonfly.git] / usr.bin / calendar / io.c
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1989, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)calendar.c  8.3 (Berkeley) 3/25/94
35  * $FreeBSD: src/usr.bin/calendar/io.c,v 1.21 2007/06/09 05:54:13 grog Exp $
36  * $DragonFly: src/usr.bin/calendar/io.c,v 1.6 2007/09/24 20:31:44 pavalos Exp $
37  */
38
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <sys/time.h>
42 #include <sys/uio.h>
43 #include <sys/wait.h>
44
45 #include <ctype.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <langinfo.h>
49 #include <locale.h>
50 #include <pwd.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55
56 #include "pathnames.h"
57 #include "calendar.h"
58
59 const char *calendarFile = "calendar.all";  /* default calendar file */
60 const char *calendarHomes[] = { ".calendar", _PATH_INCLUDE }; /* HOME */
61 const char *calendarNoMail = "nomail";  /* don't send mail if this file exist */
62
63 struct fixs neaster, npaskha;
64
65 char    hdr_from[] = "From: ";
66 char    hdr_to[] = " (Reminder Service)\nTo: ";
67 char    hdr_subj[] = "\nSubject: ";
68 char    hdr_prec[] = "'s Calendar\nPrecedence: bulk\n\n";
69
70 struct iovec header[] = {
71         {hdr_from, 6},
72         {NULL, 0},
73         {hdr_to, 24},
74         {NULL, 0},
75         {hdr_subj, 10},
76         {NULL, 0},
77         {hdr_prec, 30},
78 };
79
80 void
81 cal(void)
82 {
83         int printing;
84         char *p;
85         FILE *fp;
86         int ch, l;
87         int month;
88         int day;
89         int var;
90         static int d_first = -1;
91         char buf[2048 + 1];
92         struct event *events = NULL;
93
94         if ((fp = opencal()) == NULL)
95                 return;
96         for (printing = 0; fgets(buf, sizeof(buf), stdin) != NULL;) {
97                 if ((p = strchr(buf, '\n')) != NULL)
98                         *p = '\0';
99                 else
100                         while ((ch = getchar()) != '\n' && ch != EOF);
101                 for (l = strlen(buf);
102                      l > 0 && isspace((unsigned char)buf[l - 1]);
103                      l--)
104                         ;
105                 buf[l] = '\0';
106                 if (buf[0] == '\0')
107                         continue;
108                 if (strncmp(buf, "LANG=", 5) == 0) {
109                         setlocale(LC_ALL, buf + 5);
110                         d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
111                         setnnames();
112                         continue;
113                 }
114                 if (strncasecmp(buf, "Easter=", 7) == 0 && buf[7]) {
115                         if (neaster.name != NULL)
116                                 free(neaster.name);
117                         if ((neaster.name = strdup(buf + 7)) == NULL)
118                                 errx(EXIT_FAILURE, "cannot allocate memory");
119                         neaster.len = strlen(buf + 7);
120                         continue;
121                 }
122                 if (strncasecmp(buf, "Paskha=", 7) == 0 && buf[7]) {
123                         if (npaskha.name != NULL)
124                                 free(npaskha.name);
125                         if ((npaskha.name = strdup(buf + 7)) == NULL)
126                                 errx(EXIT_FAILURE, "cannot allocate memory");
127                         npaskha.len = strlen(buf + 7);
128                         continue;
129                 }
130                 if (buf[0] != '\t') {
131                         printing = isnow(buf, &month, &day, &var) ? 1 : 0;
132                         if ((p = strchr(buf, '\t')) == NULL)
133                                 continue;
134                         if (p > buf && p[-1] == '*')
135                                 var = 1;
136                         if (printing) {
137                                 struct tm tm;
138                                 char dbuf[80];
139
140                                 if (d_first < 0)
141                                         d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
142                                 tm.tm_sec = 0;  /* unused */
143                                 tm.tm_min = 0;  /* unused */
144                                 tm.tm_hour = 0; /* unused */
145                                 tm.tm_wday = 0; /* unused */
146                                 tm.tm_mon = month - 1;
147                                 tm.tm_mday = day;
148                                 tm.tm_year = tp->tm_year; /* unused */
149                                 strftime(dbuf, sizeof(dbuf),
150                                     d_first ? "%e %b" : "%b %e",
151                                     &tm);
152                                 events = event_add(events, month, day, dbuf, var, p);
153                         }
154                 }
155                 else if (printing)
156                         event_continue(events, buf);
157         }
158
159         event_print_all(fp, events);
160         closecal(fp);
161 }
162
163 /*
164  * Functions to handle buffered calendar events.
165  */
166 struct event *
167 event_add(struct event *events, int month, int day, char *date, int var, char *txt)
168 {
169         struct event *e;
170
171         e = (struct event *)calloc(1, sizeof(struct event));
172         if (e == NULL)
173                 errx(EXIT_FAILURE, "event_add: cannot allocate memory");
174         e->month = month;
175         e->day = day;
176         e->var = var;
177         e->date = strdup(date);
178         if (e->date == NULL)
179                 errx(EXIT_FAILURE, "event_add: cannot allocate memory");
180         e->text = strdup(txt);
181         if (e->text == NULL)
182                 errx(EXIT_FAILURE, "event_add: cannot allocate memory");
183         e->next = events;
184
185         return e;
186 }
187
188 void
189 event_continue(struct event *e, char *txt)
190 {
191         char *text;
192
193         text = strdup(e->text);
194         if (text == NULL)
195                 errx(EXIT_FAILURE, "event_continue: cannot allocate memory");
196
197         free(e->text);
198         e->text = (char *)malloc(strlen(text) + strlen(txt) + 3);
199         if (e->text == NULL)
200                 errx(EXIT_FAILURE, "event_continue: cannot allocate memory");
201         strcpy(e->text, text);
202         strcat(e->text, "\n");
203         strcat(e->text, txt);
204         free(text);
205
206         return;
207 }
208
209 void
210 event_print_all(FILE *fp, struct event *events)
211 {
212         struct event *e, *e_next;
213         int daycount = f_dayAfter + f_dayBefore;
214         int daycounter;
215         int day, month;
216
217         for (daycounter = 0; daycounter <= daycount; daycounter++) {
218                 day = tp->tm_yday - f_dayBefore + daycounter;
219                 if (day < 0) day += yrdays;
220                 if (day >= yrdays) day -= yrdays;
221
222                 month = 1;
223                 while (month <= 12) {
224                         if (day <= cumdays[month])
225                                 break;
226                         month++;
227                 }
228                 month--;
229                 day -= cumdays[month];
230
231 #ifdef DEBUG
232                 fprintf(stderr,"event_print_allmonth: %d, day: %d\n",month,day);
233 #endif
234
235                 for (e = events; e != NULL; e = e_next ) {
236                         e_next = e->next;
237
238                         if (month != e->month || day != e->day)
239                                 continue;
240
241                         fprintf(fp, "%s%c%s\n", e->date,
242                             e->var ? '*' : ' ', e->text);
243                 }
244         }
245 }
246
247 int
248 getfield(char *p, char **endp, int *flags)
249 {
250         int val, var;
251         char *start, savech;
252
253         for (; !isdigit((unsigned char)*p) && !isalpha((unsigned char)*p)
254                && *p != '*'; ++p);
255         if (*p == '*') {                        /* `*' is current month */
256                 *flags |= F_ISMONTH;
257                 *endp = p+1;
258                 return(tp->tm_mon + 1);
259         }
260         if (isdigit((unsigned char)*p)) {
261                 val = strtol(p, &p, 10);        /* if 0, it's failure */
262                 for (; !isdigit((unsigned char)*p)
263                        && !isalpha((unsigned char)*p) && *p != '*'; ++p);
264                 *endp = p;
265                 return(val);
266         }
267         for (start = p; isalpha((unsigned char)*++p););
268
269         /* Sunday-1 */
270         if (*p == '+' || *p == '-')
271             for(; isdigit((unsigned char)*++p););
272
273         savech = *p;
274         *p = '\0';
275
276         /* Month */
277         if ((val = getmonth(start)) != 0)
278                 *flags |= F_ISMONTH;
279
280         /* Day */
281         else if ((val = getday(start)) != 0) {
282             *flags |= F_ISDAY;
283
284             /* variable weekday */
285             if ((var = getdayvar(start)) != 0) {
286                 if (var <=5 && var >= -4)
287                     val += var * 10;
288 #ifdef DEBUG
289                 printf("var: %d\n", var);
290 #endif
291             }
292         }
293
294         /* Easter */
295         else if ((val = geteaster(start, tp->tm_year + 1900)) != 0)
296             *flags |= F_EASTER;
297
298         /* Paskha */
299         else if ((val = getpaskha(start, tp->tm_year + 1900)) != 0)
300             *flags |= F_EASTER;
301
302         /* undefined rest */
303         else {
304                 *p = savech;
305                 return (0);
306         }
307         for (*p = savech; !isdigit((unsigned char)*p)
308                && !isalpha((unsigned char)*p) && *p != '*'; ++p);
309         *endp = p;
310         return(val);
311 }
312
313 static char path[MAXPATHLEN];
314
315 FILE *
316 opencal(void)
317 {
318         uid_t uid;
319         size_t i;
320         int fd, found, pdes[2];
321         struct stat sbuf;
322
323         /* open up calendar file as stdin */
324         if (!freopen(calendarFile, "r", stdin)) {
325                 if (doall) {
326                     if (chdir(calendarHomes[0]) != 0)
327                         return(NULL);
328                     if (stat(calendarNoMail, &sbuf) == 0)
329                         return(NULL);
330                     if (!freopen(calendarFile, "r", stdin))
331                         return(NULL);
332                 } else {
333                         chdir(getenv("HOME"));
334                         for (found = i = 0; i < sizeof(calendarHomes) /
335                             sizeof(calendarHomes[0]); i++)
336                             if (chdir(calendarHomes[i]) == 0 &&
337                                   freopen(calendarFile, "r", stdin)) {
338                                     found = 1;
339                                     break;
340                             }
341                         if (!found)
342                             errx(EXIT_FAILURE, "no calendar file: ``%s''", calendarFile);
343                 }
344         }
345         if (pipe(pdes) < 0)
346                 return(NULL);
347         switch (fork()) {
348         case -1:                        /* error */
349                 close(pdes[0]);
350                 close(pdes[1]);
351                 return(NULL);
352         case 0:
353                 /* child -- stdin already setup, set stdout to pipe input */
354                 if (pdes[1] != STDOUT_FILENO) {
355                         dup2(pdes[1], STDOUT_FILENO);
356                         close(pdes[1]);
357                 }
358                 close(pdes[0]);
359                 uid = geteuid();
360                 if (setuid(getuid()) < 0) {
361                         warnx("first setuid failed");
362                         _exit(EXIT_FAILURE);
363                 };
364                 if (setgid(getegid()) < 0) {
365                         warnx("setgid failed");
366                         _exit(EXIT_FAILURE);
367                 }
368                 if (setuid(uid) < 0) {
369                         warnx("setuid failed");
370                         _exit(EXIT_FAILURE);
371                 }
372                 execl(_PATH_CPP, "cpp", "-P",
373                     "-traditional", "-nostdinc",        /* GCC specific opts */
374                     "-I.", "-I", _PATH_INCLUDE, (char *)NULL);
375                 warn(_PATH_CPP);
376                 _exit(EXIT_FAILURE);
377         }
378         /* parent -- set stdin to pipe output */
379         dup2(pdes[0], STDIN_FILENO);
380         close(pdes[0]);
381         close(pdes[1]);
382
383         /* not reading all calendar files, just set output to stdout */
384         if (!doall)
385                 return(stdout);
386
387         /* set output to a temporary file, so if no output don't send mail */
388         snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
389         if ((fd = mkstemp(path)) < 0)
390                 return(NULL);
391         return(fdopen(fd, "w+"));
392 }
393
394 void
395 closecal(FILE *fp)
396 {
397         uid_t uid;
398         struct stat sbuf;
399         int nread, pdes[2], status;
400         char buf[1024];
401
402         if (!doall)
403                 return;
404
405         rewind(fp);
406         if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
407                 goto done;
408         if (pipe(pdes) < 0)
409                 goto done;
410         switch (fork()) {
411         case -1:                        /* error */
412                 close(pdes[0]);
413                 close(pdes[1]);
414                 goto done;
415         case 0:
416                 /* child -- set stdin to pipe output */
417                 if (pdes[0] != STDIN_FILENO) {
418                         dup2(pdes[0], STDIN_FILENO);
419                         close(pdes[0]);
420                 }
421                 close(pdes[1]);
422                 uid = geteuid();
423                 if (setuid(getuid()) < 0) {
424                         warnx("setuid failed");
425                         _exit(EXIT_FAILURE);
426                 };
427                 if (setgid(getegid()) < 0) {
428                         warnx("setgid failed");
429                         _exit(EXIT_FAILURE);
430                 }
431                 if (setuid(uid) < 0) {
432                         warnx("setuid failed");
433                         _exit(EXIT_FAILURE);
434                 }
435                 execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
436                     "\"Reminder Service\"", (char *)NULL);
437                 warn(_PATH_SENDMAIL);
438                 _exit(EXIT_FAILURE);
439         }
440         /* parent -- write to pipe input */
441         close(pdes[0]);
442
443         header[1].iov_base = header[3].iov_base = pw->pw_name;
444         header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
445         writev(pdes[1], header, 7);
446         while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
447                 write(pdes[1], buf, nread);
448         close(pdes[1]);
449 done:   fclose(fp);
450         unlink(path);
451         while (wait(&status) >= 0);
452 }