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