]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - games/fortune/fortune/fortune.c
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / games / fortune / fortune / fortune.c
1 /*-
2  * Copyright (c) 1986, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Ken Arnold.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #if 0
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1986, 1993\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39
40 #ifndef lint
41 static const char sccsid[] = "@(#)fortune.c   8.1 (Berkeley) 5/31/93";
42 #endif /* not lint */
43 #endif
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/stat.h>
48 #include <sys/endian.h>
49
50 #include <assert.h>
51 #include <ctype.h>
52 #include <dirent.h>
53 #include <fcntl.h>
54 #include <locale.h>
55 #include <regex.h>
56 #include <stdbool.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <time.h>
61 #include <unistd.h>
62
63 #include "strfile.h"
64 #include "pathnames.h"
65
66 #define TRUE    true
67 #define FALSE   false
68
69 #define MINW    6               /* minimum wait if desired */
70 #define CPERS   20              /* # of chars for each sec */
71 #define SLEN    160             /* # of chars in short fortune */
72
73 #define POS_UNKNOWN     ((uint32_t) -1) /* pos for file unknown */
74 #define NO_PROB         (-1)            /* no prob specified for file */
75
76 #ifdef  DEBUG
77 #define DPRINTF(l,x)    { if (Debug >= l) fprintf x; }
78 #undef  NDEBUG
79 #else
80 #define DPRINTF(l,x)
81 #define NDEBUG  1
82 #endif
83
84 typedef struct fd {
85         int             percent;
86         int             fd, datfd;
87         uint32_t        pos;
88         FILE            *inf;
89         const char      *name;
90         const char      *path;
91         char            *datfile, *posfile;
92         bool            read_tbl;
93         bool            was_pos_file;
94         STRFILE         tbl;
95         int             num_children;
96         struct fd       *child, *parent;
97         struct fd       *next, *prev;
98 } FILEDESC;
99
100 static bool     Found_one;              /* did we find a match? */
101 static bool     Find_files = FALSE;     /* just find a list of proper fortune files */
102 static bool     Fortunes_only = FALSE;  /* check only "fortunes" files */
103 static bool     Wait = FALSE;           /* wait desired after fortune */
104 static bool     Short_only = FALSE;     /* short fortune desired */
105 static bool     Long_only = FALSE;      /* long fortune desired */
106 static bool     Offend = FALSE;         /* offensive fortunes only */
107 static bool     All_forts = FALSE;      /* any fortune allowed */
108 static bool     Equal_probs = FALSE;    /* scatter un-allocted prob equally */
109 static bool     Match = FALSE;          /* dump fortunes matching a pattern */
110 static bool     WriteToDisk = false;    /* use files on disk to save state */
111 #ifdef DEBUG
112 static int      Debug = 0;              /* print debug messages */
113 #endif
114
115 static char     *Fortbuf = NULL;        /* fortune buffer for -m */
116
117 static int      Fort_len = 0;
118
119 static off_t    Seekpts[2];             /* seek pointers to fortunes */
120
121 static FILEDESC *File_list = NULL,      /* Head of file list */
122                 *File_tail = NULL;      /* Tail of file list */
123 static FILEDESC *Fortfile;              /* Fortune file to use */
124
125 static STRFILE  Noprob_tbl;             /* sum of data for all no prob files */
126
127 static const char *Fortune_path;
128 static char     **Fortune_path_arr;
129
130 static int       add_dir(FILEDESC *);
131 static int       add_file(int, const char *, const char *, FILEDESC **,
132                      FILEDESC **, FILEDESC *);
133 static void      all_forts(FILEDESC *, char *);
134 static char     *copy(const char *, u_int);
135 static void      display(FILEDESC *);
136 static void      do_free(void *);
137 static void     *do_malloc(u_int);
138 static int       form_file_list(char **, int);
139 static int       fortlen(void);
140 static void      get_fort(void);
141 static void      get_pos(FILEDESC *);
142 static void      get_tbl(FILEDESC *);
143 static void      getargs(int, char *[]);
144 static void      getpath(void);
145 static void      init_prob(void);
146 static int       is_dir(const char *);
147 static int       is_fortfile(const char *, char **, char **, int);
148 static int       is_off_name(const char *);
149 static int       max(int, int);
150 static FILEDESC *new_fp(void);
151 static char     *off_name(const char *);
152 static void      open_dat(FILEDESC *);
153 static void      open_fp(FILEDESC *);
154 static FILEDESC *pick_child(FILEDESC *);
155 static void      print_file_list(void);
156 static void      print_list(FILEDESC *, int);
157 static void      sum_noprobs(FILEDESC *);
158 static void      sum_tbl(STRFILE *, STRFILE *);
159 static void      usage(void);
160 static void      zero_tbl(STRFILE *);
161
162 static char     *conv_pat(char *);
163 static int       find_matches(void);
164 static void      matches_in_list(FILEDESC *);
165 static int       maxlen_in_list(FILEDESC *);
166
167 static regex_t Re_pat;
168
169 int
170 main(int argc, char *argv[])
171 {
172         int     fd;
173
174         if (getenv("FORTUNE_SAVESTATE") != NULL)
175                 WriteToDisk = true;
176
177         (void) setlocale(LC_ALL, "");
178
179         getpath();
180         getargs(argc, argv);
181
182         if (Match)
183                 exit(find_matches() != 0);
184
185         init_prob();
186         do {
187                 get_fort();
188         } while ((Short_only && fortlen() > SLEN) ||
189                  (Long_only && fortlen() <= SLEN));
190
191         display(Fortfile);
192
193         if (WriteToDisk) {
194                 if ((fd = creat(Fortfile->posfile, 0666)) < 0) {
195                         perror(Fortfile->posfile);
196                         exit(1);
197                 }
198                 /*
199                  * if we can, we exclusive lock, but since it isn't very
200                  * important, we just punt if we don't have easy locking
201                  * available.
202                  */
203                 flock(fd, LOCK_EX);
204                 write(fd, (char *) &Fortfile->pos, sizeof Fortfile->pos);
205                 if (!Fortfile->was_pos_file)
206                 chmod(Fortfile->path, 0666);
207                 flock(fd, LOCK_UN);
208         }
209         if (Wait) {
210                 if (Fort_len == 0)
211                         (void) fortlen();
212                 sleep((unsigned int) max(Fort_len / CPERS, MINW));
213         }
214
215         exit(0);
216 }
217
218 static void
219 display(FILEDESC *fp)
220 {
221         char   *p;
222         unsigned char ch;
223         char    line[BUFSIZ];
224
225         open_fp(fp);
226         fseeko(fp->inf, Seekpts[0], SEEK_SET);
227         for (Fort_len = 0; fgets(line, sizeof line, fp->inf) != NULL &&
228             !STR_ENDSTRING(line, fp->tbl); Fort_len++) {
229                 if (fp->tbl.str_flags & STR_ROTATED)
230                         for (p = line; (ch = *p) != '\0'; ++p) {
231                                 if (isascii(ch)) {
232                                         if (isupper(ch))
233                                                 *p = 'A' + (ch - 'A' + 13) % 26;
234                                         else if (islower(ch))
235                                                 *p = 'a' + (ch - 'a' + 13) % 26;
236                                 }
237                         }
238                 if (fp->tbl.str_flags & STR_COMMENTS
239                     && line[0] == fp->tbl.str_delim
240                     && line[1] == fp->tbl.str_delim)
241                         continue;
242                 fputs(line, stdout);
243         }
244         (void) fflush(stdout);
245 }
246
247 /*
248  * fortlen:
249  *      Return the length of the fortune.
250  */
251 static int
252 fortlen(void)
253 {
254         int     nchar;
255         char    line[BUFSIZ];
256
257         if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
258                 nchar = (int)(Seekpts[1] - Seekpts[0]);
259         else {
260                 open_fp(Fortfile);
261                 fseeko(Fortfile->inf, Seekpts[0], SEEK_SET);
262                 nchar = 0;
263                 while (fgets(line, sizeof line, Fortfile->inf) != NULL &&
264                        !STR_ENDSTRING(line, Fortfile->tbl))
265                         nchar += strlen(line);
266         }
267         Fort_len = nchar;
268
269         return (nchar);
270 }
271
272 /*
273  *      This routine evaluates the arguments on the command line
274  */
275 static void
276 getargs(int argc, char *argv[])
277 {
278         int     ignore_case;
279         char    *pat;
280         int ch;
281
282         ignore_case = FALSE;
283         pat = NULL;
284
285 #ifdef DEBUG
286         while ((ch = getopt(argc, argv, "aDefilm:osw")) != -1)
287 #else
288         while ((ch = getopt(argc, argv, "aefilm:osw")) != -1)
289 #endif /* DEBUG */
290                 switch(ch) {
291                 case 'a':               /* any fortune */
292                         All_forts++;
293                         break;
294 #ifdef DEBUG
295                 case 'D':
296                         Debug++;
297                         break;
298 #endif /* DEBUG */
299                 case 'e':
300                         Equal_probs++;  /* scatter un-allocted prob equally */
301                         break;
302                 case 'f':               /* find fortune files */
303                         Find_files++;
304                         break;
305                 case 'l':               /* long ones only */
306                         Long_only++;
307                         Short_only = FALSE;
308                         break;
309                 case 'o':               /* offensive ones only */
310                         Offend++;
311                         break;
312                 case 's':               /* short ones only */
313                         Short_only++;
314                         Long_only = FALSE;
315                         break;
316                 case 'w':               /* give time to read */
317                         Wait++;
318                         break;
319                 case 'm':                       /* dump out the fortunes */
320                         Match++;
321                         pat = optarg;
322                         break;
323                 case 'i':                       /* case-insensitive match */
324                         ignore_case++;
325                         break;
326                 case '?':
327                 default:
328                         usage();
329                 }
330         argc -= optind;
331         argv += optind;
332
333         if (!form_file_list(argv, argc))
334                 exit(1);        /* errors printed through form_file_list() */
335         if (Find_files) {
336                 print_file_list();
337                 exit(0);
338         }
339 #ifdef DEBUG
340         else if (Debug >= 1)
341                 print_file_list();
342 #endif /* DEBUG */
343
344         if (pat != NULL) {
345                 int error;
346
347                 if (ignore_case)
348                         pat = conv_pat(pat);
349                 error = regcomp(&Re_pat, pat, REG_BASIC);
350                 if (error) {
351                         fprintf(stderr, "regcomp(%s) fails\n", pat);
352                         exit(1);
353                 }
354         }
355 }
356
357 /*
358  * form_file_list:
359  *      Form the file list from the file specifications.
360  */
361 static int
362 form_file_list(char **files, int file_cnt)
363 {
364         int     i, percent;
365         char    *sp;
366         char    **pstr;
367
368         if (file_cnt == 0) {
369                 if (Find_files) {
370                         Fortunes_only = TRUE;
371                         pstr = Fortune_path_arr;
372                         i = 0;
373                         while (*pstr) {
374                                 i += add_file(NO_PROB, *pstr++, NULL,
375                                               &File_list, &File_tail, NULL);
376                         }
377                         Fortunes_only = FALSE;
378                         if (!i) {
379                                 fprintf(stderr, "No fortunes found in %s.\n",
380                                     Fortune_path);
381                         }
382                         return (i != 0);
383                 } else {
384                         pstr = Fortune_path_arr;
385                         i = 0;
386                         while (*pstr) {
387                                 i += add_file(NO_PROB, "fortunes", *pstr++,
388                                               &File_list, &File_tail, NULL);
389                         }
390                         if (!i) {
391                                 fprintf(stderr, "No fortunes found in %s.\n",
392                                     Fortune_path);
393                         }
394                         return (i != 0);
395                 }
396         }
397         for (i = 0; i < file_cnt; i++) {
398                 percent = NO_PROB;
399                 if (!isdigit((unsigned char)files[i][0]))
400                         sp = files[i];
401                 else {
402                         percent = 0;
403                         for (sp = files[i]; isdigit((unsigned char)*sp); sp++)
404                                 percent = percent * 10 + *sp - '0';
405                         if (percent > 100) {
406                                 fprintf(stderr, "percentages must be <= 100\n");
407                                 return (FALSE);
408                         }
409                         if (*sp == '.') {
410                                 fprintf(stderr, "percentages must be integers\n");
411                                 return (FALSE);
412                         }
413                         /*
414                          * If the number isn't followed by a '%', then
415                          * it was not a percentage, just the first part
416                          * of a file name which starts with digits.
417                          */
418                         if (*sp != '%') {
419                                 percent = NO_PROB;
420                                 sp = files[i];
421                         }
422                         else if (*++sp == '\0') {
423                                 if (++i >= file_cnt) {
424                                         fprintf(stderr, "percentages must precede files\n");
425                                         return (FALSE);
426                                 }
427                                 sp = files[i];
428                         }
429                 }
430                 if (strcmp(sp, "all") == 0) {
431                         pstr = Fortune_path_arr;
432                         i = 0;
433                         while (*pstr) {
434                                 i += add_file(NO_PROB, *pstr++, NULL,
435                                               &File_list, &File_tail, NULL);
436                         }
437                         if (!i) {
438                                 fprintf(stderr, "No fortunes found in %s.\n",
439                                     Fortune_path);
440                                 return (FALSE);
441                         }
442                 } else if (!add_file(percent, sp, NULL, &File_list,
443                                      &File_tail, NULL)) {
444                         return (FALSE);
445                 }
446         }
447
448         return (TRUE);
449 }
450
451 /*
452  * add_file:
453  *      Add a file to the file list.
454  */
455 static int
456 add_file(int percent, const char *file, const char *dir, FILEDESC **head,
457     FILEDESC **tail, FILEDESC *parent)
458 {
459         FILEDESC        *fp;
460         int             fd;
461         const char      *path;
462         char            *tpath, *offensive;
463         bool            was_malloc;
464         bool            isdir;
465
466         if (dir == NULL) {
467                 path = file;
468                 tpath = NULL;
469                 was_malloc = FALSE;
470         }
471         else {
472                 tpath = do_malloc((unsigned int)(strlen(dir) + strlen(file) + 2));
473                 strcat(strcat(strcpy(tpath, dir), "/"), file);
474                 path = tpath;
475                 was_malloc = TRUE;
476         }
477         if ((isdir = is_dir(path)) && parent != NULL) {
478                 if (was_malloc)
479                         free(tpath);
480                 return (FALSE); /* don't recurse */
481         }
482         offensive = NULL;
483         if (!isdir && parent == NULL && (All_forts || Offend) &&
484             !is_off_name(path)) {
485                 offensive = off_name(path);
486                 if (Offend) {
487                         if (was_malloc)
488                                 free(tpath);
489                         path = tpath = offensive;
490                         offensive = NULL;
491                         was_malloc = TRUE;
492                         DPRINTF(1, (stderr, "\ttrying \"%s\"\n", path));
493                         file = off_name(file);
494                 }
495         }
496
497         DPRINTF(1, (stderr, "adding file \"%s\"\n", path));
498 over:
499         if ((fd = open(path, O_RDONLY)) < 0) {
500                 /*
501                  * This is a sneak.  If the user said -a, and if the
502                  * file we're given isn't a file, we check to see if
503                  * there is a -o version.  If there is, we treat it as
504                  * if *that* were the file given.  We only do this for
505                  * individual files -- if we're scanning a directory,
506                  * we'll pick up the -o file anyway.
507                  */
508                 if (All_forts && offensive != NULL) {
509                         if (was_malloc)
510                                 free(tpath);
511                         path = tpath = offensive;
512                         offensive = NULL;
513                         was_malloc = TRUE;
514                         DPRINTF(1, (stderr, "\ttrying \"%s\"\n", path));
515                         file = off_name(file);
516                         goto over;
517                 }
518                 if (dir == NULL && file[0] != '/') {
519                         int i = 0;
520                         char **pstr = Fortune_path_arr;
521
522                         while (*pstr) {
523                                 i += add_file(percent, file, *pstr++,
524                                               head, tail, parent);
525                         }
526                         if (!i) {
527                                 fprintf(stderr, "No '%s' found in %s.\n",
528                                     file, Fortune_path);
529                         }
530                         return (i != 0);
531                 }
532                 /*
533                 if (parent == NULL)
534                         perror(path);
535                 */
536                 if (was_malloc)
537                         free(tpath);
538                 return (FALSE);
539         }
540
541         DPRINTF(2, (stderr, "path = \"%s\"\n", path));
542
543         fp = new_fp();
544         fp->fd = fd;
545         fp->percent = percent;
546         fp->name = file;
547         fp->path = path;
548         fp->parent = parent;
549
550         if ((isdir && !add_dir(fp)) ||
551             (!isdir &&
552              !is_fortfile(path, &fp->datfile, &fp->posfile, (parent != NULL))))
553         {
554                 if (parent == NULL)
555                         fprintf(stderr,
556                                 "fortune:%s not a fortune file or directory\n",
557                                 path);
558                 if (was_malloc)
559                         free(tpath);
560                 do_free(fp->datfile);
561                 do_free(fp->posfile);
562                 free(fp);
563                 do_free(offensive);
564                 return (FALSE);
565         }
566         /*
567          * If the user said -a, we need to make this node a pointer to
568          * both files, if there are two.  We don't need to do this if
569          * we are scanning a directory, since the scan will pick up the
570          * -o file anyway.
571          */
572         if (All_forts && parent == NULL && !is_off_name(path))
573                 all_forts(fp, offensive);
574         if (*head == NULL)
575                 *head = *tail = fp;
576         else if (fp->percent == NO_PROB) {
577                 (*tail)->next = fp;
578                 fp->prev = *tail;
579                 *tail = fp;
580         }
581         else {
582                 (*head)->prev = fp;
583                 fp->next = *head;
584                 *head = fp;
585         }
586         if (WriteToDisk)
587                 fp->was_pos_file = (access(fp->posfile, W_OK) >= 0);
588
589         return (TRUE);
590 }
591
592 /*
593  * new_fp:
594  *      Return a pointer to an initialized new FILEDESC.
595  */
596 static FILEDESC *
597 new_fp(void)
598 {
599         FILEDESC        *fp;
600
601         fp = do_malloc(sizeof(*fp));
602         fp->datfd = -1;
603         fp->pos = POS_UNKNOWN;
604         fp->inf = NULL;
605         fp->fd = -1;
606         fp->percent = NO_PROB;
607         fp->read_tbl = FALSE;
608         fp->next = NULL;
609         fp->prev = NULL;
610         fp->child = NULL;
611         fp->parent = NULL;
612         fp->datfile = NULL;
613         fp->posfile = NULL;
614
615         return (fp);
616 }
617
618 /*
619  * off_name:
620  *      Return a pointer to the offensive version of a file of this name.
621  */
622 static char *
623 off_name(const char *file)
624 {
625         char    *new;
626
627         new = copy(file, (unsigned int) (strlen(file) + 2));
628
629         return (strcat(new, "-o"));
630 }
631
632 /*
633  * is_off_name:
634  *      Is the file an offensive-style name?
635  */
636 static int
637 is_off_name(const char *file)
638 {
639         int     len;
640
641         len = strlen(file);
642
643         return (len >= 3 && file[len - 2] == '-' && file[len - 1] == 'o');
644 }
645
646 /*
647  * all_forts:
648  *      Modify a FILEDESC element to be the parent of two children if
649  *      there are two children to be a parent of.
650  */
651 static void
652 all_forts(FILEDESC *fp, char *offensive)
653 {
654         char            *sp;
655         FILEDESC        *scene, *obscene;
656         int             fd;
657         char            *datfile, *posfile;
658
659         if (fp->child != NULL)  /* this is a directory, not a file */
660                 return;
661         if (!is_fortfile(offensive, &datfile, &posfile, FALSE))
662                 return;
663         if ((fd = open(offensive, O_RDONLY)) < 0)
664                 return;
665         DPRINTF(1, (stderr, "adding \"%s\" because of -a\n", offensive));
666         scene = new_fp();
667         obscene = new_fp();
668         *scene = *fp;
669
670         fp->num_children = 2;
671         fp->child = scene;
672         scene->next = obscene;
673         obscene->next = NULL;
674         scene->child = obscene->child = NULL;
675         scene->parent = obscene->parent = fp;
676
677         fp->fd = -1;
678         scene->percent = obscene->percent = NO_PROB;
679
680         obscene->fd = fd;
681         obscene->inf = NULL;
682         obscene->path = offensive;
683         if ((sp = strrchr(offensive, '/')) == NULL)
684                 obscene->name = offensive;
685         else
686                 obscene->name = ++sp;
687         obscene->datfile = datfile;
688         obscene->posfile = posfile;
689         obscene->read_tbl = false;
690         if (WriteToDisk)
691                 obscene->was_pos_file = (access(obscene->posfile, W_OK) >= 0);
692 }
693
694 /*
695  * add_dir:
696  *      Add the contents of an entire directory.
697  */
698 static int
699 add_dir(FILEDESC *fp)
700 {
701         DIR             *dir;
702         struct dirent   *dirent;
703         FILEDESC        *tailp;
704         char            *name;
705
706         (void) close(fp->fd);
707         fp->fd = -1;
708         if ((dir = opendir(fp->path)) == NULL) {
709                 perror(fp->path);
710                 return (FALSE);
711         }
712         tailp = NULL;
713         DPRINTF(1, (stderr, "adding dir \"%s\"\n", fp->path));
714         fp->num_children = 0;
715         while ((dirent = readdir(dir)) != NULL) {
716                 if (dirent->d_namlen == 0)
717                         continue;
718                 name = copy(dirent->d_name, dirent->d_namlen);
719                 if (add_file(NO_PROB, name, fp->path, &fp->child, &tailp, fp))
720                         fp->num_children++;
721                 else
722                         free(name);
723         }
724         if (fp->num_children == 0) {
725                 (void) fprintf(stderr,
726                     "fortune: %s: No fortune files in directory.\n", fp->path);
727                 return (FALSE);
728         }
729
730         return (TRUE);
731 }
732
733 /*
734  * is_dir:
735  *      Return TRUE if the file is a directory, FALSE otherwise.
736  */
737 static int
738 is_dir(const char *file)
739 {
740         struct stat     sbuf;
741
742         if (stat(file, &sbuf) < 0)
743                 return (FALSE);
744
745         return (sbuf.st_mode & S_IFDIR);
746 }
747
748 /*
749  * is_fortfile:
750  *      Return TRUE if the file is a fortune database file.  We try and
751  *      exclude files without reading them if possible to avoid
752  *      overhead.  Files which start with ".", or which have "illegal"
753  *      suffixes, as contained in suflist[], are ruled out.
754  */
755 /* ARGSUSED */
756 static int
757 is_fortfile(const char *file, char **datp, char **posp, int check_for_offend)
758 {
759         int     i;
760         const char      *sp;
761         char    *datfile;
762         static const char *suflist[] = {
763                 /* list of "illegal" suffixes" */
764                 "dat", "pos", "c", "h", "p", "i", "f",
765                 "pas", "ftn", "ins.c", "ins,pas",
766                 "ins.ftn", "sml",
767                 NULL
768         };
769
770         DPRINTF(2, (stderr, "is_fortfile(%s) returns ", file));
771
772         /*
773          * Preclude any -o files for offendable people, and any non -o
774          * files for completely offensive people.
775          */
776         if (check_for_offend && !All_forts) {
777                 i = strlen(file);
778                 if (Offend ^ (file[i - 2] == '-' && file[i - 1] == 'o')) {
779                         DPRINTF(2, (stderr, "FALSE (offending file)\n"));
780                         return (FALSE);
781                 }
782         }
783
784         if ((sp = strrchr(file, '/')) == NULL)
785                 sp = file;
786         else
787                 sp++;
788         if (*sp == '.') {
789                 DPRINTF(2, (stderr, "FALSE (file starts with '.')\n"));
790                 return (FALSE);
791         }
792         if (Fortunes_only && strncmp(sp, "fortunes", 8) != 0) {
793                 DPRINTF(2, (stderr, "FALSE (check fortunes only)\n"));
794                 return (FALSE);
795         }
796         if ((sp = strrchr(sp, '.')) != NULL) {
797                 sp++;
798                 for (i = 0; suflist[i] != NULL; i++)
799                         if (strcmp(sp, suflist[i]) == 0) {
800                                 DPRINTF(2, (stderr, "FALSE (file has suffix \".%s\")\n", sp));
801                                 return (FALSE);
802                         }
803         }
804
805         datfile = copy(file, (unsigned int) (strlen(file) + 4)); /* +4 for ".dat" */
806         strcat(datfile, ".dat");
807         if (access(datfile, R_OK) < 0) {
808                 DPRINTF(2, (stderr, "FALSE (no readable \".dat\" file)\n"));
809                 free(datfile);
810                 return (FALSE);
811         }
812         if (datp != NULL)
813                 *datp = datfile;
814         else
815                 free(datfile);
816         if (posp != NULL) {
817                 if (WriteToDisk) {
818                         *posp = copy(file, (unsigned int) (strlen(file) + 4)); /* +4 for ".dat" */
819                         strcat(*posp, ".pos");
820                 }
821                 else {
822                         *posp = NULL;
823                 }
824         }
825         DPRINTF(2, (stderr, "TRUE\n"));
826
827         return (TRUE);
828 }
829
830 /*
831  * copy:
832  *      Return a malloc()'ed copy of the string
833  */
834 static char *
835 copy(const char *str, unsigned int len)
836 {
837         char *new, *sp;
838
839         new = do_malloc(len + 1);
840         sp = new;
841         do {
842                 *sp++ = *str;
843         } while (*str++);
844
845         return (new);
846 }
847
848 /*
849  * do_malloc:
850  *      Do a malloc, checking for NULL return.
851  */
852 static void *
853 do_malloc(unsigned int size)
854 {
855         void *new;
856
857         if ((new = malloc(size)) == NULL) {
858                 (void) fprintf(stderr, "fortune: out of memory.\n");
859                 exit(1);
860         }
861
862         return (new);
863 }
864
865 /*
866  * do_free:
867  *      Free malloc'ed space, if any.
868  */
869 static void
870 do_free(void *ptr)
871 {
872         if (ptr != NULL)
873                 free(ptr);
874 }
875
876 /*
877  * init_prob:
878  *      Initialize the fortune probabilities.
879  */
880 static void
881 init_prob(void)
882 {
883         FILEDESC       *fp, *last = NULL;
884         int             percent, num_noprob, frac;
885
886         /*
887          * Distribute the residual probability (if any) across all
888          * files with unspecified probability (i.e., probability of 0)
889          * (if any).
890          */
891
892         percent = 0;
893         num_noprob = 0;
894         for (fp = File_tail; fp != NULL; fp = fp->prev)
895                 if (fp->percent == NO_PROB) {
896                         num_noprob++;
897                         if (Equal_probs)
898                                 last = fp;
899                 } else
900                         percent += fp->percent;
901         DPRINTF(1, (stderr, "summing probabilities:%d%% with %d NO_PROB's",
902                     percent, num_noprob));
903         if (percent > 100) {
904                 (void) fprintf(stderr,
905                     "fortune: probabilities sum to %d%% > 100%%!\n", percent);
906                 exit(1);
907         } else if (percent < 100 && num_noprob == 0) {
908                 (void) fprintf(stderr,
909                     "fortune: no place to put residual probability (%d%% < 100%%)\n",
910                     percent);
911                 exit(1);
912         } else if (percent == 100 && num_noprob != 0) {
913                 (void) fprintf(stderr,
914                     "fortune: no probability left to put in residual files (100%%)\n");
915                 exit(1);
916         }
917         percent = 100 - percent;
918         if (Equal_probs) {
919                 if (num_noprob != 0) {
920                         if (num_noprob > 1) {
921                                 frac = percent / num_noprob;
922                                 DPRINTF(1, (stderr, ", frac = %d%%", frac));
923                                 for (fp = File_tail; fp != last; fp = fp->prev)
924                                         if (fp->percent == NO_PROB) {
925                                                 fp->percent = frac;
926                                                 percent -= frac;
927                                         }
928                         }
929                         last->percent = percent;
930                         DPRINTF(1, (stderr, ", residual = %d%%", percent));
931                 }
932                 else
933                 DPRINTF(1, (stderr,
934                             ", %d%% distributed over remaining fortunes\n",
935                             percent));
936         }
937         DPRINTF(1, (stderr, "\n"));
938
939 #ifdef DEBUG
940         if (Debug >= 1)
941                 print_file_list();
942 #endif
943 }
944
945 /*
946  * get_fort:
947  *      Get the fortune data file's seek pointer for the next fortune.
948  */
949 static void
950 get_fort(void)
951 {
952         FILEDESC        *fp;
953         int             choice;
954
955         if (File_list->next == NULL || File_list->percent == NO_PROB)
956                 fp = File_list;
957         else {
958                 choice = arc4random_uniform(100);
959                 DPRINTF(1, (stderr, "choice = %d\n", choice));
960                 for (fp = File_list; fp->percent != NO_PROB; fp = fp->next)
961                         if (choice < fp->percent)
962                                 break;
963                         else {
964                                 choice -= fp->percent;
965                                 DPRINTF(1, (stderr,
966                                             "    skip \"%s\", %d%% (choice = %d)\n",
967                                             fp->name, fp->percent, choice));
968                         }
969                         DPRINTF(1, (stderr,
970                                     "using \"%s\", %d%% (choice = %d)\n",
971                                     fp->name, fp->percent, choice));
972         }
973         if (fp->percent != NO_PROB)
974                 get_tbl(fp);
975         else {
976                 if (fp->next != NULL) {
977                         sum_noprobs(fp);
978                         choice = arc4random_uniform(Noprob_tbl.str_numstr);
979                         DPRINTF(1, (stderr, "choice = %d (of %u) \n", choice,
980                                     Noprob_tbl.str_numstr));
981                         while ((unsigned int)choice >= fp->tbl.str_numstr) {
982                                 choice -= fp->tbl.str_numstr;
983                                 fp = fp->next;
984                                 DPRINTF(1, (stderr,
985                                             "    skip \"%s\", %u (choice = %d)\n",
986                                             fp->name, fp->tbl.str_numstr,
987                                             choice));
988                         }
989                         DPRINTF(1, (stderr, "using \"%s\", %u\n", fp->name,
990                                     fp->tbl.str_numstr));
991                 }
992                 get_tbl(fp);
993         }
994         if (fp->child != NULL) {
995                 DPRINTF(1, (stderr, "picking child\n"));
996                 fp = pick_child(fp);
997         }
998         Fortfile = fp;
999         get_pos(fp);
1000         open_dat(fp);
1001         lseek(fp->datfd,
1002             (off_t) (sizeof fp->tbl + fp->pos * sizeof Seekpts[0]), SEEK_SET);
1003         read(fp->datfd, Seekpts, sizeof Seekpts);
1004         Seekpts[0] = be64toh(Seekpts[0]);
1005         Seekpts[1] = be64toh(Seekpts[1]);
1006 }
1007
1008 /*
1009  * pick_child
1010  *      Pick a child from a chosen parent.
1011  */
1012 static FILEDESC *
1013 pick_child(FILEDESC *parent)
1014 {
1015         FILEDESC        *fp;
1016         int             choice;
1017
1018         if (Equal_probs) {
1019                 choice = arc4random_uniform(parent->num_children);
1020                 DPRINTF(1, (stderr, "    choice = %d (of %d)\n",
1021                             choice, parent->num_children));
1022                 for (fp = parent->child; choice--; fp = fp->next)
1023                         continue;
1024                 DPRINTF(1, (stderr, "    using %s\n", fp->name));
1025                 return (fp);
1026         }
1027         else {
1028                 get_tbl(parent);
1029                 choice = arc4random_uniform(parent->tbl.str_numstr);
1030                 DPRINTF(1, (stderr, "    choice = %d (of %u)\n",
1031                             choice, parent->tbl.str_numstr));
1032                 for (fp = parent->child; (unsigned)choice >= fp->tbl.str_numstr;
1033                      fp = fp->next) {
1034                         choice -= fp->tbl.str_numstr;
1035                         DPRINTF(1, (stderr, "\tskip %s, %u (choice = %d)\n",
1036                                     fp->name, fp->tbl.str_numstr, choice));
1037                 }
1038                 DPRINTF(1, (stderr, "    using %s, %u\n", fp->name,
1039                             fp->tbl.str_numstr));
1040                 return (fp);
1041         }
1042 }
1043
1044 /*
1045  * sum_noprobs:
1046  *      Sum up all the noprob probabilities, starting with fp.
1047  */
1048 static void
1049 sum_noprobs(FILEDESC *fp)
1050 {
1051         static bool     did_noprobs = FALSE;
1052
1053         if (did_noprobs)
1054                 return;
1055         zero_tbl(&Noprob_tbl);
1056         while (fp != NULL) {
1057                 get_tbl(fp);
1058                 sum_tbl(&Noprob_tbl, &fp->tbl);
1059                 fp = fp->next;
1060         }
1061         did_noprobs = TRUE;
1062 }
1063
1064 static int
1065 max(int i, int j)
1066 {
1067         return (i >= j ? i : j);
1068 }
1069
1070 /*
1071  * open_fp:
1072  *      Assocatiate a FILE * with the given FILEDESC.
1073  */
1074 static void
1075 open_fp(FILEDESC *fp)
1076 {
1077         if (fp->inf == NULL && (fp->inf = fdopen(fp->fd, "r")) == NULL) {
1078                 perror(fp->path);
1079                 exit(1);
1080         }
1081 }
1082
1083 /*
1084  * open_dat:
1085  *      Open up the dat file if we need to.
1086  */
1087 static void
1088 open_dat(FILEDESC *fp)
1089 {
1090         if (fp->datfd < 0 && (fp->datfd = open(fp->datfile, O_RDONLY)) < 0) {
1091                 perror(fp->datfile);
1092                 exit(1);
1093         }
1094 }
1095
1096 /*
1097  * get_pos:
1098  *      Get the position from the pos file, if there is one.  If not,
1099  *      return a random number.
1100  */
1101 static void
1102 get_pos(FILEDESC *fp)
1103 {
1104         int     fd;
1105
1106         assert(fp->read_tbl);
1107         if (fp->pos == POS_UNKNOWN) {
1108                 if (WriteToDisk) {
1109                         if ((fd = open(fp->posfile, O_RDONLY)) < 0 ||
1110                             read(fd, &fp->pos, sizeof fp->pos) != sizeof fp->pos)
1111                                 fp->pos = arc4random_uniform(fp->tbl.str_numstr);
1112                         else if (fp->pos >= fp->tbl.str_numstr)
1113                                 fp->pos %= fp->tbl.str_numstr;
1114                         if (fd >= 0)
1115                                 close(fd);
1116                 }
1117                 else
1118                         fp->pos = arc4random_uniform(fp->tbl.str_numstr);
1119         }
1120         if (++(fp->pos) >= fp->tbl.str_numstr)
1121                 fp->pos -= fp->tbl.str_numstr;
1122         DPRINTF(1, (stderr, "pos for %s is %ld\n", fp->name, (long)fp->pos));
1123 }
1124
1125 /*
1126  * get_tbl:
1127  *      Get the tbl data file the datfile.
1128  */
1129 static void
1130 get_tbl(FILEDESC *fp)
1131 {
1132         int             fd;
1133         FILEDESC        *child;
1134
1135         if (fp->read_tbl)
1136                 return;
1137         if (fp->child == NULL) {
1138                 if ((fd = open(fp->datfile, O_RDONLY)) < 0) {
1139                         perror(fp->datfile);
1140                         exit(1);
1141                 }
1142                 if (read(fd, (char *) &fp->tbl, sizeof fp->tbl) != sizeof fp->tbl) {
1143                         (void)fprintf(stderr,
1144                             "fortune: %s corrupted\n", fp->path);
1145                         exit(1);
1146                 }
1147                 /* fp->tbl.str_version = be32toh(fp->tbl.str_version); */
1148                 fp->tbl.str_numstr = be32toh(fp->tbl.str_numstr);
1149                 fp->tbl.str_longlen = be32toh(fp->tbl.str_longlen);
1150                 fp->tbl.str_shortlen = be32toh(fp->tbl.str_shortlen);
1151                 fp->tbl.str_flags = be32toh(fp->tbl.str_flags);
1152                 (void) close(fd);
1153         }
1154         else {
1155                 zero_tbl(&fp->tbl);
1156                 for (child = fp->child; child != NULL; child = child->next) {
1157                         get_tbl(child);
1158                         sum_tbl(&fp->tbl, &child->tbl);
1159                 }
1160         }
1161         fp->read_tbl = TRUE;
1162 }
1163
1164 /*
1165  * zero_tbl:
1166  *      Zero out the fields we care about in a tbl structure.
1167  */
1168 static void
1169 zero_tbl(STRFILE *tp)
1170 {
1171         tp->str_numstr = 0;
1172         tp->str_longlen = 0;
1173         tp->str_shortlen = ~0;
1174 }
1175
1176 /*
1177  * sum_tbl:
1178  *      Merge the tbl data of t2 into t1.
1179  */
1180 static void
1181 sum_tbl(STRFILE *t1, STRFILE *t2)
1182 {
1183         t1->str_numstr += t2->str_numstr;
1184         if (t1->str_longlen < t2->str_longlen)
1185                 t1->str_longlen = t2->str_longlen;
1186         if (t1->str_shortlen > t2->str_shortlen)
1187                 t1->str_shortlen = t2->str_shortlen;
1188 }
1189
1190 #define STR(str)        ((str) == NULL ? "NULL" : (str))
1191
1192 /*
1193  * print_file_list:
1194  *      Print out the file list
1195  */
1196 static void
1197 print_file_list(void)
1198 {
1199         print_list(File_list, 0);
1200 }
1201
1202 /*
1203  * print_list:
1204  *      Print out the actual list, recursively.
1205  */
1206 static void
1207 print_list(FILEDESC *list, int lev)
1208 {
1209         while (list != NULL) {
1210                 fprintf(stderr, "%*s", lev * 4, "");
1211                 if (list->percent == NO_PROB)
1212                         fprintf(stderr, "___%%");
1213                 else
1214                         fprintf(stderr, "%3d%%", list->percent);
1215                 fprintf(stderr, " %s", STR(list->name));
1216                 DPRINTF(1, (stderr, " (%s, %s, %s)", STR(list->path),
1217                             STR(list->datfile), STR(list->posfile)));
1218                 fprintf(stderr, "\n");
1219                 if (list->child != NULL)
1220                         print_list(list->child, lev + 1);
1221                 list = list->next;
1222         }
1223 }
1224
1225 /*
1226  * conv_pat:
1227  *      Convert the pattern to an ignore-case equivalent.
1228  */
1229 static char *
1230 conv_pat(char *orig)
1231 {
1232         char            *sp;
1233         unsigned int    cnt;
1234         char            *new;
1235
1236         cnt = 1;        /* allow for '\0' */
1237         for (sp = orig; *sp != '\0'; sp++)
1238                 if (isalpha((unsigned char)*sp))
1239                         cnt += 4;
1240                 else
1241                         cnt++;
1242         if ((new = malloc(cnt)) == NULL) {
1243                 fprintf(stderr, "pattern too long for ignoring case\n");
1244                 exit(1);
1245         }
1246
1247         for (sp = new; *orig != '\0'; orig++) {
1248                 if (islower((unsigned char)*orig)) {
1249                         *sp++ = '[';
1250                         *sp++ = *orig;
1251                         *sp++ = toupper((unsigned char)*orig);
1252                         *sp++ = ']';
1253                 }
1254                 else if (isupper((unsigned char)*orig)) {
1255                         *sp++ = '[';
1256                         *sp++ = *orig;
1257                         *sp++ = tolower((unsigned char)*orig);
1258                         *sp++ = ']';
1259                 }
1260                 else
1261                         *sp++ = *orig;
1262         }
1263         *sp = '\0';
1264
1265         return (new);
1266 }
1267
1268 /*
1269  * find_matches:
1270  *      Find all the fortunes which match the pattern we've been given.
1271  */
1272 static int
1273 find_matches(void)
1274 {
1275         Fort_len = maxlen_in_list(File_list);
1276         DPRINTF(2, (stderr, "Maximum length is %d\n", Fort_len));
1277         /* extra length, "%\n" is appended */
1278         Fortbuf = do_malloc((unsigned int) Fort_len + 10);
1279
1280         Found_one = FALSE;
1281         matches_in_list(File_list);
1282
1283         return (Found_one);
1284 }
1285
1286 /*
1287  * maxlen_in_list
1288  *      Return the maximum fortune len in the file list.
1289  */
1290 static int
1291 maxlen_in_list(FILEDESC *list)
1292 {
1293         FILEDESC        *fp;
1294         int             len, maxlen;
1295
1296         maxlen = 0;
1297         for (fp = list; fp != NULL; fp = fp->next) {
1298                 if (fp->child != NULL) {
1299                         if ((len = maxlen_in_list(fp->child)) > maxlen)
1300                                 maxlen = len;
1301                 }
1302                 else {
1303                         get_tbl(fp);
1304                         if (fp->tbl.str_longlen > (unsigned int)maxlen)
1305                                 maxlen = fp->tbl.str_longlen;
1306                 }
1307         }
1308
1309         return (maxlen);
1310 }
1311
1312 /*
1313  * matches_in_list
1314  *      Print out the matches from the files in the list.
1315  */
1316 static void
1317 matches_in_list(FILEDESC *list)
1318 {
1319         char           *sp, *p;
1320         FILEDESC        *fp;
1321         int             in_file;
1322         unsigned char   ch;
1323
1324         for (fp = list; fp != NULL; fp = fp->next) {
1325                 if (fp->child != NULL) {
1326                         matches_in_list(fp->child);
1327                         continue;
1328                 }
1329                 DPRINTF(1, (stderr, "searching in %s\n", fp->path));
1330                 open_fp(fp);
1331                 sp = Fortbuf;
1332                 in_file = FALSE;
1333                 while (fgets(sp, Fort_len, fp->inf) != NULL)
1334                         if (fp->tbl.str_flags & STR_COMMENTS
1335                             && sp[0] == fp->tbl.str_delim
1336                             && sp[1] == fp->tbl.str_delim)
1337                                 continue;
1338                         else if (!STR_ENDSTRING(sp, fp->tbl))
1339                                 sp += strlen(sp);
1340                         else {
1341                                 *sp = '\0';
1342                                 if (fp->tbl.str_flags & STR_ROTATED)
1343                                         for (p = Fortbuf; (ch = *p) != '\0'; ++p) {
1344                                                 if (isascii(ch)) {
1345                                                         if (isupper(ch))
1346                                                                 *p = 'A' + (ch - 'A' + 13) % 26;
1347                                                         else if (islower(ch))
1348                                                                 *p = 'a' + (ch - 'a' + 13) % 26;
1349                                                 }
1350                                         }
1351                                 if (regexec(&Re_pat, Fortbuf, 0, NULL, 0) != REG_NOMATCH) {
1352                                         printf("%c%c", fp->tbl.str_delim,
1353                                             fp->tbl.str_delim);
1354                                         if (!in_file) {
1355                                                 printf(" (%s)", fp->name);
1356                                                 Found_one = TRUE;
1357                                                 in_file = TRUE;
1358                                         }
1359                                         putchar('\n');
1360                                         (void) fwrite(Fortbuf, 1, (sp - Fortbuf), stdout);
1361                                 }
1362                                 sp = Fortbuf;
1363                         }
1364         }
1365 }
1366
1367 static void
1368 usage(void)
1369 {
1370         (void) fprintf(stderr, "fortune [-a");
1371 #ifdef  DEBUG
1372         (void) fprintf(stderr, "D");
1373 #endif  /* DEBUG */
1374         (void) fprintf(stderr, "efilosw]");
1375         (void) fprintf(stderr, " [-m pattern]");
1376         (void) fprintf(stderr, " [[N%%] file/directory/all]\n");
1377         exit(1);
1378 }
1379
1380 /*
1381  * getpath
1382  *      Set up file search patch from environment var FORTUNE_PATH;
1383  *      if not set, use the compiled in FORTDIR.
1384  */
1385
1386 static void
1387 getpath(void)
1388 {
1389         int     nstr, foundenv;
1390         char    *pch, **ppch, *str, *path;
1391
1392         foundenv = 1;
1393         Fortune_path = getenv("FORTUNE_PATH");
1394         if (Fortune_path == NULL) {
1395                 Fortune_path = FORTDIR;
1396                 foundenv = 0;
1397         }
1398         path = strdup(Fortune_path);
1399
1400         for (nstr = 2, pch = path; *pch != '\0'; pch++) {
1401                 if (*pch == ':')
1402                         nstr++;
1403         }
1404
1405         ppch = Fortune_path_arr = (char **)calloc(nstr, sizeof(char *));
1406         
1407         nstr = 0;
1408         str = strtok(path, ":");
1409         while (str) {
1410                 if (is_dir(str)) {
1411                         nstr++;
1412                         *ppch++ = str;
1413                 }
1414                 str = strtok(NULL, ":");
1415         }
1416
1417         if (nstr == 0) {
1418                 if (foundenv == 1) {
1419                         fprintf(stderr,
1420                             "fortune: FORTUNE_PATH: None of the specified "
1421                             "directories found.\n");
1422                         exit(1);
1423                 }
1424                 free(path);
1425                 Fortune_path_arr[0] = strdup(FORTDIR);
1426         }
1427 }