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