]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - usr.bin/calendar/io.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1989, 1993\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif
39
40 #if 0
41 #ifndef lint
42 static char sccsid[] = "@(#)calendar.c  8.3 (Berkeley) 3/25/94";
43 #endif
44 #endif
45
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48
49 #include <sys/types.h>
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53 #include <sys/uio.h>
54 #include <sys/wait.h>
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <langinfo.h>
59 #include <locale.h>
60 #include <pwd.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65
66 #include "pathnames.h"
67 #include "calendar.h"
68
69
70 const char *calendarFile = "calendar";  /* default calendar file */
71 const char *calendarHomes[] = {".calendar", _PATH_INCLUDE};     /* HOME */
72 const char *calendarNoMail = "nomail";  /* don't sent mail if this file exist */
73
74 char    path[MAXPATHLEN];
75
76 struct fixs neaster, npaskha;
77
78 struct iovec header[] = {
79         {"From: ", 6},
80         {NULL, 0},
81         {" (Reminder Service)\nTo: ", 24},
82         {NULL, 0},
83         {"\nSubject: ", 10},
84         {NULL, 0},
85         {"'s Calendar\nPrecedence: bulk\n\n", 30},
86 };
87
88 void
89 cal(void)
90 {
91         int printing;
92         char *p;
93         FILE *fp;
94         int ch, l;
95         int month;
96         int day;
97         int var;
98         static int d_first = -1;
99         char buf[2048 + 1];
100         struct event *events = NULL;
101
102         if ((fp = opencal()) == NULL)
103                 return;
104         for (printing = 0; fgets(buf, sizeof(buf), stdin) != NULL;) {
105                 if ((p = strchr(buf, '\n')) != NULL)
106                         *p = '\0';
107                 else
108                         while ((ch = getchar()) != '\n' && ch != EOF);
109                 for (l = strlen(buf);
110                      l > 0 && isspace((unsigned char)buf[l - 1]);
111                      l--)
112                         ;
113                 buf[l] = '\0';
114                 if (buf[0] == '\0')
115                         continue;
116                 if (strncmp(buf, "LANG=", 5) == 0) {
117                         (void)setlocale(LC_ALL, buf + 5);
118                         d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
119                         setnnames();
120                         continue;
121                 }
122                 if (strncasecmp(buf, "Easter=", 7) == 0 && buf[7]) {
123                         if (neaster.name != NULL)
124                                 free(neaster.name);
125                         if ((neaster.name = strdup(buf + 7)) == NULL)
126                                 errx(1, "cannot allocate memory");
127                         neaster.len = strlen(buf + 7);
128                         continue;
129                 }
130                 if (strncasecmp(buf, "Paskha=", 7) == 0 && buf[7]) {
131                         if (npaskha.name != NULL)
132                                 free(npaskha.name);
133                         if ((npaskha.name = strdup(buf + 7)) == NULL)
134                                 errx(1, "cannot allocate memory");
135                         npaskha.len = strlen(buf + 7);
136                         continue;
137                 }
138                 if (buf[0] != '\t') {
139                         printing = isnow(buf, &month, &day, &var) ? 1 : 0;
140                         if ((p = strchr(buf, '\t')) == NULL)
141                                 continue;
142                         if (p > buf && p[-1] == '*')
143                                 var = 1;
144                         if (printing) {
145                                 struct tm tm;
146                                 char dbuf[80];
147
148                                 if (d_first < 0)
149                                         d_first =
150                                             (*nl_langinfo(D_MD_ORDER) == 'd');
151                                 tm.tm_sec = 0;  /* unused */
152                                 tm.tm_min = 0;  /* unused */
153                                 tm.tm_hour = 0; /* unused */
154                                 tm.tm_wday = 0; /* unused */
155                                 tm.tm_mon = month - 1;
156                                 tm.tm_mday = day;
157                                 tm.tm_year = tp->tm_year; /* unused */
158                                 (void)strftime(dbuf, sizeof(dbuf),
159                                     d_first ? "%e %b" : "%b %e", &tm);
160                                 events = event_add(events, month, day, dbuf,
161                                     var, p);
162                         }
163                 } else {
164                         if (printing)
165                                 event_continue(events, buf);
166                 }
167         }
168
169         event_print_all(fp, events);
170         closecal(fp);
171 }
172
173 struct event *
174 event_add(struct event *events, int month, int day,
175     char *date, int var, char *txt)
176 {
177         struct event *e;
178
179         /*
180          * Creating a new event:
181          * - Create a new event
182          * - Copy the machine readable day and month
183          * - Copy the human readable and language specific date
184          * - Copy the text of the event
185          */
186         e = (struct event *)calloc(1, sizeof(struct event));
187         if (e == NULL)
188                 errx(1, "event_add: cannot allocate memory");
189         e->month = month;
190         e->day = day;
191         e->var = var;
192         e->date = strdup(date);
193         if (e->date == NULL)
194                 errx(1, "event_add: cannot allocate memory");
195         e->text = strdup(txt);
196         if (e->text == NULL)
197                 errx(1, "event_add: cannot allocate memory");
198         e->next = events;
199
200         return e;
201 }
202
203 void
204 event_continue(struct event *e, char *txt)
205 {
206         char *text;
207
208         /*
209          * Adding text to the event:
210          * - Save a copy of the old text (unknown length, so strdup())
211          * - Allocate enough space for old text + \n + new text + 0
212          * - Store the old text + \n + new text
213          * - Destroy the saved copy.
214          */
215         text = strdup(e->text);
216         if (text == NULL)
217                 errx(1, "event_continue: cannot allocate memory");
218
219         free(e->text);
220         e->text = (char *)malloc(strlen(text) + strlen(txt) + 3);
221         if (e->text == NULL)
222                 errx(1, "event_continue: cannot allocate memory");
223         strcpy(e->text, text);
224         strcat(e->text, "\n");
225         strcat(e->text, txt);
226         free(text);
227
228         return;
229 }
230
231 void
232 event_print_all(FILE *fp, struct event *events)
233 {
234         struct event *e, *e_next;
235         int daycounter;
236         int day, month;
237
238         /*
239          * Print all events:
240          * - We know the number of days to be counted (f_dayAfter + f_dayBefore)
241          * - We know the current day of the year ("now" - f_dayBefore + counter)
242          * - We know the number of days in the year (yrdays, set in settime())
243          * - So we know the date on which the current daycounter is on the
244          *   calendar in days and months.
245          * - Go through the list of events, and print all matching dates
246          */
247         for (daycounter = 0; daycounter <= f_dayAfter + f_dayBefore;
248             daycounter++) {
249                 day = tp->tm_yday - f_dayBefore + daycounter;
250                 if (day < 0)
251                         day += yrdays;
252                 if (day >= yrdays)
253                         day -= yrdays;
254
255                 /*
256                  * When we know the day of the year, we can determine the day
257                  * of the month and the month.
258                  */
259                 month = 1;
260                 while (month <= 12) {
261                         if (day <= cumdays[month])
262                                 break;
263                         month++;
264                 }
265                 month--;
266                 day -= cumdays[month];
267
268 #ifdef DEBUG
269                 fprintf(stderr, "event_print_allmonth: %d, day: %d\n",
270                     month, day);
271 #endif
272
273                 /*
274                  * Go through all events and print the text of the matching
275                  * dates
276                  */
277                 for (e = events; e != NULL; e = e_next) {
278                         e_next = e->next;
279
280                         if (month != e->month || day != e->day)
281                                 continue;
282
283                         (void)fprintf(fp, "%s%c%s\n", e->date,
284                             e->var ? '*' : ' ', e->text);
285                 }
286         }
287 }
288
289 int
290 getfield(char *p, char **endp, int *flags)
291 {
292         int val, var;
293         char *start, savech;
294
295         for (; !isdigit((unsigned char)*p) && !isalpha((unsigned char)*p)
296                && *p != '*'; ++p)
297                ;
298         if (*p == '*') {                        /* `*' is current month */
299                 *flags |= F_ISMONTH;
300                 *endp = p + 1;
301                 return (tp->tm_mon + 1);
302         }
303         if (isdigit((unsigned char)*p)) {
304                 val = strtol(p, &p, 10);        /* if 0, it's failure */
305                 for (; !isdigit((unsigned char)*p)
306                        && !isalpha((unsigned char)*p) && *p != '*'; ++p);
307                 *endp = p;
308                 return (val);
309         }
310         for (start = p; isalpha((unsigned char)*++p););
311
312         /* Sunday-1 */
313         if (*p == '+' || *p == '-')
314                 for(; isdigit((unsigned char)*++p);)
315                         ;
316
317         savech = *p;
318         *p = '\0';
319
320         /* Month */
321         if ((val = getmonth(start)) != 0)
322                 *flags |= F_ISMONTH;
323
324         /* Day */
325         else if ((val = getday(start)) != 0) {
326                 *flags |= F_ISDAY;
327
328                 /* variable weekday */
329                 if ((var = getdayvar(start)) != 0) {
330                         if (var <= 5 && var >= -4)
331                                 val += var * 10;
332 #ifdef DEBUG
333                         printf("var: %d\n", var);
334 #endif
335                 }
336         }
337
338         /* Easter */
339         else if ((val = geteaster(start, tp->tm_year + 1900)) != 0)
340                 *flags |= F_EASTER;
341
342         /* Paskha */
343         else if ((val = getpaskha(start, tp->tm_year + 1900)) != 0)
344                 *flags |= F_EASTER;
345
346         /* undefined rest */
347         else {
348                 *p = savech;
349                 return (0);
350         }
351         for (*p = savech; !isdigit((unsigned char)*p)
352            && !isalpha((unsigned char)*p) && *p != '*'; ++p)
353                 ;
354         *endp = p;
355         return (val);
356 }
357
358 FILE *
359 opencal(void)
360 {
361         uid_t uid;
362         size_t i;
363         int fd, found, pdes[2];
364         struct stat sbuf;
365
366         /* open up calendar file as stdin */
367         if (!freopen(calendarFile, "r", stdin)) {
368                 if (doall) {
369                         if (chdir(calendarHomes[0]) != 0)
370                                 return (NULL);
371                         if (stat(calendarNoMail, &sbuf) == 0)
372                                 return (NULL);
373                         if (!freopen(calendarFile, "r", stdin))
374                                 return (NULL);
375                 } else {
376                         char *home = getenv("HOME");
377                         if (home == NULL || *home == '\0')
378                                 errx(1, "cannot get home directory");
379                         chdir(home);
380                         for (found = i = 0; i < sizeof(calendarHomes) /
381                             sizeof(calendarHomes[0]); i++)
382                                 if (chdir(calendarHomes[i]) == 0 &&
383                                     freopen(calendarFile, "r", stdin)) {
384                                         found = 1;
385                                         break;
386                                 }
387                         if (!found)
388                                 errx(1,
389                                     "can't open calendar file \"%s\": %s (%d)",
390                                     calendarFile, strerror(errno), errno);
391                 }
392         }
393         if (pipe(pdes) < 0)
394                 return (NULL);
395         switch (fork()) {
396         case -1:                        /* error */
397                 (void)close(pdes[0]);
398                 (void)close(pdes[1]);
399                 return (NULL);
400         case 0:
401                 /* child -- stdin already setup, set stdout to pipe input */
402                 if (pdes[1] != STDOUT_FILENO) {
403                         (void)dup2(pdes[1], STDOUT_FILENO);
404                         (void)close(pdes[1]);
405                 }
406                 (void)close(pdes[0]);
407                 uid = geteuid();
408                 if (setuid(getuid()) < 0) {
409                         warnx("first setuid failed");
410                         _exit(1);
411                 };
412                 if (setgid(getegid()) < 0) {
413                         warnx("setgid failed");
414                         _exit(1);
415                 }
416                 if (setuid(uid) < 0) {
417                         warnx("setuid failed");
418                         _exit(1);
419                 }
420                 execl(_PATH_CPP, "cpp", "-P",
421                     "-traditional", "-nostdinc",        /* GCC specific opts */
422                     "-I.", "-I", _PATH_INCLUDE, (char *)NULL);
423                 warn(_PATH_CPP);
424                 _exit(1);
425         }
426         /* parent -- set stdin to pipe output */
427         (void)dup2(pdes[0], STDIN_FILENO);
428         (void)close(pdes[0]);
429         (void)close(pdes[1]);
430
431         /* not reading all calendar files, just set output to stdout */
432         if (!doall)
433                 return (stdout);
434
435         /* set output to a temporary file, so if no output don't send mail */
436         (void)snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
437         if ((fd = mkstemp(path)) < 0)
438                 return (NULL);
439         return (fdopen(fd, "w+"));
440 }
441
442 void
443 closecal(FILE *fp)
444 {
445         uid_t uid;
446         struct stat sbuf;
447         int nread, pdes[2], status;
448         char buf[1024];
449
450         if (!doall)
451                 return;
452
453         (void)rewind(fp);
454         if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
455                 goto done;
456         if (pipe(pdes) < 0)
457                 goto done;
458         switch (fork()) {
459         case -1:                        /* error */
460                 (void)close(pdes[0]);
461                 (void)close(pdes[1]);
462                 goto done;
463         case 0:
464                 /* child -- set stdin to pipe output */
465                 if (pdes[0] != STDIN_FILENO) {
466                         (void)dup2(pdes[0], STDIN_FILENO);
467                         (void)close(pdes[0]);
468                 }
469                 (void)close(pdes[1]);
470                 uid = geteuid();
471                 if (setuid(getuid()) < 0) {
472                         warnx("setuid failed");
473                         _exit(1);
474                 };
475                 if (setgid(getegid()) < 0) {
476                         warnx("setgid failed");
477                         _exit(1);
478                 }
479                 if (setuid(uid) < 0) {
480                         warnx("setuid failed");
481                         _exit(1);
482                 }
483                 execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
484                     "\"Reminder Service\"", (char *)NULL);
485                 warn(_PATH_SENDMAIL);
486                 _exit(1);
487         }
488         /* parent -- write to pipe input */
489         (void)close(pdes[0]);
490
491         header[1].iov_base = header[3].iov_base = pw->pw_name;
492         header[1].iov_len = header[3].iov_len = strlen(pw->pw_name);
493         writev(pdes[1], header, 7);
494         while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
495                 (void)write(pdes[1], buf, nread);
496         (void)close(pdes[1]);
497 done:   (void)fclose(fp);
498         (void)unlink(path);
499         while (wait(&status) >= 0);
500 }