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