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