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