calendar(1): Sync with FreeBSD
[dragonfly.git] / usr.bin / calendar / io.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #if 0
33 #ifndef lint
34 static char sccsid[] = "@(#)calendar.c  8.3 (Berkeley) 3/25/94";
35 #endif
36 #endif
37
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD: head/usr.bin/calendar/io.c 327117 2017-12-23 21:04:32Z eadler $");
40
41 #include <sys/param.h>
42 #include <sys/stat.h>
43 #include <sys/wait.h>
44 #include <ctype.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <langinfo.h>
48 #include <locale.h>
49 #include <pwd.h>
50 #include <stdbool.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <stringlist.h>
55 #include <time.h>
56 #include <unistd.h>
57
58 #include "pathnames.h"
59 #include "calendar.h"
60
61 enum {
62         T_OK = 0,
63         T_ERR,
64         T_PROCESS,
65 };
66
67 const char *calendarFile = "calendar";  /* default calendar file */
68 static const char *calendarHomes[] = {".calendar", _PATH_INCLUDE}; /* HOME */
69 static const char *calendarNoMail = "nomail";/* don't sent mail if file exist */
70
71 static char path[MAXPATHLEN];
72
73 struct fixs neaster, npaskha, ncny, nfullmoon, nnewmoon;
74 struct fixs nmarequinox, nsepequinox, njunsolstice, ndecsolstice;
75
76 static int cal_parse(FILE *in, FILE *out);
77
78 static StringList *definitions = NULL;
79 static struct event *events[MAXCOUNT];
80 static char *extradata[MAXCOUNT];
81
82 static void
83 trimlr(char **buf)
84 {
85         char *walk = *buf;
86         char *last;
87
88         while (isspace(*walk))
89                 walk++;
90         if (*walk != '\0') {
91                 last = walk + strlen(walk) - 1;
92                 while (last > walk && isspace(*last))
93                         last--;
94                 *(last+1) = 0;
95         }
96
97         *buf = walk;
98 }
99
100 static FILE *
101 cal_fopen(const char *file)
102 {
103         FILE *fp;
104         char *home = getenv("HOME");
105         unsigned int i;
106
107         if (home == NULL || *home == '\0') {
108                 warnx("Cannot get home directory");
109                 return (NULL);
110         }
111
112         if (chdir(home) != 0) {
113                 warnx("Cannot enter home directory");
114                 return (NULL);
115         }
116
117         for (i = 0; i < nitems(calendarHomes); i++) {
118                 if (chdir(calendarHomes[i]) != 0)
119                         continue;
120
121                 if ((fp = fopen(file, "r")) != NULL)
122                         return (fp);
123         }
124
125         warnx("can't open calendar file \"%s\"", file);
126
127         return (NULL);
128 }
129
130 static int
131 token(char *line, FILE *out, bool *skip)
132 {
133         char *walk, c, a;
134
135         if (strncmp(line, "endif", 5) == 0) {
136                 *skip = false;
137                 return (T_OK);
138         }
139
140         if (*skip)
141                 return (T_OK);
142
143         if (strncmp(line, "include", 7) == 0) {
144                 walk = line + 7;
145
146                 trimlr(&walk);
147
148                 if (*walk == '\0') {
149                         warnx("Expecting arguments after #include");
150                         return (T_ERR);
151                 }
152
153                 if (*walk != '<' && *walk != '\"') {
154                         warnx("Excecting '<' or '\"' after #include");
155                         return (T_ERR);
156                 }
157
158                 a = *walk;
159                 walk++;
160                 c = walk[strlen(walk) - 1];
161
162                 switch(c) {
163                 case '>':
164                         if (a != '<') {
165                                 warnx("Unterminated include expecting '\"'");
166                                 return (T_ERR);
167                         }
168                         break;
169                 case '\"':
170                         if (a != '\"') {
171                                 warnx("Unterminated include expecting '>'");
172                                 return (T_ERR);
173                         }
174                         break;
175                 default:
176                         warnx("Unterminated include expecting '%c'",
177                             a == '<' ? '>' : '\"' );
178                         return (T_ERR);
179                 }
180                 walk[strlen(walk) - 1] = '\0';
181
182                 if (cal_parse(cal_fopen(walk), out))
183                         return (T_ERR);
184
185                 return (T_OK);
186         }
187
188         if (strncmp(line, "define", 6) == 0) {
189                 if (definitions == NULL)
190                         definitions = sl_init();
191                 walk = line + 6;
192                 trimlr(&walk);
193
194                 if (*walk == '\0') {
195                         warnx("Expecting arguments after #define");
196                         return (T_ERR);
197                 }
198
199                 sl_add(definitions, strdup(walk));
200                 return (T_OK);
201         }
202
203         if (strncmp(line, "ifndef", 6) == 0) {
204                 walk = line + 6;
205                 trimlr(&walk);
206
207                 if (*walk == '\0') {
208                         warnx("Expecting arguments after #ifndef");
209                         return (T_ERR);
210                 }
211
212                 if (definitions != NULL && sl_find(definitions, walk) != NULL)
213                         *skip = true;
214
215                 return (T_OK);
216         }
217
218         return (T_PROCESS);
219
220 }
221
222 #define REPLACE(string, slen, struct_) \
223                 if (strncasecmp(buf, (string), (slen)) == 0 && buf[(slen)]) { \
224                         if (struct_.name != NULL)                             \
225                                 free(struct_.name);                           \
226                         if ((struct_.name = strdup(buf + (slen))) == NULL)    \
227                                 errx(1, "cannot allocate memory");            \
228                         struct_.len = strlen(buf + (slen));                   \
229                         continue;                                             \
230                 }
231 static int
232 cal_parse(FILE *in, FILE *out)
233 {
234         char *line = NULL;
235         char *buf;
236         size_t linecap = 0;
237         ssize_t linelen;
238         ssize_t l;
239         static int d_first = -1;
240         static int count = 0;
241         int i;
242         int month[MAXCOUNT];
243         int day[MAXCOUNT];
244         int year[MAXCOUNT];
245         bool skip = false;
246         char dbuf[80];
247         char *pp, p;
248         struct tm tm;
249         int flags;
250
251         /* Unused */
252         tm.tm_sec = 0;
253         tm.tm_min = 0;
254         tm.tm_hour = 0;
255         tm.tm_wday = 0;
256
257         if (in == NULL)
258                 return (1);
259
260         while ((linelen = getline(&line, &linecap, in)) > 0) {
261                 if (*line == '#') {
262                         switch (token(line+1, out, &skip)) {
263                         case T_ERR:
264                                 free(line);
265                                 return (1);
266                         case T_OK:
267                                 continue;
268                         case T_PROCESS:
269                                 break;
270                         default:
271                                 break;
272                         }
273                 }
274
275                 if (skip)
276                         continue;
277
278                 buf = line;
279                 for (l = linelen;
280                      l > 0 && isspace((unsigned char)buf[l - 1]);
281                      l--)
282                         ;
283                 buf[l] = '\0';
284                 if (buf[0] == '\0')
285                         continue;
286
287                 /* Parse special definitions: LANG, Easter, Paskha etc */
288                 if (strncmp(buf, "LANG=", 5) == 0) {
289                         (void)setlocale(LC_ALL, buf + 5);
290                         d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
291                         setnnames();
292                         continue;
293                 }
294                 REPLACE("Easter=", 7, neaster);
295                 REPLACE("Paskha=", 7, npaskha);
296                 REPLACE("ChineseNewYear=", 15, ncny);
297                 REPLACE("NewMoon=", 8, nnewmoon);
298                 REPLACE("FullMoon=", 9, nfullmoon);
299                 REPLACE("MarEquinox=", 11, nmarequinox);
300                 REPLACE("SepEquinox=", 11, nsepequinox);
301                 REPLACE("JunSolstice=", 12, njunsolstice);
302                 REPLACE("DecSolstice=", 12, ndecsolstice);
303                 if (strncmp(buf, "SEQUENCE=", 9) == 0) {
304                         setnsequences(buf + 9);
305                         continue;
306                 }
307
308                 /*
309                  * If the line starts with a tab, the data has to be
310                  * added to the previous line
311                  */
312                 if (buf[0] == '\t') {
313                         for (i = 0; i < count; i++)
314                                 event_continue(events[i], buf);
315                         continue;
316                 }
317
318                 /* Get rid of leading spaces (non-standard) */
319                 while (isspace((unsigned char)buf[0]))
320                         memcpy(buf, buf + 1, strlen(buf));
321
322                 /* No tab in the line, then not a valid line */
323                 if ((pp = strchr(buf, '\t')) == NULL)
324                         continue;
325
326                 /* Trim spaces in front of the tab */
327                 while (isspace((unsigned char)pp[-1]))
328                         pp--;
329
330                 p = *pp;
331                 *pp = '\0';
332                 if ((count = parsedaymonth(buf, year, month, day, &flags,
333                     extradata)) == 0)
334                         continue;
335                 *pp = p;
336                 if (count < 0) {
337                         /* Show error status based on return value */
338                         if (debug)
339                                 fprintf(stderr, "Ignored: %s\n", buf);
340                         if (count == -1)
341                                 continue;
342                         count = -count + 1;
343                 }
344
345                 /* Find the last tab */
346                 while (pp[1] == '\t')
347                         pp++;
348
349                 if (d_first < 0)
350                         d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
351
352                 for (i = 0; i < count; i++) {
353                         tm.tm_mon = month[i] - 1;
354                         tm.tm_mday = day[i];
355                         tm.tm_year = year[i] - 1900;
356                         (void)strftime(dbuf, sizeof(dbuf),
357                             d_first ? "%e %b" : "%b %e", &tm);
358                         if (debug)
359                                 fprintf(stderr, "got %s\n", pp);
360                         events[i] = event_add(year[i], month[i], day[i], dbuf,
361                             ((flags &= F_VARIABLE) != 0) ? 1 : 0, pp,
362                             extradata[i]);
363                 }
364         }
365
366         free(line);
367         fclose(in);
368
369         return (0);
370 }
371
372 void
373 cal(void)
374 {
375         FILE *fpin;
376         FILE *fpout;
377         int i;
378
379         for (i = 0; i < MAXCOUNT; i++)
380                 extradata[i] = (char *)calloc(1, 20);
381
382
383         if ((fpin = opencalin()) == NULL)
384                 return;
385
386         if ((fpout = opencalout()) == NULL) {
387                 fclose(fpin);
388                 return;
389         }
390
391         if (cal_parse(fpin, fpout))
392                 return;
393
394         event_print_all(fpout);
395         closecal(fpout);
396 }
397
398 FILE *
399 opencalin(void)
400 {
401         struct stat sbuf;
402         FILE *fpin;
403
404         /* open up calendar file */
405         if ((fpin = fopen(calendarFile, "r")) == NULL) {
406                 if (doall) {
407                         if (chdir(calendarHomes[0]) != 0)
408                                 return (NULL);
409                         if (stat(calendarNoMail, &sbuf) == 0)
410                                 return (NULL);
411                         if ((fpin = fopen(calendarFile, "r")) == NULL)
412                                 return (NULL);
413                 } else {
414                         fpin = cal_fopen(calendarFile);
415                 }
416         }
417         return (fpin);
418 }
419
420 FILE *
421 opencalout(void)
422 {
423         int fd;
424
425         /* not reading all calendar files, just set output to stdout */
426         if (!doall)
427                 return (stdout);
428
429         /* set output to a temporary file, so if no output don't send mail */
430         snprintf(path, sizeof(path), "%s/_calXXXXXX", _PATH_TMP);
431         if ((fd = mkstemp(path)) < 0)
432                 return (NULL);
433         return (fdopen(fd, "w+"));
434 }
435
436 void
437 closecal(FILE *fp)
438 {
439         uid_t uid;
440         struct stat sbuf;
441         int nread, pdes[2], status;
442         char buf[1024];
443
444         if (!doall)
445                 return;
446
447         rewind(fp);
448         if (fstat(fileno(fp), &sbuf) || !sbuf.st_size)
449                 goto done;
450         if (pipe(pdes) < 0)
451                 goto done;
452         switch (fork()) {
453         case -1:                        /* error */
454                 (void)close(pdes[0]);
455                 (void)close(pdes[1]);
456                 goto done;
457         case 0:
458                 /* child -- set stdin to pipe output */
459                 if (pdes[0] != STDIN_FILENO) {
460                         (void)dup2(pdes[0], STDIN_FILENO);
461                         (void)close(pdes[0]);
462                 }
463                 (void)close(pdes[1]);
464                 uid = geteuid();
465                 if (setuid(getuid()) < 0) {
466                         warnx("setuid failed");
467                         _exit(1);
468                 }
469                 if (setgid(getegid()) < 0) {
470                         warnx("setgid failed");
471                         _exit(1);
472                 }
473                 if (setuid(uid) < 0) {
474                         warnx("setuid failed");
475                         _exit(1);
476                 }
477                 execl(_PATH_SENDMAIL, "sendmail", "-i", "-t", "-F",
478                     "\"Reminder Service\"", (char *)NULL);
479                 warn(_PATH_SENDMAIL);
480                 _exit(1);
481         }
482         /* parent -- write to pipe input */
483         (void)close(pdes[0]);
484
485         write(pdes[1], "From: \"Reminder Service\" <", 26);
486         write(pdes[1], pw->pw_name, strlen(pw->pw_name));
487         write(pdes[1], ">\nTo: <", 7);
488         write(pdes[1], pw->pw_name, strlen(pw->pw_name));
489         write(pdes[1], ">\nSubject: ", 11);
490         write(pdes[1], dayname, strlen(dayname));
491         write(pdes[1], "'s Calendar\nPrecedence: bulk\n\n", 30);
492
493         while ((nread = read(fileno(fp), buf, sizeof(buf))) > 0)
494                 (void)write(pdes[1], buf, nread);
495         (void)close(pdes[1]);
496 done:   (void)fclose(fp);
497         (void)unlink(path);
498         while (wait(&status) >= 0);
499 }