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