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