xref: /dragonfly/games/fortune/fortune/fortune.c (revision 509221ae)
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.4 2005/08/08 15:25:42 joerg 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(ac, av)
182 int	ac;
183 char	*av[];
184 {
185 #ifdef	OK_TO_WRITE_DISK
186 	int	fd;
187 #endif	/* OK_TO_WRITE_DISK */
188 
189 	(void) setlocale(LC_ALL, "");
190 
191 	getargs(ac, av);
192 
193 #ifndef NO_REGEX
194 	if (Match)
195 		exit(find_matches() != 0);
196 #endif
197 
198 	init_prob();
199 	srandomdev();
200 	do {
201 		get_fort();
202 	} while ((Short_only && fortlen() > SLEN) ||
203 		 (Long_only && fortlen() <= SLEN));
204 
205 	display(Fortfile);
206 
207 #ifdef	OK_TO_WRITE_DISK
208 	if ((fd = creat(Fortfile->posfile, 0666)) < 0) {
209 		perror(Fortfile->posfile);
210 		exit(1);
211 	}
212 #ifdef	LOCK_EX
213 	/*
214 	 * if we can, we exclusive lock, but since it isn't very
215 	 * important, we just punt if we don't have easy locking
216 	 * available.
217 	 */
218 	(void) flock(fd, LOCK_EX);
219 #endif	/* LOCK_EX */
220 	write(fd, (char *) &Fortfile->pos, sizeof Fortfile->pos);
221 	if (!Fortfile->was_pos_file)
222 		(void) chmod(Fortfile->path, 0666);
223 #ifdef	LOCK_EX
224 	(void) flock(fd, LOCK_UN);
225 #endif	/* LOCK_EX */
226 #endif	/* OK_TO_WRITE_DISK */
227 	if (Wait) {
228 		if (Fort_len == 0)
229 			(void) fortlen();
230 		sleep((unsigned int) max(Fort_len / CPERS, MINW));
231 	}
232 	exit(0);
233 	/* NOTREACHED */
234 }
235 
236 void
237 display(fp)
238 FILEDESC	*fp;
239 {
240 	char   *p;
241 	unsigned char ch;
242 	char	line[BUFSIZ];
243 
244 	open_fp(fp);
245 	(void) fseek(fp->inf, Seekpts[0], 0);
246 	for (Fort_len = 0; fgets(line, sizeof line, fp->inf) != NULL &&
247 	    !STR_ENDSTRING(line, fp->tbl); Fort_len++) {
248 		if (fp->tbl.str_flags & STR_ROTATED)
249 			for (p = line; (ch = *p) != '\0'; ++p) {
250 				if (isascii(ch)) {
251 					if (isupper(ch))
252 						*p = 'A' + (ch - 'A' + 13) % 26;
253 					else if (islower(ch))
254 						*p = 'a' + (ch - 'a' + 13) % 26;
255 				}
256 			}
257 		if (fp->tbl.str_flags & STR_COMMENTS
258 		    && line[0] == fp->tbl.str_delim
259 		    && line[1] == fp->tbl.str_delim)
260 			continue;
261 		fputs(line, stdout);
262 	}
263 	(void) fflush(stdout);
264 }
265 
266 /*
267  * fortlen:
268  *	Return the length of the fortune.
269  */
270 int
271 fortlen()
272 {
273 	int	nchar;
274 	char		line[BUFSIZ];
275 
276 	if (!(Fortfile->tbl.str_flags & (STR_RANDOM | STR_ORDERED)))
277 		nchar = (Seekpts[1] - Seekpts[0] <= SLEN);
278 	else {
279 		open_fp(Fortfile);
280 		(void) fseek(Fortfile->inf, Seekpts[0], 0);
281 		nchar = 0;
282 		while (fgets(line, sizeof line, Fortfile->inf) != NULL &&
283 		       !STR_ENDSTRING(line, Fortfile->tbl))
284 			nchar += strlen(line);
285 	}
286 	Fort_len = nchar;
287 	return nchar;
288 }
289 
290 /*
291  *	This routine evaluates the arguments on the command line
292  */
293 void
294 getargs(argc, argv)
295 int	argc;
296 char	**argv;
297 {
298 	int	ignore_case;
299 # ifndef NO_REGEX
300 	char	*pat;
301 # endif	/* NO_REGEX */
302 	extern char *optarg;
303 	extern int optind;
304 	int ch;
305 
306 	ignore_case = FALSE;
307 # ifndef NO_REGEX
308 	pat = NULL;
309 # endif /* NO_REGEX */
310 
311 # ifdef DEBUG
312 	while ((ch = getopt(argc, argv, "aDefilm:osw")) != -1)
313 #else
314 	while ((ch = getopt(argc, argv, "aefilm:osw")) != -1)
315 #endif /* DEBUG */
316 		switch(ch) {
317 		case 'a':		/* any fortune */
318 			All_forts++;
319 			break;
320 # ifdef DEBUG
321 		case 'D':
322 			Debug++;
323 			break;
324 # endif /* DEBUG */
325 		case 'e':
326 			Equal_probs++;	/* scatter un-allocted prob equally */
327 			break;
328 		case 'f':		/* find fortune files */
329 			Find_files++;
330 			break;
331 		case 'l':		/* long ones only */
332 			Long_only++;
333 			Short_only = FALSE;
334 			break;
335 		case 'o':		/* offensive ones only */
336 			Offend++;
337 			break;
338 		case 's':		/* short ones only */
339 			Short_only++;
340 			Long_only = FALSE;
341 			break;
342 		case 'w':		/* give time to read */
343 			Wait++;
344 			break;
345 # ifdef	NO_REGEX
346 		case 'i':			/* case-insensitive match */
347 		case 'm':			/* dump out the fortunes */
348 			(void) fprintf(stderr,
349 			    "fortune: can't match fortunes on this system (Sorry)\n");
350 			exit(0);
351 # else	/* NO_REGEX */
352 		case 'm':			/* dump out the fortunes */
353 			Match++;
354 			pat = optarg;
355 			break;
356 		case 'i':			/* case-insensitive match */
357 			ignore_case++;
358 			break;
359 # endif	/* NO_REGEX */
360 		case '?':
361 		default:
362 			usage();
363 		}
364 	argc -= optind;
365 	argv += optind;
366 
367 	if (!form_file_list(argv, argc))
368 		exit(1);	/* errors printed through form_file_list() */
369 	if (Find_files) {
370 		print_file_list();
371 		exit(0);
372 	}
373 #ifdef DEBUG
374 	else if (Debug >= 1)
375 		print_file_list();
376 #endif /* DEBUG */
377 
378 # ifndef NO_REGEX
379 	if (pat != NULL) {
380 		if (ignore_case)
381 			pat = conv_pat(pat);
382 		if (BAD_COMP(RE_COMP(pat))) {
383 #ifndef REGCMP
384 			fprintf(stderr, "%s\n", pat);
385 #else	/* REGCMP */
386 			fprintf(stderr, "bad pattern: %s\n", pat);
387 #endif	/* REGCMP */
388 		}
389 	}
390 # endif	/* NO_REGEX */
391 }
392 
393 /*
394  * form_file_list:
395  *	Form the file list from the file specifications.
396  */
397 int
398 form_file_list(files, file_cnt)
399 char	**files;
400 int	file_cnt;
401 {
402 	int	i, percent;
403 	char	*sp;
404 
405 	if (file_cnt == 0) {
406 		if (Find_files) {
407 			Fortunes_only = TRUE;
408 			i = add_file(NO_PROB, FORTDIR, NULL, &File_list,
409 					&File_tail, NULL);
410 			Fortunes_only = FALSE;
411 			return i;
412 		} else
413 			return add_file(NO_PROB, "fortunes", FORTDIR,
414 					&File_list, &File_tail, NULL);
415 	}
416 	for (i = 0; i < file_cnt; i++) {
417 		percent = NO_PROB;
418 		if (!isdigit((unsigned char)files[i][0]))
419 			sp = files[i];
420 		else {
421 			percent = 0;
422 			for (sp = files[i]; isdigit((unsigned char)*sp); sp++)
423 				percent = percent * 10 + *sp - '0';
424 			if (percent > 100) {
425 				fprintf(stderr, "percentages must be <= 100\n");
426 				return FALSE;
427 			}
428 			if (*sp == '.') {
429 				fprintf(stderr, "percentages must be integers\n");
430 				return FALSE;
431 			}
432 			/*
433 			 * If the number isn't followed by a '%', then
434 			 * it was not a percentage, just the first part
435 			 * of a file name which starts with digits.
436 			 */
437 			if (*sp != '%') {
438 				percent = NO_PROB;
439 				sp = files[i];
440 			}
441 			else if (*++sp == '\0') {
442 				if (++i >= file_cnt) {
443 					fprintf(stderr, "percentages must precede files\n");
444 					return FALSE;
445 				}
446 				sp = files[i];
447 			}
448 		}
449 		if (strcmp(sp, "all") == 0)
450 			sp = FORTDIR;
451 		if (!add_file(percent, sp, NULL, &File_list, &File_tail, NULL))
452 			return FALSE;
453 	}
454 	return TRUE;
455 }
456 
457 /*
458  * add_file:
459  *	Add a file to the file list.
460  */
461 int
462 add_file(percent, file, dir, head, tail, parent)
463 int		percent;
464 char	*file;
465 char		*dir;
466 FILEDESC	**head, **tail;
467 FILEDESC	*parent;
468 {
469 	FILEDESC	*fp;
470 	int		fd;
471 	char		*path, *offensive;
472 	bool		was_malloc;
473 	bool		isdir;
474 
475 	if (dir == NULL) {
476 		path = file;
477 		was_malloc = FALSE;
478 	}
479 	else {
480 		path = do_malloc((unsigned int) (strlen(dir) + strlen(file) + 2));
481 		(void) strcat(strcat(strcpy(path, dir), "/"), file);
482 		was_malloc = TRUE;
483 	}
484 	if ((isdir = is_dir(path)) && parent != NULL) {
485 		if (was_malloc)
486 			free(path);
487 		return FALSE;	/* don't recurse */
488 	}
489 	offensive = NULL;
490 	if (!isdir && parent == NULL && (All_forts || Offend) &&
491 	    !is_off_name(path)) {
492 		offensive = off_name(path);
493 		if (Offend) {
494 			if (was_malloc)
495 				free(path);
496 			path = offensive;
497 			offensive = NULL;
498 			was_malloc = TRUE;
499 			DPRINTF(1, (stderr, "\ttrying \"%s\"\n", path));
500 			file = off_name(file);
501 		}
502 	}
503 
504 	DPRINTF(1, (stderr, "adding file \"%s\"\n", path));
505 over:
506 	if ((fd = open(path, 0)) < 0) {
507 		/*
508 		 * This is a sneak.  If the user said -a, and if the
509 		 * file we're given isn't a file, we check to see if
510 		 * there is a -o version.  If there is, we treat it as
511 		 * if *that* were the file given.  We only do this for
512 		 * individual files -- if we're scanning a directory,
513 		 * we'll pick up the -o file anyway.
514 		 */
515 		if (All_forts && offensive != NULL) {
516 			if (was_malloc)
517 				free(path);
518 			path = offensive;
519 			offensive = NULL;
520 			was_malloc = TRUE;
521 			DPRINTF(1, (stderr, "\ttrying \"%s\"\n", path));
522 			file = off_name(file);
523 			goto over;
524 		}
525 		if (dir == NULL && file[0] != '/')
526 			return add_file(percent, file, FORTDIR, head, tail,
527 					parent);
528 		if (parent == NULL)
529 			perror(path);
530 		if (was_malloc)
531 			free(path);
532 		return FALSE;
533 	}
534 
535 	DPRINTF(2, (stderr, "path = \"%s\"\n", path));
536 
537 	fp = new_fp();
538 	fp->fd = fd;
539 	fp->percent = percent;
540 	fp->name = file;
541 	fp->path = path;
542 	fp->parent = parent;
543 
544 	if ((isdir && !add_dir(fp)) ||
545 	    (!isdir &&
546 	     !is_fortfile(path, &fp->datfile, &fp->posfile, (parent != NULL))))
547 	{
548 		if (parent == NULL)
549 			fprintf(stderr,
550 				"fortune:%s not a fortune file or directory\n",
551 				path);
552 		if (was_malloc)
553 			free(path);
554 		do_free(fp->datfile);
555 		do_free(fp->posfile);
556 		free((char *) fp);
557 		do_free(offensive);
558 		return FALSE;
559 	}
560 	/*
561 	 * If the user said -a, we need to make this node a pointer to
562 	 * both files, if there are two.  We don't need to do this if
563 	 * we are scanning a directory, since the scan will pick up the
564 	 * -o file anyway.
565 	 */
566 	if (All_forts && parent == NULL && !is_off_name(path))
567 		all_forts(fp, offensive);
568 	if (*head == NULL)
569 		*head = *tail = fp;
570 	else if (fp->percent == NO_PROB) {
571 		(*tail)->next = fp;
572 		fp->prev = *tail;
573 		*tail = fp;
574 	}
575 	else {
576 		(*head)->prev = fp;
577 		fp->next = *head;
578 		*head = fp;
579 	}
580 #ifdef	OK_TO_WRITE_DISK
581 	fp->was_pos_file = (access(fp->posfile, W_OK) >= 0);
582 #endif	/* OK_TO_WRITE_DISK */
583 
584 	return TRUE;
585 }
586 
587 /*
588  * new_fp:
589  *	Return a pointer to an initialized new FILEDESC.
590  */
591 FILEDESC *
592 new_fp()
593 {
594 	FILEDESC	*fp;
595 
596 	fp = (FILEDESC *) do_malloc(sizeof *fp);
597 	fp->datfd = -1;
598 	fp->pos = POS_UNKNOWN;
599 	fp->inf = NULL;
600 	fp->fd = -1;
601 	fp->percent = NO_PROB;
602 	fp->read_tbl = FALSE;
603 	fp->next = NULL;
604 	fp->prev = NULL;
605 	fp->child = NULL;
606 	fp->parent = NULL;
607 	fp->datfile = NULL;
608 	fp->posfile = NULL;
609 	return fp;
610 }
611 
612 /*
613  * off_name:
614  *	Return a pointer to the offensive version of a file of this name.
615  */
616 char *
617 off_name(file)
618 char	*file;
619 {
620 	char	*new;
621 
622 	new = copy(file, (unsigned int) (strlen(file) + 2));
623 	return strcat(new, "-o");
624 }
625 
626 /*
627  * is_off_name:
628  *	Is the file an offensive-style name?
629  */
630 int
631 is_off_name(file)
632 char	*file;
633 {
634 	int	len;
635 
636 	len = strlen(file);
637 	return (len >= 3 && file[len - 2] == '-' && file[len - 1] == 'o');
638 }
639 
640 /*
641  * all_forts:
642  *	Modify a FILEDESC element to be the parent of two children if
643  *	there are two children to be a parent of.
644  */
645 void
646 all_forts(fp, offensive)
647 FILEDESC	*fp;
648 char			*offensive;
649 {
650 	char		*sp;
651 	FILEDESC	*scene, *obscene;
652 	int		fd;
653 	auto char		*datfile, *posfile;
654 
655 	if (fp->child != NULL)	/* this is a directory, not a file */
656 		return;
657 	if (!is_fortfile(offensive, &datfile, &posfile, FALSE))
658 		return;
659 	if ((fd = open(offensive, 0)) < 0)
660 		return;
661 	DPRINTF(1, (stderr, "adding \"%s\" because of -a\n", offensive));
662 	scene = new_fp();
663 	obscene = new_fp();
664 	*scene = *fp;
665 
666 	fp->num_children = 2;
667 	fp->child = scene;
668 	scene->next = obscene;
669 	obscene->next = NULL;
670 	scene->child = obscene->child = NULL;
671 	scene->parent = obscene->parent = fp;
672 
673 	fp->fd = -1;
674 	scene->percent = obscene->percent = NO_PROB;
675 
676 	obscene->fd = fd;
677 	obscene->inf = NULL;
678 	obscene->path = offensive;
679 	if ((sp = rindex(offensive, '/')) == NULL)
680 		obscene->name = offensive;
681 	else
682 		obscene->name = ++sp;
683 	obscene->datfile = datfile;
684 	obscene->posfile = posfile;
685 	obscene->read_tbl = FALSE;
686 #ifdef	OK_TO_WRITE_DISK
687 	obscene->was_pos_file = (access(obscene->posfile, W_OK) >= 0);
688 #endif	/* OK_TO_WRITE_DISK */
689 }
690 
691 /*
692  * add_dir:
693  *	Add the contents of an entire directory.
694  */
695 int
696 add_dir(fp)
697 FILEDESC	*fp;
698 {
699 	DIR		*dir;
700 	struct dirent	*dirent;
701 	auto FILEDESC		*tailp;
702 	auto char		*name;
703 
704 	(void) close(fp->fd);
705 	fp->fd = -1;
706 	if ((dir = opendir(fp->path)) == NULL) {
707 		perror(fp->path);
708 		return FALSE;
709 	}
710 	tailp = NULL;
711 	DPRINTF(1, (stderr, "adding dir \"%s\"\n", fp->path));
712 	fp->num_children = 0;
713 	while ((dirent = readdir(dir)) != NULL) {
714 		if ((name = strdup(dirent->d_name)) == NULL)
715 			err(1, "strdup failed");
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 }
1405