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