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